simplemde.js 572 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020
  1. /**
  2. * simplemde v1.11.2
  3. * Copyright Next Step Webs, Inc.
  4. * @link https://github.com/sparksuite/simplemde-markdown-editor
  5. * @link https://github.com/NextStepWebs/simplemde-markdown-editor
  6. * @license MIT
  7. */
  8. (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){
  9. 'use strict'
  10. exports.toByteArray = toByteArray
  11. exports.fromByteArray = fromByteArray
  12. var lookup = []
  13. var revLookup = []
  14. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  15. function init () {
  16. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  17. for (var i = 0, len = code.length; i < len; ++i) {
  18. lookup[i] = code[i]
  19. revLookup[code.charCodeAt(i)] = i
  20. }
  21. revLookup['-'.charCodeAt(0)] = 62
  22. revLookup['_'.charCodeAt(0)] = 63
  23. }
  24. init()
  25. function toByteArray (b64) {
  26. var i, j, l, tmp, placeHolders, arr
  27. var len = b64.length
  28. if (len % 4 > 0) {
  29. throw new Error('Invalid string. Length must be a multiple of 4')
  30. }
  31. // the number of equal signs (place holders)
  32. // if there are two placeholders, than the two characters before it
  33. // represent one byte
  34. // if there is only one, then the three characters before it represent 2 bytes
  35. // this is just a cheap hack to not do indexOf twice
  36. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  37. // base64 is 4/3 + up to two characters of the original data
  38. arr = new Arr(len * 3 / 4 - placeHolders)
  39. // if there are placeholders, only get up to the last complete 4 chars
  40. l = placeHolders > 0 ? len - 4 : len
  41. var L = 0
  42. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  43. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  44. arr[L++] = (tmp >> 16) & 0xFF
  45. arr[L++] = (tmp >> 8) & 0xFF
  46. arr[L++] = tmp & 0xFF
  47. }
  48. if (placeHolders === 2) {
  49. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  50. arr[L++] = tmp & 0xFF
  51. } else if (placeHolders === 1) {
  52. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  53. arr[L++] = (tmp >> 8) & 0xFF
  54. arr[L++] = tmp & 0xFF
  55. }
  56. return arr
  57. }
  58. function tripletToBase64 (num) {
  59. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  60. }
  61. function encodeChunk (uint8, start, end) {
  62. var tmp
  63. var output = []
  64. for (var i = start; i < end; i += 3) {
  65. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  66. output.push(tripletToBase64(tmp))
  67. }
  68. return output.join('')
  69. }
  70. function fromByteArray (uint8) {
  71. var tmp
  72. var len = uint8.length
  73. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  74. var output = ''
  75. var parts = []
  76. var maxChunkLength = 16383 // must be multiple of 3
  77. // go through the array every three bytes, we'll deal with trailing stuff later
  78. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  79. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  80. }
  81. // pad the end with zeros, but make sure to not forget the extra bytes
  82. if (extraBytes === 1) {
  83. tmp = uint8[len - 1]
  84. output += lookup[tmp >> 2]
  85. output += lookup[(tmp << 4) & 0x3F]
  86. output += '=='
  87. } else if (extraBytes === 2) {
  88. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  89. output += lookup[tmp >> 10]
  90. output += lookup[(tmp >> 4) & 0x3F]
  91. output += lookup[(tmp << 2) & 0x3F]
  92. output += '='
  93. }
  94. parts.push(output)
  95. return parts.join('')
  96. }
  97. },{}],2:[function(require,module,exports){
  98. },{}],3:[function(require,module,exports){
  99. (function (global){
  100. /*!
  101. * The buffer module from node.js, for the browser.
  102. *
  103. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  104. * @license MIT
  105. */
  106. /* eslint-disable no-proto */
  107. 'use strict'
  108. var base64 = require('base64-js')
  109. var ieee754 = require('ieee754')
  110. var isArray = require('isarray')
  111. exports.Buffer = Buffer
  112. exports.SlowBuffer = SlowBuffer
  113. exports.INSPECT_MAX_BYTES = 50
  114. /**
  115. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  116. * === true Use Uint8Array implementation (fastest)
  117. * === false Use Object implementation (most compatible, even IE6)
  118. *
  119. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  120. * Opera 11.6+, iOS 4.2+.
  121. *
  122. * Due to various browser bugs, sometimes the Object implementation will be used even
  123. * when the browser supports typed arrays.
  124. *
  125. * Note:
  126. *
  127. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  128. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  129. *
  130. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  131. *
  132. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  133. * incorrect length in some situations.
  134. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  135. * get the Object implementation, which is slower but behaves correctly.
  136. */
  137. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  138. ? global.TYPED_ARRAY_SUPPORT
  139. : typedArraySupport()
  140. /*
  141. * Export kMaxLength after typed array support is determined.
  142. */
  143. exports.kMaxLength = kMaxLength()
  144. function typedArraySupport () {
  145. try {
  146. var arr = new Uint8Array(1)
  147. arr.foo = function () { return 42 }
  148. return arr.foo() === 42 && // typed array instances can be augmented
  149. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  150. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  151. } catch (e) {
  152. return false
  153. }
  154. }
  155. function kMaxLength () {
  156. return Buffer.TYPED_ARRAY_SUPPORT
  157. ? 0x7fffffff
  158. : 0x3fffffff
  159. }
  160. function createBuffer (that, length) {
  161. if (kMaxLength() < length) {
  162. throw new RangeError('Invalid typed array length')
  163. }
  164. if (Buffer.TYPED_ARRAY_SUPPORT) {
  165. // Return an augmented `Uint8Array` instance, for best performance
  166. that = new Uint8Array(length)
  167. that.__proto__ = Buffer.prototype
  168. } else {
  169. // Fallback: Return an object instance of the Buffer class
  170. if (that === null) {
  171. that = new Buffer(length)
  172. }
  173. that.length = length
  174. }
  175. return that
  176. }
  177. /**
  178. * The Buffer constructor returns instances of `Uint8Array` that have their
  179. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  180. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  181. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  182. * returns a single octet.
  183. *
  184. * The `Uint8Array` prototype remains unmodified.
  185. */
  186. function Buffer (arg, encodingOrOffset, length) {
  187. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  188. return new Buffer(arg, encodingOrOffset, length)
  189. }
  190. // Common case.
  191. if (typeof arg === 'number') {
  192. if (typeof encodingOrOffset === 'string') {
  193. throw new Error(
  194. 'If encoding is specified then the first argument must be a string'
  195. )
  196. }
  197. return allocUnsafe(this, arg)
  198. }
  199. return from(this, arg, encodingOrOffset, length)
  200. }
  201. Buffer.poolSize = 8192 // not used by this implementation
  202. // TODO: Legacy, not needed anymore. Remove in next major version.
  203. Buffer._augment = function (arr) {
  204. arr.__proto__ = Buffer.prototype
  205. return arr
  206. }
  207. function from (that, value, encodingOrOffset, length) {
  208. if (typeof value === 'number') {
  209. throw new TypeError('"value" argument must not be a number')
  210. }
  211. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  212. return fromArrayBuffer(that, value, encodingOrOffset, length)
  213. }
  214. if (typeof value === 'string') {
  215. return fromString(that, value, encodingOrOffset)
  216. }
  217. return fromObject(that, value)
  218. }
  219. /**
  220. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  221. * if value is a number.
  222. * Buffer.from(str[, encoding])
  223. * Buffer.from(array)
  224. * Buffer.from(buffer)
  225. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  226. **/
  227. Buffer.from = function (value, encodingOrOffset, length) {
  228. return from(null, value, encodingOrOffset, length)
  229. }
  230. if (Buffer.TYPED_ARRAY_SUPPORT) {
  231. Buffer.prototype.__proto__ = Uint8Array.prototype
  232. Buffer.__proto__ = Uint8Array
  233. if (typeof Symbol !== 'undefined' && Symbol.species &&
  234. Buffer[Symbol.species] === Buffer) {
  235. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  236. Object.defineProperty(Buffer, Symbol.species, {
  237. value: null,
  238. configurable: true
  239. })
  240. }
  241. }
  242. function assertSize (size) {
  243. if (typeof size !== 'number') {
  244. throw new TypeError('"size" argument must be a number')
  245. }
  246. }
  247. function alloc (that, size, fill, encoding) {
  248. assertSize(size)
  249. if (size <= 0) {
  250. return createBuffer(that, size)
  251. }
  252. if (fill !== undefined) {
  253. // Only pay attention to encoding if it's a string. This
  254. // prevents accidentally sending in a number that would
  255. // be interpretted as a start offset.
  256. return typeof encoding === 'string'
  257. ? createBuffer(that, size).fill(fill, encoding)
  258. : createBuffer(that, size).fill(fill)
  259. }
  260. return createBuffer(that, size)
  261. }
  262. /**
  263. * Creates a new filled Buffer instance.
  264. * alloc(size[, fill[, encoding]])
  265. **/
  266. Buffer.alloc = function (size, fill, encoding) {
  267. return alloc(null, size, fill, encoding)
  268. }
  269. function allocUnsafe (that, size) {
  270. assertSize(size)
  271. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  272. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  273. for (var i = 0; i < size; i++) {
  274. that[i] = 0
  275. }
  276. }
  277. return that
  278. }
  279. /**
  280. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  281. * */
  282. Buffer.allocUnsafe = function (size) {
  283. return allocUnsafe(null, size)
  284. }
  285. /**
  286. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  287. */
  288. Buffer.allocUnsafeSlow = function (size) {
  289. return allocUnsafe(null, size)
  290. }
  291. function fromString (that, string, encoding) {
  292. if (typeof encoding !== 'string' || encoding === '') {
  293. encoding = 'utf8'
  294. }
  295. if (!Buffer.isEncoding(encoding)) {
  296. throw new TypeError('"encoding" must be a valid string encoding')
  297. }
  298. var length = byteLength(string, encoding) | 0
  299. that = createBuffer(that, length)
  300. that.write(string, encoding)
  301. return that
  302. }
  303. function fromArrayLike (that, array) {
  304. var length = checked(array.length) | 0
  305. that = createBuffer(that, length)
  306. for (var i = 0; i < length; i += 1) {
  307. that[i] = array[i] & 255
  308. }
  309. return that
  310. }
  311. function fromArrayBuffer (that, array, byteOffset, length) {
  312. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  313. if (byteOffset < 0 || array.byteLength < byteOffset) {
  314. throw new RangeError('\'offset\' is out of bounds')
  315. }
  316. if (array.byteLength < byteOffset + (length || 0)) {
  317. throw new RangeError('\'length\' is out of bounds')
  318. }
  319. if (length === undefined) {
  320. array = new Uint8Array(array, byteOffset)
  321. } else {
  322. array = new Uint8Array(array, byteOffset, length)
  323. }
  324. if (Buffer.TYPED_ARRAY_SUPPORT) {
  325. // Return an augmented `Uint8Array` instance, for best performance
  326. that = array
  327. that.__proto__ = Buffer.prototype
  328. } else {
  329. // Fallback: Return an object instance of the Buffer class
  330. that = fromArrayLike(that, array)
  331. }
  332. return that
  333. }
  334. function fromObject (that, obj) {
  335. if (Buffer.isBuffer(obj)) {
  336. var len = checked(obj.length) | 0
  337. that = createBuffer(that, len)
  338. if (that.length === 0) {
  339. return that
  340. }
  341. obj.copy(that, 0, 0, len)
  342. return that
  343. }
  344. if (obj) {
  345. if ((typeof ArrayBuffer !== 'undefined' &&
  346. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  347. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  348. return createBuffer(that, 0)
  349. }
  350. return fromArrayLike(that, obj)
  351. }
  352. if (obj.type === 'Buffer' && isArray(obj.data)) {
  353. return fromArrayLike(that, obj.data)
  354. }
  355. }
  356. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  357. }
  358. function checked (length) {
  359. // Note: cannot use `length < kMaxLength` here because that fails when
  360. // length is NaN (which is otherwise coerced to zero.)
  361. if (length >= kMaxLength()) {
  362. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  363. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  364. }
  365. return length | 0
  366. }
  367. function SlowBuffer (length) {
  368. if (+length != length) { // eslint-disable-line eqeqeq
  369. length = 0
  370. }
  371. return Buffer.alloc(+length)
  372. }
  373. Buffer.isBuffer = function isBuffer (b) {
  374. return !!(b != null && b._isBuffer)
  375. }
  376. Buffer.compare = function compare (a, b) {
  377. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  378. throw new TypeError('Arguments must be Buffers')
  379. }
  380. if (a === b) return 0
  381. var x = a.length
  382. var y = b.length
  383. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  384. if (a[i] !== b[i]) {
  385. x = a[i]
  386. y = b[i]
  387. break
  388. }
  389. }
  390. if (x < y) return -1
  391. if (y < x) return 1
  392. return 0
  393. }
  394. Buffer.isEncoding = function isEncoding (encoding) {
  395. switch (String(encoding).toLowerCase()) {
  396. case 'hex':
  397. case 'utf8':
  398. case 'utf-8':
  399. case 'ascii':
  400. case 'binary':
  401. case 'base64':
  402. case 'raw':
  403. case 'ucs2':
  404. case 'ucs-2':
  405. case 'utf16le':
  406. case 'utf-16le':
  407. return true
  408. default:
  409. return false
  410. }
  411. }
  412. Buffer.concat = function concat (list, length) {
  413. if (!isArray(list)) {
  414. throw new TypeError('"list" argument must be an Array of Buffers')
  415. }
  416. if (list.length === 0) {
  417. return Buffer.alloc(0)
  418. }
  419. var i
  420. if (length === undefined) {
  421. length = 0
  422. for (i = 0; i < list.length; i++) {
  423. length += list[i].length
  424. }
  425. }
  426. var buffer = Buffer.allocUnsafe(length)
  427. var pos = 0
  428. for (i = 0; i < list.length; i++) {
  429. var buf = list[i]
  430. if (!Buffer.isBuffer(buf)) {
  431. throw new TypeError('"list" argument must be an Array of Buffers')
  432. }
  433. buf.copy(buffer, pos)
  434. pos += buf.length
  435. }
  436. return buffer
  437. }
  438. function byteLength (string, encoding) {
  439. if (Buffer.isBuffer(string)) {
  440. return string.length
  441. }
  442. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  443. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  444. return string.byteLength
  445. }
  446. if (typeof string !== 'string') {
  447. string = '' + string
  448. }
  449. var len = string.length
  450. if (len === 0) return 0
  451. // Use a for loop to avoid recursion
  452. var loweredCase = false
  453. for (;;) {
  454. switch (encoding) {
  455. case 'ascii':
  456. case 'binary':
  457. // Deprecated
  458. case 'raw':
  459. case 'raws':
  460. return len
  461. case 'utf8':
  462. case 'utf-8':
  463. case undefined:
  464. return utf8ToBytes(string).length
  465. case 'ucs2':
  466. case 'ucs-2':
  467. case 'utf16le':
  468. case 'utf-16le':
  469. return len * 2
  470. case 'hex':
  471. return len >>> 1
  472. case 'base64':
  473. return base64ToBytes(string).length
  474. default:
  475. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  476. encoding = ('' + encoding).toLowerCase()
  477. loweredCase = true
  478. }
  479. }
  480. }
  481. Buffer.byteLength = byteLength
  482. function slowToString (encoding, start, end) {
  483. var loweredCase = false
  484. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  485. // property of a typed array.
  486. // This behaves neither like String nor Uint8Array in that we set start/end
  487. // to their upper/lower bounds if the value passed is out of range.
  488. // undefined is handled specially as per ECMA-262 6th Edition,
  489. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  490. if (start === undefined || start < 0) {
  491. start = 0
  492. }
  493. // Return early if start > this.length. Done here to prevent potential uint32
  494. // coercion fail below.
  495. if (start > this.length) {
  496. return ''
  497. }
  498. if (end === undefined || end > this.length) {
  499. end = this.length
  500. }
  501. if (end <= 0) {
  502. return ''
  503. }
  504. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  505. end >>>= 0
  506. start >>>= 0
  507. if (end <= start) {
  508. return ''
  509. }
  510. if (!encoding) encoding = 'utf8'
  511. while (true) {
  512. switch (encoding) {
  513. case 'hex':
  514. return hexSlice(this, start, end)
  515. case 'utf8':
  516. case 'utf-8':
  517. return utf8Slice(this, start, end)
  518. case 'ascii':
  519. return asciiSlice(this, start, end)
  520. case 'binary':
  521. return binarySlice(this, start, end)
  522. case 'base64':
  523. return base64Slice(this, start, end)
  524. case 'ucs2':
  525. case 'ucs-2':
  526. case 'utf16le':
  527. case 'utf-16le':
  528. return utf16leSlice(this, start, end)
  529. default:
  530. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  531. encoding = (encoding + '').toLowerCase()
  532. loweredCase = true
  533. }
  534. }
  535. }
  536. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  537. // Buffer instances.
  538. Buffer.prototype._isBuffer = true
  539. function swap (b, n, m) {
  540. var i = b[n]
  541. b[n] = b[m]
  542. b[m] = i
  543. }
  544. Buffer.prototype.swap16 = function swap16 () {
  545. var len = this.length
  546. if (len % 2 !== 0) {
  547. throw new RangeError('Buffer size must be a multiple of 16-bits')
  548. }
  549. for (var i = 0; i < len; i += 2) {
  550. swap(this, i, i + 1)
  551. }
  552. return this
  553. }
  554. Buffer.prototype.swap32 = function swap32 () {
  555. var len = this.length
  556. if (len % 4 !== 0) {
  557. throw new RangeError('Buffer size must be a multiple of 32-bits')
  558. }
  559. for (var i = 0; i < len; i += 4) {
  560. swap(this, i, i + 3)
  561. swap(this, i + 1, i + 2)
  562. }
  563. return this
  564. }
  565. Buffer.prototype.toString = function toString () {
  566. var length = this.length | 0
  567. if (length === 0) return ''
  568. if (arguments.length === 0) return utf8Slice(this, 0, length)
  569. return slowToString.apply(this, arguments)
  570. }
  571. Buffer.prototype.equals = function equals (b) {
  572. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  573. if (this === b) return true
  574. return Buffer.compare(this, b) === 0
  575. }
  576. Buffer.prototype.inspect = function inspect () {
  577. var str = ''
  578. var max = exports.INSPECT_MAX_BYTES
  579. if (this.length > 0) {
  580. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  581. if (this.length > max) str += ' ... '
  582. }
  583. return '<Buffer ' + str + '>'
  584. }
  585. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  586. if (!Buffer.isBuffer(target)) {
  587. throw new TypeError('Argument must be a Buffer')
  588. }
  589. if (start === undefined) {
  590. start = 0
  591. }
  592. if (end === undefined) {
  593. end = target ? target.length : 0
  594. }
  595. if (thisStart === undefined) {
  596. thisStart = 0
  597. }
  598. if (thisEnd === undefined) {
  599. thisEnd = this.length
  600. }
  601. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  602. throw new RangeError('out of range index')
  603. }
  604. if (thisStart >= thisEnd && start >= end) {
  605. return 0
  606. }
  607. if (thisStart >= thisEnd) {
  608. return -1
  609. }
  610. if (start >= end) {
  611. return 1
  612. }
  613. start >>>= 0
  614. end >>>= 0
  615. thisStart >>>= 0
  616. thisEnd >>>= 0
  617. if (this === target) return 0
  618. var x = thisEnd - thisStart
  619. var y = end - start
  620. var len = Math.min(x, y)
  621. var thisCopy = this.slice(thisStart, thisEnd)
  622. var targetCopy = target.slice(start, end)
  623. for (var i = 0; i < len; ++i) {
  624. if (thisCopy[i] !== targetCopy[i]) {
  625. x = thisCopy[i]
  626. y = targetCopy[i]
  627. break
  628. }
  629. }
  630. if (x < y) return -1
  631. if (y < x) return 1
  632. return 0
  633. }
  634. function arrayIndexOf (arr, val, byteOffset, encoding) {
  635. var indexSize = 1
  636. var arrLength = arr.length
  637. var valLength = val.length
  638. if (encoding !== undefined) {
  639. encoding = String(encoding).toLowerCase()
  640. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  641. encoding === 'utf16le' || encoding === 'utf-16le') {
  642. if (arr.length < 2 || val.length < 2) {
  643. return -1
  644. }
  645. indexSize = 2
  646. arrLength /= 2
  647. valLength /= 2
  648. byteOffset /= 2
  649. }
  650. }
  651. function read (buf, i) {
  652. if (indexSize === 1) {
  653. return buf[i]
  654. } else {
  655. return buf.readUInt16BE(i * indexSize)
  656. }
  657. }
  658. var foundIndex = -1
  659. for (var i = 0; byteOffset + i < arrLength; i++) {
  660. if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  661. if (foundIndex === -1) foundIndex = i
  662. if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize
  663. } else {
  664. if (foundIndex !== -1) i -= i - foundIndex
  665. foundIndex = -1
  666. }
  667. }
  668. return -1
  669. }
  670. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  671. if (typeof byteOffset === 'string') {
  672. encoding = byteOffset
  673. byteOffset = 0
  674. } else if (byteOffset > 0x7fffffff) {
  675. byteOffset = 0x7fffffff
  676. } else if (byteOffset < -0x80000000) {
  677. byteOffset = -0x80000000
  678. }
  679. byteOffset >>= 0
  680. if (this.length === 0) return -1
  681. if (byteOffset >= this.length) return -1
  682. // Negative offsets start from the end of the buffer
  683. if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  684. if (typeof val === 'string') {
  685. val = Buffer.from(val, encoding)
  686. }
  687. if (Buffer.isBuffer(val)) {
  688. // special case: looking for empty string/buffer always fails
  689. if (val.length === 0) {
  690. return -1
  691. }
  692. return arrayIndexOf(this, val, byteOffset, encoding)
  693. }
  694. if (typeof val === 'number') {
  695. if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
  696. return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
  697. }
  698. return arrayIndexOf(this, [ val ], byteOffset, encoding)
  699. }
  700. throw new TypeError('val must be string, number or Buffer')
  701. }
  702. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  703. return this.indexOf(val, byteOffset, encoding) !== -1
  704. }
  705. function hexWrite (buf, string, offset, length) {
  706. offset = Number(offset) || 0
  707. var remaining = buf.length - offset
  708. if (!length) {
  709. length = remaining
  710. } else {
  711. length = Number(length)
  712. if (length > remaining) {
  713. length = remaining
  714. }
  715. }
  716. // must be an even number of digits
  717. var strLen = string.length
  718. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  719. if (length > strLen / 2) {
  720. length = strLen / 2
  721. }
  722. for (var i = 0; i < length; i++) {
  723. var parsed = parseInt(string.substr(i * 2, 2), 16)
  724. if (isNaN(parsed)) return i
  725. buf[offset + i] = parsed
  726. }
  727. return i
  728. }
  729. function utf8Write (buf, string, offset, length) {
  730. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  731. }
  732. function asciiWrite (buf, string, offset, length) {
  733. return blitBuffer(asciiToBytes(string), buf, offset, length)
  734. }
  735. function binaryWrite (buf, string, offset, length) {
  736. return asciiWrite(buf, string, offset, length)
  737. }
  738. function base64Write (buf, string, offset, length) {
  739. return blitBuffer(base64ToBytes(string), buf, offset, length)
  740. }
  741. function ucs2Write (buf, string, offset, length) {
  742. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  743. }
  744. Buffer.prototype.write = function write (string, offset, length, encoding) {
  745. // Buffer#write(string)
  746. if (offset === undefined) {
  747. encoding = 'utf8'
  748. length = this.length
  749. offset = 0
  750. // Buffer#write(string, encoding)
  751. } else if (length === undefined && typeof offset === 'string') {
  752. encoding = offset
  753. length = this.length
  754. offset = 0
  755. // Buffer#write(string, offset[, length][, encoding])
  756. } else if (isFinite(offset)) {
  757. offset = offset | 0
  758. if (isFinite(length)) {
  759. length = length | 0
  760. if (encoding === undefined) encoding = 'utf8'
  761. } else {
  762. encoding = length
  763. length = undefined
  764. }
  765. // legacy write(string, encoding, offset, length) - remove in v0.13
  766. } else {
  767. throw new Error(
  768. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  769. )
  770. }
  771. var remaining = this.length - offset
  772. if (length === undefined || length > remaining) length = remaining
  773. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  774. throw new RangeError('Attempt to write outside buffer bounds')
  775. }
  776. if (!encoding) encoding = 'utf8'
  777. var loweredCase = false
  778. for (;;) {
  779. switch (encoding) {
  780. case 'hex':
  781. return hexWrite(this, string, offset, length)
  782. case 'utf8':
  783. case 'utf-8':
  784. return utf8Write(this, string, offset, length)
  785. case 'ascii':
  786. return asciiWrite(this, string, offset, length)
  787. case 'binary':
  788. return binaryWrite(this, string, offset, length)
  789. case 'base64':
  790. // Warning: maxLength not taken into account in base64Write
  791. return base64Write(this, string, offset, length)
  792. case 'ucs2':
  793. case 'ucs-2':
  794. case 'utf16le':
  795. case 'utf-16le':
  796. return ucs2Write(this, string, offset, length)
  797. default:
  798. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  799. encoding = ('' + encoding).toLowerCase()
  800. loweredCase = true
  801. }
  802. }
  803. }
  804. Buffer.prototype.toJSON = function toJSON () {
  805. return {
  806. type: 'Buffer',
  807. data: Array.prototype.slice.call(this._arr || this, 0)
  808. }
  809. }
  810. function base64Slice (buf, start, end) {
  811. if (start === 0 && end === buf.length) {
  812. return base64.fromByteArray(buf)
  813. } else {
  814. return base64.fromByteArray(buf.slice(start, end))
  815. }
  816. }
  817. function utf8Slice (buf, start, end) {
  818. end = Math.min(buf.length, end)
  819. var res = []
  820. var i = start
  821. while (i < end) {
  822. var firstByte = buf[i]
  823. var codePoint = null
  824. var bytesPerSequence = (firstByte > 0xEF) ? 4
  825. : (firstByte > 0xDF) ? 3
  826. : (firstByte > 0xBF) ? 2
  827. : 1
  828. if (i + bytesPerSequence <= end) {
  829. var secondByte, thirdByte, fourthByte, tempCodePoint
  830. switch (bytesPerSequence) {
  831. case 1:
  832. if (firstByte < 0x80) {
  833. codePoint = firstByte
  834. }
  835. break
  836. case 2:
  837. secondByte = buf[i + 1]
  838. if ((secondByte & 0xC0) === 0x80) {
  839. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  840. if (tempCodePoint > 0x7F) {
  841. codePoint = tempCodePoint
  842. }
  843. }
  844. break
  845. case 3:
  846. secondByte = buf[i + 1]
  847. thirdByte = buf[i + 2]
  848. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  849. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  850. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  851. codePoint = tempCodePoint
  852. }
  853. }
  854. break
  855. case 4:
  856. secondByte = buf[i + 1]
  857. thirdByte = buf[i + 2]
  858. fourthByte = buf[i + 3]
  859. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  860. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  861. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  862. codePoint = tempCodePoint
  863. }
  864. }
  865. }
  866. }
  867. if (codePoint === null) {
  868. // we did not generate a valid codePoint so insert a
  869. // replacement char (U+FFFD) and advance only 1 byte
  870. codePoint = 0xFFFD
  871. bytesPerSequence = 1
  872. } else if (codePoint > 0xFFFF) {
  873. // encode to utf16 (surrogate pair dance)
  874. codePoint -= 0x10000
  875. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  876. codePoint = 0xDC00 | codePoint & 0x3FF
  877. }
  878. res.push(codePoint)
  879. i += bytesPerSequence
  880. }
  881. return decodeCodePointsArray(res)
  882. }
  883. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  884. // the lowest limit is Chrome, with 0x10000 args.
  885. // We go 1 magnitude less, for safety
  886. var MAX_ARGUMENTS_LENGTH = 0x1000
  887. function decodeCodePointsArray (codePoints) {
  888. var len = codePoints.length
  889. if (len <= MAX_ARGUMENTS_LENGTH) {
  890. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  891. }
  892. // Decode in chunks to avoid "call stack size exceeded".
  893. var res = ''
  894. var i = 0
  895. while (i < len) {
  896. res += String.fromCharCode.apply(
  897. String,
  898. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  899. )
  900. }
  901. return res
  902. }
  903. function asciiSlice (buf, start, end) {
  904. var ret = ''
  905. end = Math.min(buf.length, end)
  906. for (var i = start; i < end; i++) {
  907. ret += String.fromCharCode(buf[i] & 0x7F)
  908. }
  909. return ret
  910. }
  911. function binarySlice (buf, start, end) {
  912. var ret = ''
  913. end = Math.min(buf.length, end)
  914. for (var i = start; i < end; i++) {
  915. ret += String.fromCharCode(buf[i])
  916. }
  917. return ret
  918. }
  919. function hexSlice (buf, start, end) {
  920. var len = buf.length
  921. if (!start || start < 0) start = 0
  922. if (!end || end < 0 || end > len) end = len
  923. var out = ''
  924. for (var i = start; i < end; i++) {
  925. out += toHex(buf[i])
  926. }
  927. return out
  928. }
  929. function utf16leSlice (buf, start, end) {
  930. var bytes = buf.slice(start, end)
  931. var res = ''
  932. for (var i = 0; i < bytes.length; i += 2) {
  933. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  934. }
  935. return res
  936. }
  937. Buffer.prototype.slice = function slice (start, end) {
  938. var len = this.length
  939. start = ~~start
  940. end = end === undefined ? len : ~~end
  941. if (start < 0) {
  942. start += len
  943. if (start < 0) start = 0
  944. } else if (start > len) {
  945. start = len
  946. }
  947. if (end < 0) {
  948. end += len
  949. if (end < 0) end = 0
  950. } else if (end > len) {
  951. end = len
  952. }
  953. if (end < start) end = start
  954. var newBuf
  955. if (Buffer.TYPED_ARRAY_SUPPORT) {
  956. newBuf = this.subarray(start, end)
  957. newBuf.__proto__ = Buffer.prototype
  958. } else {
  959. var sliceLen = end - start
  960. newBuf = new Buffer(sliceLen, undefined)
  961. for (var i = 0; i < sliceLen; i++) {
  962. newBuf[i] = this[i + start]
  963. }
  964. }
  965. return newBuf
  966. }
  967. /*
  968. * Need to make sure that buffer isn't trying to write out of bounds.
  969. */
  970. function checkOffset (offset, ext, length) {
  971. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  972. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  973. }
  974. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  975. offset = offset | 0
  976. byteLength = byteLength | 0
  977. if (!noAssert) checkOffset(offset, byteLength, this.length)
  978. var val = this[offset]
  979. var mul = 1
  980. var i = 0
  981. while (++i < byteLength && (mul *= 0x100)) {
  982. val += this[offset + i] * mul
  983. }
  984. return val
  985. }
  986. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  987. offset = offset | 0
  988. byteLength = byteLength | 0
  989. if (!noAssert) {
  990. checkOffset(offset, byteLength, this.length)
  991. }
  992. var val = this[offset + --byteLength]
  993. var mul = 1
  994. while (byteLength > 0 && (mul *= 0x100)) {
  995. val += this[offset + --byteLength] * mul
  996. }
  997. return val
  998. }
  999. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1000. if (!noAssert) checkOffset(offset, 1, this.length)
  1001. return this[offset]
  1002. }
  1003. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1004. if (!noAssert) checkOffset(offset, 2, this.length)
  1005. return this[offset] | (this[offset + 1] << 8)
  1006. }
  1007. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1008. if (!noAssert) checkOffset(offset, 2, this.length)
  1009. return (this[offset] << 8) | this[offset + 1]
  1010. }
  1011. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1012. if (!noAssert) checkOffset(offset, 4, this.length)
  1013. return ((this[offset]) |
  1014. (this[offset + 1] << 8) |
  1015. (this[offset + 2] << 16)) +
  1016. (this[offset + 3] * 0x1000000)
  1017. }
  1018. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1019. if (!noAssert) checkOffset(offset, 4, this.length)
  1020. return (this[offset] * 0x1000000) +
  1021. ((this[offset + 1] << 16) |
  1022. (this[offset + 2] << 8) |
  1023. this[offset + 3])
  1024. }
  1025. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1026. offset = offset | 0
  1027. byteLength = byteLength | 0
  1028. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1029. var val = this[offset]
  1030. var mul = 1
  1031. var i = 0
  1032. while (++i < byteLength && (mul *= 0x100)) {
  1033. val += this[offset + i] * mul
  1034. }
  1035. mul *= 0x80
  1036. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1037. return val
  1038. }
  1039. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1040. offset = offset | 0
  1041. byteLength = byteLength | 0
  1042. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1043. var i = byteLength
  1044. var mul = 1
  1045. var val = this[offset + --i]
  1046. while (i > 0 && (mul *= 0x100)) {
  1047. val += this[offset + --i] * mul
  1048. }
  1049. mul *= 0x80
  1050. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1051. return val
  1052. }
  1053. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1054. if (!noAssert) checkOffset(offset, 1, this.length)
  1055. if (!(this[offset] & 0x80)) return (this[offset])
  1056. return ((0xff - this[offset] + 1) * -1)
  1057. }
  1058. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1059. if (!noAssert) checkOffset(offset, 2, this.length)
  1060. var val = this[offset] | (this[offset + 1] << 8)
  1061. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1062. }
  1063. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1064. if (!noAssert) checkOffset(offset, 2, this.length)
  1065. var val = this[offset + 1] | (this[offset] << 8)
  1066. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1067. }
  1068. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1069. if (!noAssert) checkOffset(offset, 4, this.length)
  1070. return (this[offset]) |
  1071. (this[offset + 1] << 8) |
  1072. (this[offset + 2] << 16) |
  1073. (this[offset + 3] << 24)
  1074. }
  1075. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1076. if (!noAssert) checkOffset(offset, 4, this.length)
  1077. return (this[offset] << 24) |
  1078. (this[offset + 1] << 16) |
  1079. (this[offset + 2] << 8) |
  1080. (this[offset + 3])
  1081. }
  1082. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1083. if (!noAssert) checkOffset(offset, 4, this.length)
  1084. return ieee754.read(this, offset, true, 23, 4)
  1085. }
  1086. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1087. if (!noAssert) checkOffset(offset, 4, this.length)
  1088. return ieee754.read(this, offset, false, 23, 4)
  1089. }
  1090. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1091. if (!noAssert) checkOffset(offset, 8, this.length)
  1092. return ieee754.read(this, offset, true, 52, 8)
  1093. }
  1094. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1095. if (!noAssert) checkOffset(offset, 8, this.length)
  1096. return ieee754.read(this, offset, false, 52, 8)
  1097. }
  1098. function checkInt (buf, value, offset, ext, max, min) {
  1099. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1100. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1101. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1102. }
  1103. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1104. value = +value
  1105. offset = offset | 0
  1106. byteLength = byteLength | 0
  1107. if (!noAssert) {
  1108. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1109. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1110. }
  1111. var mul = 1
  1112. var i = 0
  1113. this[offset] = value & 0xFF
  1114. while (++i < byteLength && (mul *= 0x100)) {
  1115. this[offset + i] = (value / mul) & 0xFF
  1116. }
  1117. return offset + byteLength
  1118. }
  1119. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1120. value = +value
  1121. offset = offset | 0
  1122. byteLength = byteLength | 0
  1123. if (!noAssert) {
  1124. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1125. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1126. }
  1127. var i = byteLength - 1
  1128. var mul = 1
  1129. this[offset + i] = value & 0xFF
  1130. while (--i >= 0 && (mul *= 0x100)) {
  1131. this[offset + i] = (value / mul) & 0xFF
  1132. }
  1133. return offset + byteLength
  1134. }
  1135. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1136. value = +value
  1137. offset = offset | 0
  1138. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1139. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1140. this[offset] = (value & 0xff)
  1141. return offset + 1
  1142. }
  1143. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1144. if (value < 0) value = 0xffff + value + 1
  1145. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  1146. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1147. (littleEndian ? i : 1 - i) * 8
  1148. }
  1149. }
  1150. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1151. value = +value
  1152. offset = offset | 0
  1153. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1154. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1155. this[offset] = (value & 0xff)
  1156. this[offset + 1] = (value >>> 8)
  1157. } else {
  1158. objectWriteUInt16(this, value, offset, true)
  1159. }
  1160. return offset + 2
  1161. }
  1162. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1163. value = +value
  1164. offset = offset | 0
  1165. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1166. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1167. this[offset] = (value >>> 8)
  1168. this[offset + 1] = (value & 0xff)
  1169. } else {
  1170. objectWriteUInt16(this, value, offset, false)
  1171. }
  1172. return offset + 2
  1173. }
  1174. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1175. if (value < 0) value = 0xffffffff + value + 1
  1176. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  1177. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1178. }
  1179. }
  1180. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1181. value = +value
  1182. offset = offset | 0
  1183. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1184. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1185. this[offset + 3] = (value >>> 24)
  1186. this[offset + 2] = (value >>> 16)
  1187. this[offset + 1] = (value >>> 8)
  1188. this[offset] = (value & 0xff)
  1189. } else {
  1190. objectWriteUInt32(this, value, offset, true)
  1191. }
  1192. return offset + 4
  1193. }
  1194. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1195. value = +value
  1196. offset = offset | 0
  1197. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1198. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1199. this[offset] = (value >>> 24)
  1200. this[offset + 1] = (value >>> 16)
  1201. this[offset + 2] = (value >>> 8)
  1202. this[offset + 3] = (value & 0xff)
  1203. } else {
  1204. objectWriteUInt32(this, value, offset, false)
  1205. }
  1206. return offset + 4
  1207. }
  1208. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1209. value = +value
  1210. offset = offset | 0
  1211. if (!noAssert) {
  1212. var limit = Math.pow(2, 8 * byteLength - 1)
  1213. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1214. }
  1215. var i = 0
  1216. var mul = 1
  1217. var sub = 0
  1218. this[offset] = value & 0xFF
  1219. while (++i < byteLength && (mul *= 0x100)) {
  1220. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1221. sub = 1
  1222. }
  1223. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1224. }
  1225. return offset + byteLength
  1226. }
  1227. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1228. value = +value
  1229. offset = offset | 0
  1230. if (!noAssert) {
  1231. var limit = Math.pow(2, 8 * byteLength - 1)
  1232. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1233. }
  1234. var i = byteLength - 1
  1235. var mul = 1
  1236. var sub = 0
  1237. this[offset + i] = value & 0xFF
  1238. while (--i >= 0 && (mul *= 0x100)) {
  1239. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1240. sub = 1
  1241. }
  1242. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1243. }
  1244. return offset + byteLength
  1245. }
  1246. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1247. value = +value
  1248. offset = offset | 0
  1249. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1250. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1251. if (value < 0) value = 0xff + value + 1
  1252. this[offset] = (value & 0xff)
  1253. return offset + 1
  1254. }
  1255. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1256. value = +value
  1257. offset = offset | 0
  1258. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1259. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1260. this[offset] = (value & 0xff)
  1261. this[offset + 1] = (value >>> 8)
  1262. } else {
  1263. objectWriteUInt16(this, value, offset, true)
  1264. }
  1265. return offset + 2
  1266. }
  1267. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1268. value = +value
  1269. offset = offset | 0
  1270. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1271. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1272. this[offset] = (value >>> 8)
  1273. this[offset + 1] = (value & 0xff)
  1274. } else {
  1275. objectWriteUInt16(this, value, offset, false)
  1276. }
  1277. return offset + 2
  1278. }
  1279. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1280. value = +value
  1281. offset = offset | 0
  1282. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1283. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1284. this[offset] = (value & 0xff)
  1285. this[offset + 1] = (value >>> 8)
  1286. this[offset + 2] = (value >>> 16)
  1287. this[offset + 3] = (value >>> 24)
  1288. } else {
  1289. objectWriteUInt32(this, value, offset, true)
  1290. }
  1291. return offset + 4
  1292. }
  1293. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1294. value = +value
  1295. offset = offset | 0
  1296. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1297. if (value < 0) value = 0xffffffff + value + 1
  1298. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1299. this[offset] = (value >>> 24)
  1300. this[offset + 1] = (value >>> 16)
  1301. this[offset + 2] = (value >>> 8)
  1302. this[offset + 3] = (value & 0xff)
  1303. } else {
  1304. objectWriteUInt32(this, value, offset, false)
  1305. }
  1306. return offset + 4
  1307. }
  1308. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1309. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1310. if (offset < 0) throw new RangeError('Index out of range')
  1311. }
  1312. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1313. if (!noAssert) {
  1314. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1315. }
  1316. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1317. return offset + 4
  1318. }
  1319. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1320. return writeFloat(this, value, offset, true, noAssert)
  1321. }
  1322. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1323. return writeFloat(this, value, offset, false, noAssert)
  1324. }
  1325. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1326. if (!noAssert) {
  1327. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1328. }
  1329. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1330. return offset + 8
  1331. }
  1332. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1333. return writeDouble(this, value, offset, true, noAssert)
  1334. }
  1335. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1336. return writeDouble(this, value, offset, false, noAssert)
  1337. }
  1338. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1339. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1340. if (!start) start = 0
  1341. if (!end && end !== 0) end = this.length
  1342. if (targetStart >= target.length) targetStart = target.length
  1343. if (!targetStart) targetStart = 0
  1344. if (end > 0 && end < start) end = start
  1345. // Copy 0 bytes; we're done
  1346. if (end === start) return 0
  1347. if (target.length === 0 || this.length === 0) return 0
  1348. // Fatal error conditions
  1349. if (targetStart < 0) {
  1350. throw new RangeError('targetStart out of bounds')
  1351. }
  1352. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1353. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1354. // Are we oob?
  1355. if (end > this.length) end = this.length
  1356. if (target.length - targetStart < end - start) {
  1357. end = target.length - targetStart + start
  1358. }
  1359. var len = end - start
  1360. var i
  1361. if (this === target && start < targetStart && targetStart < end) {
  1362. // descending copy from end
  1363. for (i = len - 1; i >= 0; i--) {
  1364. target[i + targetStart] = this[i + start]
  1365. }
  1366. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1367. // ascending copy from start
  1368. for (i = 0; i < len; i++) {
  1369. target[i + targetStart] = this[i + start]
  1370. }
  1371. } else {
  1372. Uint8Array.prototype.set.call(
  1373. target,
  1374. this.subarray(start, start + len),
  1375. targetStart
  1376. )
  1377. }
  1378. return len
  1379. }
  1380. // Usage:
  1381. // buffer.fill(number[, offset[, end]])
  1382. // buffer.fill(buffer[, offset[, end]])
  1383. // buffer.fill(string[, offset[, end]][, encoding])
  1384. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1385. // Handle string cases:
  1386. if (typeof val === 'string') {
  1387. if (typeof start === 'string') {
  1388. encoding = start
  1389. start = 0
  1390. end = this.length
  1391. } else if (typeof end === 'string') {
  1392. encoding = end
  1393. end = this.length
  1394. }
  1395. if (val.length === 1) {
  1396. var code = val.charCodeAt(0)
  1397. if (code < 256) {
  1398. val = code
  1399. }
  1400. }
  1401. if (encoding !== undefined && typeof encoding !== 'string') {
  1402. throw new TypeError('encoding must be a string')
  1403. }
  1404. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1405. throw new TypeError('Unknown encoding: ' + encoding)
  1406. }
  1407. } else if (typeof val === 'number') {
  1408. val = val & 255
  1409. }
  1410. // Invalid ranges are not set to a default, so can range check early.
  1411. if (start < 0 || this.length < start || this.length < end) {
  1412. throw new RangeError('Out of range index')
  1413. }
  1414. if (end <= start) {
  1415. return this
  1416. }
  1417. start = start >>> 0
  1418. end = end === undefined ? this.length : end >>> 0
  1419. if (!val) val = 0
  1420. var i
  1421. if (typeof val === 'number') {
  1422. for (i = start; i < end; i++) {
  1423. this[i] = val
  1424. }
  1425. } else {
  1426. var bytes = Buffer.isBuffer(val)
  1427. ? val
  1428. : utf8ToBytes(new Buffer(val, encoding).toString())
  1429. var len = bytes.length
  1430. for (i = 0; i < end - start; i++) {
  1431. this[i + start] = bytes[i % len]
  1432. }
  1433. }
  1434. return this
  1435. }
  1436. // HELPER FUNCTIONS
  1437. // ================
  1438. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1439. function base64clean (str) {
  1440. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1441. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1442. // Node converts strings with length < 2 to ''
  1443. if (str.length < 2) return ''
  1444. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1445. while (str.length % 4 !== 0) {
  1446. str = str + '='
  1447. }
  1448. return str
  1449. }
  1450. function stringtrim (str) {
  1451. if (str.trim) return str.trim()
  1452. return str.replace(/^\s+|\s+$/g, '')
  1453. }
  1454. function toHex (n) {
  1455. if (n < 16) return '0' + n.toString(16)
  1456. return n.toString(16)
  1457. }
  1458. function utf8ToBytes (string, units) {
  1459. units = units || Infinity
  1460. var codePoint
  1461. var length = string.length
  1462. var leadSurrogate = null
  1463. var bytes = []
  1464. for (var i = 0; i < length; i++) {
  1465. codePoint = string.charCodeAt(i)
  1466. // is surrogate component
  1467. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1468. // last char was a lead
  1469. if (!leadSurrogate) {
  1470. // no lead yet
  1471. if (codePoint > 0xDBFF) {
  1472. // unexpected trail
  1473. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1474. continue
  1475. } else if (i + 1 === length) {
  1476. // unpaired lead
  1477. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1478. continue
  1479. }
  1480. // valid lead
  1481. leadSurrogate = codePoint
  1482. continue
  1483. }
  1484. // 2 leads in a row
  1485. if (codePoint < 0xDC00) {
  1486. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1487. leadSurrogate = codePoint
  1488. continue
  1489. }
  1490. // valid surrogate pair
  1491. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1492. } else if (leadSurrogate) {
  1493. // valid bmp char, but last char was a lead
  1494. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1495. }
  1496. leadSurrogate = null
  1497. // encode utf8
  1498. if (codePoint < 0x80) {
  1499. if ((units -= 1) < 0) break
  1500. bytes.push(codePoint)
  1501. } else if (codePoint < 0x800) {
  1502. if ((units -= 2) < 0) break
  1503. bytes.push(
  1504. codePoint >> 0x6 | 0xC0,
  1505. codePoint & 0x3F | 0x80
  1506. )
  1507. } else if (codePoint < 0x10000) {
  1508. if ((units -= 3) < 0) break
  1509. bytes.push(
  1510. codePoint >> 0xC | 0xE0,
  1511. codePoint >> 0x6 & 0x3F | 0x80,
  1512. codePoint & 0x3F | 0x80
  1513. )
  1514. } else if (codePoint < 0x110000) {
  1515. if ((units -= 4) < 0) break
  1516. bytes.push(
  1517. codePoint >> 0x12 | 0xF0,
  1518. codePoint >> 0xC & 0x3F | 0x80,
  1519. codePoint >> 0x6 & 0x3F | 0x80,
  1520. codePoint & 0x3F | 0x80
  1521. )
  1522. } else {
  1523. throw new Error('Invalid code point')
  1524. }
  1525. }
  1526. return bytes
  1527. }
  1528. function asciiToBytes (str) {
  1529. var byteArray = []
  1530. for (var i = 0; i < str.length; i++) {
  1531. // Node's code seems to be doing this and not & 0x7F..
  1532. byteArray.push(str.charCodeAt(i) & 0xFF)
  1533. }
  1534. return byteArray
  1535. }
  1536. function utf16leToBytes (str, units) {
  1537. var c, hi, lo
  1538. var byteArray = []
  1539. for (var i = 0; i < str.length; i++) {
  1540. if ((units -= 2) < 0) break
  1541. c = str.charCodeAt(i)
  1542. hi = c >> 8
  1543. lo = c % 256
  1544. byteArray.push(lo)
  1545. byteArray.push(hi)
  1546. }
  1547. return byteArray
  1548. }
  1549. function base64ToBytes (str) {
  1550. return base64.toByteArray(base64clean(str))
  1551. }
  1552. function blitBuffer (src, dst, offset, length) {
  1553. for (var i = 0; i < length; i++) {
  1554. if ((i + offset >= dst.length) || (i >= src.length)) break
  1555. dst[i + offset] = src[i]
  1556. }
  1557. return i
  1558. }
  1559. function isnan (val) {
  1560. return val !== val // eslint-disable-line no-self-compare
  1561. }
  1562. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1563. },{"base64-js":1,"ieee754":15,"isarray":16}],4:[function(require,module,exports){
  1564. // Use strict mode (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
  1565. "use strict";
  1566. // Requires
  1567. var Typo = require("typo-js");
  1568. // Create function
  1569. function CodeMirrorSpellChecker(options) {
  1570. // Initialize
  1571. options = options || {};
  1572. // Verify
  1573. if(typeof options.codeMirrorInstance !== "function" || typeof options.codeMirrorInstance.defineMode !== "function") {
  1574. console.log("CodeMirror Spell Checker: You must provide an instance of CodeMirror via the option `codeMirrorInstance`");
  1575. return;
  1576. }
  1577. // Because some browsers don't support this functionality yet
  1578. if(!String.prototype.includes) {
  1579. String.prototype.includes = function() {
  1580. "use strict";
  1581. return String.prototype.indexOf.apply(this, arguments) !== -1;
  1582. };
  1583. }
  1584. // Define the new mode
  1585. options.codeMirrorInstance.defineMode("spell-checker", function(config) {
  1586. // Load AFF/DIC data
  1587. if(!CodeMirrorSpellChecker.aff_loading) {
  1588. CodeMirrorSpellChecker.aff_loading = true;
  1589. var xhr_aff = new XMLHttpRequest();
  1590. xhr_aff.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff", true);
  1591. xhr_aff.onload = function() {
  1592. if(xhr_aff.readyState === 4 && xhr_aff.status === 200) {
  1593. CodeMirrorSpellChecker.aff_data = xhr_aff.responseText;
  1594. CodeMirrorSpellChecker.num_loaded++;
  1595. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1596. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1597. platform: "any"
  1598. });
  1599. }
  1600. }
  1601. };
  1602. xhr_aff.send(null);
  1603. }
  1604. if(!CodeMirrorSpellChecker.dic_loading) {
  1605. CodeMirrorSpellChecker.dic_loading = true;
  1606. var xhr_dic = new XMLHttpRequest();
  1607. xhr_dic.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic", true);
  1608. xhr_dic.onload = function() {
  1609. if(xhr_dic.readyState === 4 && xhr_dic.status === 200) {
  1610. CodeMirrorSpellChecker.dic_data = xhr_dic.responseText;
  1611. CodeMirrorSpellChecker.num_loaded++;
  1612. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1613. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1614. platform: "any"
  1615. });
  1616. }
  1617. }
  1618. };
  1619. xhr_dic.send(null);
  1620. }
  1621. // Define what separates a word
  1622. var rx_word = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ";
  1623. // Create the overlay and such
  1624. var overlay = {
  1625. token: function(stream) {
  1626. var ch = stream.peek();
  1627. var word = "";
  1628. if(rx_word.includes(ch)) {
  1629. stream.next();
  1630. return null;
  1631. }
  1632. while((ch = stream.peek()) != null && !rx_word.includes(ch)) {
  1633. word += ch;
  1634. stream.next();
  1635. }
  1636. if(CodeMirrorSpellChecker.typo && !CodeMirrorSpellChecker.typo.check(word))
  1637. return "spell-error"; // CSS class: cm-spell-error
  1638. return null;
  1639. }
  1640. };
  1641. var mode = options.codeMirrorInstance.getMode(
  1642. config, config.backdrop || "text/plain"
  1643. );
  1644. return options.codeMirrorInstance.overlayMode(mode, overlay, true);
  1645. });
  1646. }
  1647. // Initialize data globally to reduce memory consumption
  1648. CodeMirrorSpellChecker.num_loaded = 0;
  1649. CodeMirrorSpellChecker.aff_loading = false;
  1650. CodeMirrorSpellChecker.dic_loading = false;
  1651. CodeMirrorSpellChecker.aff_data = "";
  1652. CodeMirrorSpellChecker.dic_data = "";
  1653. CodeMirrorSpellChecker.typo;
  1654. // Export
  1655. module.exports = CodeMirrorSpellChecker;
  1656. },{"typo-js":18}],5:[function(require,module,exports){
  1657. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1658. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1659. (function(mod) {
  1660. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1661. mod(require("../../lib/codemirror"));
  1662. else if (typeof define == "function" && define.amd) // AMD
  1663. define(["../../lib/codemirror"], mod);
  1664. else // Plain browser env
  1665. mod(CodeMirror);
  1666. })(function(CodeMirror) {
  1667. "use strict";
  1668. CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
  1669. if (old == CodeMirror.Init) old = false;
  1670. if (!old == !val) return;
  1671. if (val) setFullscreen(cm);
  1672. else setNormal(cm);
  1673. });
  1674. function setFullscreen(cm) {
  1675. var wrap = cm.getWrapperElement();
  1676. cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
  1677. width: wrap.style.width, height: wrap.style.height};
  1678. wrap.style.width = "";
  1679. wrap.style.height = "auto";
  1680. wrap.className += " CodeMirror-fullscreen";
  1681. document.documentElement.style.overflow = "hidden";
  1682. cm.refresh();
  1683. }
  1684. function setNormal(cm) {
  1685. var wrap = cm.getWrapperElement();
  1686. wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
  1687. document.documentElement.style.overflow = "";
  1688. var info = cm.state.fullScreenRestore;
  1689. wrap.style.width = info.width; wrap.style.height = info.height;
  1690. window.scrollTo(info.scrollLeft, info.scrollTop);
  1691. cm.refresh();
  1692. }
  1693. });
  1694. },{"../../lib/codemirror":10}],6:[function(require,module,exports){
  1695. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1696. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1697. (function(mod) {
  1698. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1699. mod(require("../../lib/codemirror"));
  1700. else if (typeof define == "function" && define.amd) // AMD
  1701. define(["../../lib/codemirror"], mod);
  1702. else // Plain browser env
  1703. mod(CodeMirror);
  1704. })(function(CodeMirror) {
  1705. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  1706. var prev = old && old != CodeMirror.Init;
  1707. if (val && !prev) {
  1708. cm.on("blur", onBlur);
  1709. cm.on("change", onChange);
  1710. cm.on("swapDoc", onChange);
  1711. onChange(cm);
  1712. } else if (!val && prev) {
  1713. cm.off("blur", onBlur);
  1714. cm.off("change", onChange);
  1715. cm.off("swapDoc", onChange);
  1716. clearPlaceholder(cm);
  1717. var wrapper = cm.getWrapperElement();
  1718. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  1719. }
  1720. if (val && !cm.hasFocus()) onBlur(cm);
  1721. });
  1722. function clearPlaceholder(cm) {
  1723. if (cm.state.placeholder) {
  1724. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  1725. cm.state.placeholder = null;
  1726. }
  1727. }
  1728. function setPlaceholder(cm) {
  1729. clearPlaceholder(cm);
  1730. var elt = cm.state.placeholder = document.createElement("pre");
  1731. elt.style.cssText = "height: 0; overflow: visible";
  1732. elt.className = "CodeMirror-placeholder";
  1733. var placeHolder = cm.getOption("placeholder")
  1734. if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
  1735. elt.appendChild(placeHolder)
  1736. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  1737. }
  1738. function onBlur(cm) {
  1739. if (isEmpty(cm)) setPlaceholder(cm);
  1740. }
  1741. function onChange(cm) {
  1742. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  1743. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  1744. if (empty) setPlaceholder(cm);
  1745. else clearPlaceholder(cm);
  1746. }
  1747. function isEmpty(cm) {
  1748. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  1749. }
  1750. });
  1751. },{"../../lib/codemirror":10}],7:[function(require,module,exports){
  1752. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1753. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1754. (function(mod) {
  1755. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1756. mod(require("../../lib/codemirror"));
  1757. else if (typeof define == "function" && define.amd) // AMD
  1758. define(["../../lib/codemirror"], mod);
  1759. else // Plain browser env
  1760. mod(CodeMirror);
  1761. })(function(CodeMirror) {
  1762. "use strict";
  1763. var listRE = /^(\s*)(>[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/,
  1764. emptyListRE = /^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/,
  1765. unorderedListRE = /[*+-]\s/;
  1766. CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
  1767. if (cm.getOption("disableInput")) return CodeMirror.Pass;
  1768. var ranges = cm.listSelections(), replacements = [];
  1769. for (var i = 0; i < ranges.length; i++) {
  1770. var pos = ranges[i].head;
  1771. var eolState = cm.getStateAfter(pos.line);
  1772. var inList = eolState.list !== false;
  1773. var inQuote = eolState.quote !== 0;
  1774. var line = cm.getLine(pos.line), match = listRE.exec(line);
  1775. if (!ranges[i].empty() || (!inList && !inQuote) || !match) {
  1776. cm.execCommand("newlineAndIndent");
  1777. return;
  1778. }
  1779. if (emptyListRE.test(line)) {
  1780. cm.replaceRange("", {
  1781. line: pos.line, ch: 0
  1782. }, {
  1783. line: pos.line, ch: pos.ch + 1
  1784. });
  1785. replacements[i] = "\n";
  1786. } else {
  1787. var indent = match[1], after = match[5];
  1788. var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
  1789. ? match[2]
  1790. : (parseInt(match[3], 10) + 1) + match[4];
  1791. replacements[i] = "\n" + indent + bullet + after;
  1792. }
  1793. }
  1794. cm.replaceSelections(replacements);
  1795. };
  1796. });
  1797. },{"../../lib/codemirror":10}],8:[function(require,module,exports){
  1798. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1799. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1800. // Utility function that allows modes to be combined. The mode given
  1801. // as the base argument takes care of most of the normal mode
  1802. // functionality, but a second (typically simple) mode is used, which
  1803. // can override the style of text. Both modes get to parse all of the
  1804. // text, but when both assign a non-null style to a piece of code, the
  1805. // overlay wins, unless the combine argument was true and not overridden,
  1806. // or state.overlay.combineTokens was true, in which case the styles are
  1807. // combined.
  1808. (function(mod) {
  1809. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1810. mod(require("../../lib/codemirror"));
  1811. else if (typeof define == "function" && define.amd) // AMD
  1812. define(["../../lib/codemirror"], mod);
  1813. else // Plain browser env
  1814. mod(CodeMirror);
  1815. })(function(CodeMirror) {
  1816. "use strict";
  1817. CodeMirror.overlayMode = function(base, overlay, combine) {
  1818. return {
  1819. startState: function() {
  1820. return {
  1821. base: CodeMirror.startState(base),
  1822. overlay: CodeMirror.startState(overlay),
  1823. basePos: 0, baseCur: null,
  1824. overlayPos: 0, overlayCur: null,
  1825. streamSeen: null
  1826. };
  1827. },
  1828. copyState: function(state) {
  1829. return {
  1830. base: CodeMirror.copyState(base, state.base),
  1831. overlay: CodeMirror.copyState(overlay, state.overlay),
  1832. basePos: state.basePos, baseCur: null,
  1833. overlayPos: state.overlayPos, overlayCur: null
  1834. };
  1835. },
  1836. token: function(stream, state) {
  1837. if (stream != state.streamSeen ||
  1838. Math.min(state.basePos, state.overlayPos) < stream.start) {
  1839. state.streamSeen = stream;
  1840. state.basePos = state.overlayPos = stream.start;
  1841. }
  1842. if (stream.start == state.basePos) {
  1843. state.baseCur = base.token(stream, state.base);
  1844. state.basePos = stream.pos;
  1845. }
  1846. if (stream.start == state.overlayPos) {
  1847. stream.pos = stream.start;
  1848. state.overlayCur = overlay.token(stream, state.overlay);
  1849. state.overlayPos = stream.pos;
  1850. }
  1851. stream.pos = Math.min(state.basePos, state.overlayPos);
  1852. // state.overlay.combineTokens always takes precedence over combine,
  1853. // unless set to null
  1854. if (state.overlayCur == null) return state.baseCur;
  1855. else if (state.baseCur != null &&
  1856. state.overlay.combineTokens ||
  1857. combine && state.overlay.combineTokens == null)
  1858. return state.baseCur + " " + state.overlayCur;
  1859. else return state.overlayCur;
  1860. },
  1861. indent: base.indent && function(state, textAfter) {
  1862. return base.indent(state.base, textAfter);
  1863. },
  1864. electricChars: base.electricChars,
  1865. innerMode: function(state) { return {state: state.base, mode: base}; },
  1866. blankLine: function(state) {
  1867. if (base.blankLine) base.blankLine(state.base);
  1868. if (overlay.blankLine) overlay.blankLine(state.overlay);
  1869. }
  1870. };
  1871. };
  1872. });
  1873. },{"../../lib/codemirror":10}],9:[function(require,module,exports){
  1874. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1875. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1876. // Because sometimes you need to mark the selected *text*.
  1877. //
  1878. // Adds an option 'styleSelectedText' which, when enabled, gives
  1879. // selected text the CSS class given as option value, or
  1880. // "CodeMirror-selectedtext" when the value is not a string.
  1881. (function(mod) {
  1882. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1883. mod(require("../../lib/codemirror"));
  1884. else if (typeof define == "function" && define.amd) // AMD
  1885. define(["../../lib/codemirror"], mod);
  1886. else // Plain browser env
  1887. mod(CodeMirror);
  1888. })(function(CodeMirror) {
  1889. "use strict";
  1890. CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
  1891. var prev = old && old != CodeMirror.Init;
  1892. if (val && !prev) {
  1893. cm.state.markedSelection = [];
  1894. cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
  1895. reset(cm);
  1896. cm.on("cursorActivity", onCursorActivity);
  1897. cm.on("change", onChange);
  1898. } else if (!val && prev) {
  1899. cm.off("cursorActivity", onCursorActivity);
  1900. cm.off("change", onChange);
  1901. clear(cm);
  1902. cm.state.markedSelection = cm.state.markedSelectionStyle = null;
  1903. }
  1904. });
  1905. function onCursorActivity(cm) {
  1906. cm.operation(function() { update(cm); });
  1907. }
  1908. function onChange(cm) {
  1909. if (cm.state.markedSelection.length)
  1910. cm.operation(function() { clear(cm); });
  1911. }
  1912. var CHUNK_SIZE = 8;
  1913. var Pos = CodeMirror.Pos;
  1914. var cmp = CodeMirror.cmpPos;
  1915. function coverRange(cm, from, to, addAt) {
  1916. if (cmp(from, to) == 0) return;
  1917. var array = cm.state.markedSelection;
  1918. var cls = cm.state.markedSelectionStyle;
  1919. for (var line = from.line;;) {
  1920. var start = line == from.line ? from : Pos(line, 0);
  1921. var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
  1922. var end = atEnd ? to : Pos(endLine, 0);
  1923. var mark = cm.markText(start, end, {className: cls});
  1924. if (addAt == null) array.push(mark);
  1925. else array.splice(addAt++, 0, mark);
  1926. if (atEnd) break;
  1927. line = endLine;
  1928. }
  1929. }
  1930. function clear(cm) {
  1931. var array = cm.state.markedSelection;
  1932. for (var i = 0; i < array.length; ++i) array[i].clear();
  1933. array.length = 0;
  1934. }
  1935. function reset(cm) {
  1936. clear(cm);
  1937. var ranges = cm.listSelections();
  1938. for (var i = 0; i < ranges.length; i++)
  1939. coverRange(cm, ranges[i].from(), ranges[i].to());
  1940. }
  1941. function update(cm) {
  1942. if (!cm.somethingSelected()) return clear(cm);
  1943. if (cm.listSelections().length > 1) return reset(cm);
  1944. var from = cm.getCursor("start"), to = cm.getCursor("end");
  1945. var array = cm.state.markedSelection;
  1946. if (!array.length) return coverRange(cm, from, to);
  1947. var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
  1948. if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
  1949. cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
  1950. return reset(cm);
  1951. while (cmp(from, coverStart.from) > 0) {
  1952. array.shift().clear();
  1953. coverStart = array[0].find();
  1954. }
  1955. if (cmp(from, coverStart.from) < 0) {
  1956. if (coverStart.to.line - from.line < CHUNK_SIZE) {
  1957. array.shift().clear();
  1958. coverRange(cm, from, coverStart.to, 0);
  1959. } else {
  1960. coverRange(cm, from, coverStart.from, 0);
  1961. }
  1962. }
  1963. while (cmp(to, coverEnd.to) < 0) {
  1964. array.pop().clear();
  1965. coverEnd = array[array.length - 1].find();
  1966. }
  1967. if (cmp(to, coverEnd.to) > 0) {
  1968. if (to.line - coverEnd.from.line < CHUNK_SIZE) {
  1969. array.pop().clear();
  1970. coverRange(cm, coverEnd.from, to);
  1971. } else {
  1972. coverRange(cm, coverEnd.to, to);
  1973. }
  1974. }
  1975. }
  1976. });
  1977. },{"../../lib/codemirror":10}],10:[function(require,module,exports){
  1978. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1979. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1980. // This is CodeMirror (http://codemirror.net), a code editor
  1981. // implemented in JavaScript on top of the browser's DOM.
  1982. //
  1983. // You can find some technical background for some of the code below
  1984. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  1985. (function(mod) {
  1986. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1987. module.exports = mod();
  1988. else if (typeof define == "function" && define.amd) // AMD
  1989. return define([], mod);
  1990. else // Plain browser env
  1991. (this || window).CodeMirror = mod();
  1992. })(function() {
  1993. "use strict";
  1994. // BROWSER SNIFFING
  1995. // Kludges for bugs and behavior differences that can't be feature
  1996. // detected are enabled based on userAgent etc sniffing.
  1997. var userAgent = navigator.userAgent;
  1998. var platform = navigator.platform;
  1999. var gecko = /gecko\/\d/i.test(userAgent);
  2000. var ie_upto10 = /MSIE \d/.test(userAgent);
  2001. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  2002. var ie = ie_upto10 || ie_11up;
  2003. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  2004. var webkit = /WebKit\//.test(userAgent);
  2005. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  2006. var chrome = /Chrome\//.test(userAgent);
  2007. var presto = /Opera\//.test(userAgent);
  2008. var safari = /Apple Computer/.test(navigator.vendor);
  2009. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  2010. var phantom = /PhantomJS/.test(userAgent);
  2011. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  2012. // This is woefully incomplete. Suggestions for alternative methods welcome.
  2013. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  2014. var mac = ios || /Mac/.test(platform);
  2015. var chromeOS = /\bCrOS\b/.test(userAgent);
  2016. var windows = /win/i.test(platform);
  2017. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  2018. if (presto_version) presto_version = Number(presto_version[1]);
  2019. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  2020. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  2021. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  2022. var captureRightClick = gecko || (ie && ie_version >= 9);
  2023. // Optimize some code when these features are not used.
  2024. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  2025. // EDITOR CONSTRUCTOR
  2026. // A CodeMirror instance represents an editor. This is the object
  2027. // that user code is usually dealing with.
  2028. function CodeMirror(place, options) {
  2029. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  2030. this.options = options = options ? copyObj(options) : {};
  2031. // Determine effective options based on given values and defaults.
  2032. copyObj(defaults, options, false);
  2033. setGuttersForLineNumbers(options);
  2034. var doc = options.value;
  2035. if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
  2036. this.doc = doc;
  2037. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  2038. var display = this.display = new Display(place, doc, input);
  2039. display.wrapper.CodeMirror = this;
  2040. updateGutters(this);
  2041. themeChanged(this);
  2042. if (options.lineWrapping)
  2043. this.display.wrapper.className += " CodeMirror-wrap";
  2044. if (options.autofocus && !mobile) display.input.focus();
  2045. initScrollbars(this);
  2046. this.state = {
  2047. keyMaps: [], // stores maps added by addKeyMap
  2048. overlays: [], // highlighting overlays, as added by addOverlay
  2049. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  2050. overwrite: false,
  2051. delayingBlurEvent: false,
  2052. focused: false,
  2053. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  2054. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  2055. selectingText: false,
  2056. draggingText: false,
  2057. highlight: new Delayed(), // stores highlight worker timeout
  2058. keySeq: null, // Unfinished key sequence
  2059. specialChars: null
  2060. };
  2061. var cm = this;
  2062. // Override magic textarea content restore that IE sometimes does
  2063. // on our hidden textarea on reload
  2064. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  2065. registerEventHandlers(this);
  2066. ensureGlobalHandlers();
  2067. startOperation(this);
  2068. this.curOp.forceUpdate = true;
  2069. attachDoc(this, doc);
  2070. if ((options.autofocus && !mobile) || cm.hasFocus())
  2071. setTimeout(bind(onFocus, this), 20);
  2072. else
  2073. onBlur(this);
  2074. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  2075. optionHandlers[opt](this, options[opt], Init);
  2076. maybeUpdateLineNumberWidth(this);
  2077. if (options.finishInit) options.finishInit(this);
  2078. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  2079. endOperation(this);
  2080. // Suppress optimizelegibility in Webkit, since it breaks text
  2081. // measuring on line wrapping boundaries.
  2082. if (webkit && options.lineWrapping &&
  2083. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  2084. display.lineDiv.style.textRendering = "auto";
  2085. }
  2086. // DISPLAY CONSTRUCTOR
  2087. // The display handles the DOM integration, both for input reading
  2088. // and content drawing. It holds references to DOM nodes and
  2089. // display-related state.
  2090. function Display(place, doc, input) {
  2091. var d = this;
  2092. this.input = input;
  2093. // Covers bottom-right square when both scrollbars are present.
  2094. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  2095. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  2096. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  2097. // and h scrollbar is present.
  2098. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  2099. d.gutterFiller.setAttribute("cm-not-content", "true");
  2100. // Will contain the actual code, positioned to cover the viewport.
  2101. d.lineDiv = elt("div", null, "CodeMirror-code");
  2102. // Elements are added to these to represent selection and cursors.
  2103. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  2104. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  2105. // A visibility: hidden element used to find the size of things.
  2106. d.measure = elt("div", null, "CodeMirror-measure");
  2107. // When lines outside of the viewport are measured, they are drawn in this.
  2108. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  2109. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  2110. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  2111. null, "position: relative; outline: none");
  2112. // Moved around its parent to cover visible view.
  2113. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  2114. // Set to the height of the document, allowing scrolling.
  2115. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  2116. d.sizerWidth = null;
  2117. // Behavior of elts with overflow: auto and padding is
  2118. // inconsistent across browsers. This is used to ensure the
  2119. // scrollable area is big enough.
  2120. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  2121. // Will contain the gutters, if any.
  2122. d.gutters = elt("div", null, "CodeMirror-gutters");
  2123. d.lineGutter = null;
  2124. // Actual scrollable element.
  2125. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  2126. d.scroller.setAttribute("tabIndex", "-1");
  2127. // The element in which the editor lives.
  2128. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  2129. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  2130. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  2131. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  2132. if (place) {
  2133. if (place.appendChild) place.appendChild(d.wrapper);
  2134. else place(d.wrapper);
  2135. }
  2136. // Current rendered range (may be bigger than the view window).
  2137. d.viewFrom = d.viewTo = doc.first;
  2138. d.reportedViewFrom = d.reportedViewTo = doc.first;
  2139. // Information about the rendered lines.
  2140. d.view = [];
  2141. d.renderedView = null;
  2142. // Holds info about a single rendered line when it was rendered
  2143. // for measurement, while not in view.
  2144. d.externalMeasured = null;
  2145. // Empty space (in pixels) above the view
  2146. d.viewOffset = 0;
  2147. d.lastWrapHeight = d.lastWrapWidth = 0;
  2148. d.updateLineNumbers = null;
  2149. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  2150. d.scrollbarsClipped = false;
  2151. // Used to only resize the line number gutter when necessary (when
  2152. // the amount of lines crosses a boundary that makes its width change)
  2153. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  2154. // Set to true when a non-horizontal-scrolling line widget is
  2155. // added. As an optimization, line widget aligning is skipped when
  2156. // this is false.
  2157. d.alignWidgets = false;
  2158. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  2159. // Tracks the maximum line length so that the horizontal scrollbar
  2160. // can be kept static when scrolling.
  2161. d.maxLine = null;
  2162. d.maxLineLength = 0;
  2163. d.maxLineChanged = false;
  2164. // Used for measuring wheel scrolling granularity
  2165. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  2166. // True when shift is held down.
  2167. d.shift = false;
  2168. // Used to track whether anything happened since the context menu
  2169. // was opened.
  2170. d.selForContextMenu = null;
  2171. d.activeTouch = null;
  2172. input.init(d);
  2173. }
  2174. // STATE UPDATES
  2175. // Used to get the editor into a consistent state again when options change.
  2176. function loadMode(cm) {
  2177. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  2178. resetModeState(cm);
  2179. }
  2180. function resetModeState(cm) {
  2181. cm.doc.iter(function(line) {
  2182. if (line.stateAfter) line.stateAfter = null;
  2183. if (line.styles) line.styles = null;
  2184. });
  2185. cm.doc.frontier = cm.doc.first;
  2186. startWorker(cm, 100);
  2187. cm.state.modeGen++;
  2188. if (cm.curOp) regChange(cm);
  2189. }
  2190. function wrappingChanged(cm) {
  2191. if (cm.options.lineWrapping) {
  2192. addClass(cm.display.wrapper, "CodeMirror-wrap");
  2193. cm.display.sizer.style.minWidth = "";
  2194. cm.display.sizerWidth = null;
  2195. } else {
  2196. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  2197. findMaxLine(cm);
  2198. }
  2199. estimateLineHeights(cm);
  2200. regChange(cm);
  2201. clearCaches(cm);
  2202. setTimeout(function(){updateScrollbars(cm);}, 100);
  2203. }
  2204. // Returns a function that estimates the height of a line, to use as
  2205. // first approximation until the line becomes visible (and is thus
  2206. // properly measurable).
  2207. function estimateHeight(cm) {
  2208. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2209. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2210. return function(line) {
  2211. if (lineIsHidden(cm.doc, line)) return 0;
  2212. var widgetsHeight = 0;
  2213. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  2214. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  2215. }
  2216. if (wrapping)
  2217. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  2218. else
  2219. return widgetsHeight + th;
  2220. };
  2221. }
  2222. function estimateLineHeights(cm) {
  2223. var doc = cm.doc, est = estimateHeight(cm);
  2224. doc.iter(function(line) {
  2225. var estHeight = est(line);
  2226. if (estHeight != line.height) updateLineHeight(line, estHeight);
  2227. });
  2228. }
  2229. function themeChanged(cm) {
  2230. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  2231. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  2232. clearCaches(cm);
  2233. }
  2234. function guttersChanged(cm) {
  2235. updateGutters(cm);
  2236. regChange(cm);
  2237. setTimeout(function(){alignHorizontally(cm);}, 20);
  2238. }
  2239. // Rebuild the gutter elements, ensure the margin to the left of the
  2240. // code matches their width.
  2241. function updateGutters(cm) {
  2242. var gutters = cm.display.gutters, specs = cm.options.gutters;
  2243. removeChildren(gutters);
  2244. for (var i = 0; i < specs.length; ++i) {
  2245. var gutterClass = specs[i];
  2246. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  2247. if (gutterClass == "CodeMirror-linenumbers") {
  2248. cm.display.lineGutter = gElt;
  2249. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  2250. }
  2251. }
  2252. gutters.style.display = i ? "" : "none";
  2253. updateGutterSpace(cm);
  2254. }
  2255. function updateGutterSpace(cm) {
  2256. var width = cm.display.gutters.offsetWidth;
  2257. cm.display.sizer.style.marginLeft = width + "px";
  2258. }
  2259. // Compute the character length of a line, taking into account
  2260. // collapsed ranges (see markText) that might hide parts, and join
  2261. // other lines onto it.
  2262. function lineLength(line) {
  2263. if (line.height == 0) return 0;
  2264. var len = line.text.length, merged, cur = line;
  2265. while (merged = collapsedSpanAtStart(cur)) {
  2266. var found = merged.find(0, true);
  2267. cur = found.from.line;
  2268. len += found.from.ch - found.to.ch;
  2269. }
  2270. cur = line;
  2271. while (merged = collapsedSpanAtEnd(cur)) {
  2272. var found = merged.find(0, true);
  2273. len -= cur.text.length - found.from.ch;
  2274. cur = found.to.line;
  2275. len += cur.text.length - found.to.ch;
  2276. }
  2277. return len;
  2278. }
  2279. // Find the longest line in the document.
  2280. function findMaxLine(cm) {
  2281. var d = cm.display, doc = cm.doc;
  2282. d.maxLine = getLine(doc, doc.first);
  2283. d.maxLineLength = lineLength(d.maxLine);
  2284. d.maxLineChanged = true;
  2285. doc.iter(function(line) {
  2286. var len = lineLength(line);
  2287. if (len > d.maxLineLength) {
  2288. d.maxLineLength = len;
  2289. d.maxLine = line;
  2290. }
  2291. });
  2292. }
  2293. // Make sure the gutters options contains the element
  2294. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  2295. function setGuttersForLineNumbers(options) {
  2296. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  2297. if (found == -1 && options.lineNumbers) {
  2298. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  2299. } else if (found > -1 && !options.lineNumbers) {
  2300. options.gutters = options.gutters.slice(0);
  2301. options.gutters.splice(found, 1);
  2302. }
  2303. }
  2304. // SCROLLBARS
  2305. // Prepare DOM reads needed to update the scrollbars. Done in one
  2306. // shot to minimize update/measure roundtrips.
  2307. function measureForScrollbars(cm) {
  2308. var d = cm.display, gutterW = d.gutters.offsetWidth;
  2309. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  2310. return {
  2311. clientHeight: d.scroller.clientHeight,
  2312. viewHeight: d.wrapper.clientHeight,
  2313. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  2314. viewWidth: d.wrapper.clientWidth,
  2315. barLeft: cm.options.fixedGutter ? gutterW : 0,
  2316. docHeight: docH,
  2317. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  2318. nativeBarWidth: d.nativeBarWidth,
  2319. gutterWidth: gutterW
  2320. };
  2321. }
  2322. function NativeScrollbars(place, scroll, cm) {
  2323. this.cm = cm;
  2324. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  2325. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  2326. place(vert); place(horiz);
  2327. on(vert, "scroll", function() {
  2328. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  2329. });
  2330. on(horiz, "scroll", function() {
  2331. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  2332. });
  2333. this.checkedZeroWidth = false;
  2334. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  2335. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  2336. }
  2337. NativeScrollbars.prototype = copyObj({
  2338. update: function(measure) {
  2339. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  2340. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  2341. var sWidth = measure.nativeBarWidth;
  2342. if (needsV) {
  2343. this.vert.style.display = "block";
  2344. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  2345. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  2346. // A bug in IE8 can cause this value to be negative, so guard it.
  2347. this.vert.firstChild.style.height =
  2348. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  2349. } else {
  2350. this.vert.style.display = "";
  2351. this.vert.firstChild.style.height = "0";
  2352. }
  2353. if (needsH) {
  2354. this.horiz.style.display = "block";
  2355. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  2356. this.horiz.style.left = measure.barLeft + "px";
  2357. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  2358. this.horiz.firstChild.style.width =
  2359. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  2360. } else {
  2361. this.horiz.style.display = "";
  2362. this.horiz.firstChild.style.width = "0";
  2363. }
  2364. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  2365. if (sWidth == 0) this.zeroWidthHack();
  2366. this.checkedZeroWidth = true;
  2367. }
  2368. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  2369. },
  2370. setScrollLeft: function(pos) {
  2371. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  2372. if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
  2373. },
  2374. setScrollTop: function(pos) {
  2375. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  2376. if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
  2377. },
  2378. zeroWidthHack: function() {
  2379. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  2380. this.horiz.style.height = this.vert.style.width = w;
  2381. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  2382. this.disableHoriz = new Delayed;
  2383. this.disableVert = new Delayed;
  2384. },
  2385. enableZeroWidthBar: function(bar, delay) {
  2386. bar.style.pointerEvents = "auto";
  2387. function maybeDisable() {
  2388. // To find out whether the scrollbar is still visible, we
  2389. // check whether the element under the pixel in the bottom
  2390. // left corner of the scrollbar box is the scrollbar box
  2391. // itself (when the bar is still visible) or its filler child
  2392. // (when the bar is hidden). If it is still visible, we keep
  2393. // it enabled, if it's hidden, we disable pointer events.
  2394. var box = bar.getBoundingClientRect();
  2395. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
  2396. if (elt != bar) bar.style.pointerEvents = "none";
  2397. else delay.set(1000, maybeDisable);
  2398. }
  2399. delay.set(1000, maybeDisable);
  2400. },
  2401. clear: function() {
  2402. var parent = this.horiz.parentNode;
  2403. parent.removeChild(this.horiz);
  2404. parent.removeChild(this.vert);
  2405. }
  2406. }, NativeScrollbars.prototype);
  2407. function NullScrollbars() {}
  2408. NullScrollbars.prototype = copyObj({
  2409. update: function() { return {bottom: 0, right: 0}; },
  2410. setScrollLeft: function() {},
  2411. setScrollTop: function() {},
  2412. clear: function() {}
  2413. }, NullScrollbars.prototype);
  2414. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  2415. function initScrollbars(cm) {
  2416. if (cm.display.scrollbars) {
  2417. cm.display.scrollbars.clear();
  2418. if (cm.display.scrollbars.addClass)
  2419. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  2420. }
  2421. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  2422. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  2423. // Prevent clicks in the scrollbars from killing focus
  2424. on(node, "mousedown", function() {
  2425. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  2426. });
  2427. node.setAttribute("cm-not-content", "true");
  2428. }, function(pos, axis) {
  2429. if (axis == "horizontal") setScrollLeft(cm, pos);
  2430. else setScrollTop(cm, pos);
  2431. }, cm);
  2432. if (cm.display.scrollbars.addClass)
  2433. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  2434. }
  2435. function updateScrollbars(cm, measure) {
  2436. if (!measure) measure = measureForScrollbars(cm);
  2437. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  2438. updateScrollbarsInner(cm, measure);
  2439. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  2440. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  2441. updateHeightsInViewport(cm);
  2442. updateScrollbarsInner(cm, measureForScrollbars(cm));
  2443. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  2444. }
  2445. }
  2446. // Re-synchronize the fake scrollbars with the actual size of the
  2447. // content.
  2448. function updateScrollbarsInner(cm, measure) {
  2449. var d = cm.display;
  2450. var sizes = d.scrollbars.update(measure);
  2451. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  2452. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  2453. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  2454. if (sizes.right && sizes.bottom) {
  2455. d.scrollbarFiller.style.display = "block";
  2456. d.scrollbarFiller.style.height = sizes.bottom + "px";
  2457. d.scrollbarFiller.style.width = sizes.right + "px";
  2458. } else d.scrollbarFiller.style.display = "";
  2459. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  2460. d.gutterFiller.style.display = "block";
  2461. d.gutterFiller.style.height = sizes.bottom + "px";
  2462. d.gutterFiller.style.width = measure.gutterWidth + "px";
  2463. } else d.gutterFiller.style.display = "";
  2464. }
  2465. // Compute the lines that are visible in a given viewport (defaults
  2466. // the the current scroll position). viewport may contain top,
  2467. // height, and ensure (see op.scrollToPos) properties.
  2468. function visibleLines(display, doc, viewport) {
  2469. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  2470. top = Math.floor(top - paddingTop(display));
  2471. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  2472. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  2473. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2474. // forces those lines into the viewport (if possible).
  2475. if (viewport && viewport.ensure) {
  2476. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  2477. if (ensureFrom < from) {
  2478. from = ensureFrom;
  2479. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  2480. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2481. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  2482. to = ensureTo;
  2483. }
  2484. }
  2485. return {from: from, to: Math.max(to, from + 1)};
  2486. }
  2487. // LINE NUMBERS
  2488. // Re-align line numbers and gutter marks to compensate for
  2489. // horizontal scrolling.
  2490. function alignHorizontally(cm) {
  2491. var display = cm.display, view = display.view;
  2492. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  2493. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  2494. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  2495. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  2496. if (cm.options.fixedGutter && view[i].gutter)
  2497. view[i].gutter.style.left = left;
  2498. var align = view[i].alignable;
  2499. if (align) for (var j = 0; j < align.length; j++)
  2500. align[j].style.left = left;
  2501. }
  2502. if (cm.options.fixedGutter)
  2503. display.gutters.style.left = (comp + gutterW) + "px";
  2504. }
  2505. // Used to ensure that the line number gutter is still the right
  2506. // size for the current document size. Returns true when an update
  2507. // is needed.
  2508. function maybeUpdateLineNumberWidth(cm) {
  2509. if (!cm.options.lineNumbers) return false;
  2510. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  2511. if (last.length != display.lineNumChars) {
  2512. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  2513. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  2514. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  2515. display.lineGutter.style.width = "";
  2516. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  2517. display.lineNumWidth = display.lineNumInnerWidth + padding;
  2518. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  2519. display.lineGutter.style.width = display.lineNumWidth + "px";
  2520. updateGutterSpace(cm);
  2521. return true;
  2522. }
  2523. return false;
  2524. }
  2525. function lineNumberFor(options, i) {
  2526. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  2527. }
  2528. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2529. // but using getBoundingClientRect to get a sub-pixel-accurate
  2530. // result.
  2531. function compensateForHScroll(display) {
  2532. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  2533. }
  2534. // DISPLAY DRAWING
  2535. function DisplayUpdate(cm, viewport, force) {
  2536. var display = cm.display;
  2537. this.viewport = viewport;
  2538. // Store some values that we'll need later (but don't want to force a relayout for)
  2539. this.visible = visibleLines(display, cm.doc, viewport);
  2540. this.editorIsHidden = !display.wrapper.offsetWidth;
  2541. this.wrapperHeight = display.wrapper.clientHeight;
  2542. this.wrapperWidth = display.wrapper.clientWidth;
  2543. this.oldDisplayWidth = displayWidth(cm);
  2544. this.force = force;
  2545. this.dims = getDimensions(cm);
  2546. this.events = [];
  2547. }
  2548. DisplayUpdate.prototype.signal = function(emitter, type) {
  2549. if (hasHandler(emitter, type))
  2550. this.events.push(arguments);
  2551. };
  2552. DisplayUpdate.prototype.finish = function() {
  2553. for (var i = 0; i < this.events.length; i++)
  2554. signal.apply(null, this.events[i]);
  2555. };
  2556. function maybeClipScrollbars(cm) {
  2557. var display = cm.display;
  2558. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  2559. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  2560. display.heightForcer.style.height = scrollGap(cm) + "px";
  2561. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  2562. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  2563. display.scrollbarsClipped = true;
  2564. }
  2565. }
  2566. // Does the actual updating of the line display. Bails out
  2567. // (returning false) when there is nothing to be done and forced is
  2568. // false.
  2569. function updateDisplayIfNeeded(cm, update) {
  2570. var display = cm.display, doc = cm.doc;
  2571. if (update.editorIsHidden) {
  2572. resetView(cm);
  2573. return false;
  2574. }
  2575. // Bail out if the visible area is already rendered and nothing changed.
  2576. if (!update.force &&
  2577. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  2578. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  2579. display.renderedView == display.view && countDirtyView(cm) == 0)
  2580. return false;
  2581. if (maybeUpdateLineNumberWidth(cm)) {
  2582. resetView(cm);
  2583. update.dims = getDimensions(cm);
  2584. }
  2585. // Compute a suitable new viewport (from & to)
  2586. var end = doc.first + doc.size;
  2587. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  2588. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  2589. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  2590. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  2591. if (sawCollapsedSpans) {
  2592. from = visualLineNo(cm.doc, from);
  2593. to = visualLineEndNo(cm.doc, to);
  2594. }
  2595. var different = from != display.viewFrom || to != display.viewTo ||
  2596. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  2597. adjustView(cm, from, to);
  2598. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  2599. // Position the mover div to align with the current scroll position
  2600. cm.display.mover.style.top = display.viewOffset + "px";
  2601. var toUpdate = countDirtyView(cm);
  2602. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  2603. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  2604. return false;
  2605. // For big changes, we hide the enclosing element during the
  2606. // update, since that speeds up the operations on most browsers.
  2607. var focused = activeElt();
  2608. if (toUpdate > 4) display.lineDiv.style.display = "none";
  2609. patchDisplay(cm, display.updateLineNumbers, update.dims);
  2610. if (toUpdate > 4) display.lineDiv.style.display = "";
  2611. display.renderedView = display.view;
  2612. // There might have been a widget with a focused element that got
  2613. // hidden or updated, if so re-focus it.
  2614. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  2615. // Prevent selection and cursors from interfering with the scroll
  2616. // width and height.
  2617. removeChildren(display.cursorDiv);
  2618. removeChildren(display.selectionDiv);
  2619. display.gutters.style.height = display.sizer.style.minHeight = 0;
  2620. if (different) {
  2621. display.lastWrapHeight = update.wrapperHeight;
  2622. display.lastWrapWidth = update.wrapperWidth;
  2623. startWorker(cm, 400);
  2624. }
  2625. display.updateLineNumbers = null;
  2626. return true;
  2627. }
  2628. function postUpdateDisplay(cm, update) {
  2629. var viewport = update.viewport;
  2630. for (var first = true;; first = false) {
  2631. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  2632. // Clip forced viewport to actual scrollable area.
  2633. if (viewport && viewport.top != null)
  2634. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  2635. // Updated line heights might result in the drawn area not
  2636. // actually covering the viewport. Keep looping until it does.
  2637. update.visible = visibleLines(cm.display, cm.doc, viewport);
  2638. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  2639. break;
  2640. }
  2641. if (!updateDisplayIfNeeded(cm, update)) break;
  2642. updateHeightsInViewport(cm);
  2643. var barMeasure = measureForScrollbars(cm);
  2644. updateSelection(cm);
  2645. updateScrollbars(cm, barMeasure);
  2646. setDocumentHeight(cm, barMeasure);
  2647. }
  2648. update.signal(cm, "update", cm);
  2649. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  2650. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  2651. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  2652. }
  2653. }
  2654. function updateDisplaySimple(cm, viewport) {
  2655. var update = new DisplayUpdate(cm, viewport);
  2656. if (updateDisplayIfNeeded(cm, update)) {
  2657. updateHeightsInViewport(cm);
  2658. postUpdateDisplay(cm, update);
  2659. var barMeasure = measureForScrollbars(cm);
  2660. updateSelection(cm);
  2661. updateScrollbars(cm, barMeasure);
  2662. setDocumentHeight(cm, barMeasure);
  2663. update.finish();
  2664. }
  2665. }
  2666. function setDocumentHeight(cm, measure) {
  2667. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  2668. cm.display.heightForcer.style.top = measure.docHeight + "px";
  2669. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  2670. }
  2671. // Read the actual heights of the rendered lines, and update their
  2672. // stored heights to match.
  2673. function updateHeightsInViewport(cm) {
  2674. var display = cm.display;
  2675. var prevBottom = display.lineDiv.offsetTop;
  2676. for (var i = 0; i < display.view.length; i++) {
  2677. var cur = display.view[i], height;
  2678. if (cur.hidden) continue;
  2679. if (ie && ie_version < 8) {
  2680. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  2681. height = bot - prevBottom;
  2682. prevBottom = bot;
  2683. } else {
  2684. var box = cur.node.getBoundingClientRect();
  2685. height = box.bottom - box.top;
  2686. }
  2687. var diff = cur.line.height - height;
  2688. if (height < 2) height = textHeight(display);
  2689. if (diff > .001 || diff < -.001) {
  2690. updateLineHeight(cur.line, height);
  2691. updateWidgetHeight(cur.line);
  2692. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  2693. updateWidgetHeight(cur.rest[j]);
  2694. }
  2695. }
  2696. }
  2697. // Read and store the height of line widgets associated with the
  2698. // given line.
  2699. function updateWidgetHeight(line) {
  2700. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  2701. line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
  2702. }
  2703. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2704. // view, so that we don't interleave reading and writing to the DOM.
  2705. function getDimensions(cm) {
  2706. var d = cm.display, left = {}, width = {};
  2707. var gutterLeft = d.gutters.clientLeft;
  2708. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2709. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  2710. width[cm.options.gutters[i]] = n.clientWidth;
  2711. }
  2712. return {fixedPos: compensateForHScroll(d),
  2713. gutterTotalWidth: d.gutters.offsetWidth,
  2714. gutterLeft: left,
  2715. gutterWidth: width,
  2716. wrapperWidth: d.wrapper.clientWidth};
  2717. }
  2718. // Sync the actual display DOM structure with display.view, removing
  2719. // nodes for lines that are no longer in view, and creating the ones
  2720. // that are not there yet, and updating the ones that are out of
  2721. // date.
  2722. function patchDisplay(cm, updateNumbersFrom, dims) {
  2723. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  2724. var container = display.lineDiv, cur = container.firstChild;
  2725. function rm(node) {
  2726. var next = node.nextSibling;
  2727. // Works around a throw-scroll bug in OS X Webkit
  2728. if (webkit && mac && cm.display.currentWheelTarget == node)
  2729. node.style.display = "none";
  2730. else
  2731. node.parentNode.removeChild(node);
  2732. return next;
  2733. }
  2734. var view = display.view, lineN = display.viewFrom;
  2735. // Loop over the elements in the view, syncing cur (the DOM nodes
  2736. // in display.lineDiv) with the view as we go.
  2737. for (var i = 0; i < view.length; i++) {
  2738. var lineView = view[i];
  2739. if (lineView.hidden) {
  2740. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  2741. var node = buildLineElement(cm, lineView, lineN, dims);
  2742. container.insertBefore(node, cur);
  2743. } else { // Already drawn
  2744. while (cur != lineView.node) cur = rm(cur);
  2745. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  2746. updateNumbersFrom <= lineN && lineView.lineNumber;
  2747. if (lineView.changes) {
  2748. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  2749. updateLineForChanges(cm, lineView, lineN, dims);
  2750. }
  2751. if (updateNumber) {
  2752. removeChildren(lineView.lineNumber);
  2753. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  2754. }
  2755. cur = lineView.node.nextSibling;
  2756. }
  2757. lineN += lineView.size;
  2758. }
  2759. while (cur) cur = rm(cur);
  2760. }
  2761. // When an aspect of a line changes, a string is added to
  2762. // lineView.changes. This updates the relevant part of the line's
  2763. // DOM structure.
  2764. function updateLineForChanges(cm, lineView, lineN, dims) {
  2765. for (var j = 0; j < lineView.changes.length; j++) {
  2766. var type = lineView.changes[j];
  2767. if (type == "text") updateLineText(cm, lineView);
  2768. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  2769. else if (type == "class") updateLineClasses(lineView);
  2770. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  2771. }
  2772. lineView.changes = null;
  2773. }
  2774. // Lines with gutter elements, widgets or a background class need to
  2775. // be wrapped, and have the extra elements added to the wrapper div
  2776. function ensureLineWrapped(lineView) {
  2777. if (lineView.node == lineView.text) {
  2778. lineView.node = elt("div", null, null, "position: relative");
  2779. if (lineView.text.parentNode)
  2780. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  2781. lineView.node.appendChild(lineView.text);
  2782. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  2783. }
  2784. return lineView.node;
  2785. }
  2786. function updateLineBackground(lineView) {
  2787. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  2788. if (cls) cls += " CodeMirror-linebackground";
  2789. if (lineView.background) {
  2790. if (cls) lineView.background.className = cls;
  2791. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  2792. } else if (cls) {
  2793. var wrap = ensureLineWrapped(lineView);
  2794. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  2795. }
  2796. }
  2797. // Wrapper around buildLineContent which will reuse the structure
  2798. // in display.externalMeasured when possible.
  2799. function getLineContent(cm, lineView) {
  2800. var ext = cm.display.externalMeasured;
  2801. if (ext && ext.line == lineView.line) {
  2802. cm.display.externalMeasured = null;
  2803. lineView.measure = ext.measure;
  2804. return ext.built;
  2805. }
  2806. return buildLineContent(cm, lineView);
  2807. }
  2808. // Redraw the line's text. Interacts with the background and text
  2809. // classes because the mode may output tokens that influence these
  2810. // classes.
  2811. function updateLineText(cm, lineView) {
  2812. var cls = lineView.text.className;
  2813. var built = getLineContent(cm, lineView);
  2814. if (lineView.text == lineView.node) lineView.node = built.pre;
  2815. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2816. lineView.text = built.pre;
  2817. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2818. lineView.bgClass = built.bgClass;
  2819. lineView.textClass = built.textClass;
  2820. updateLineClasses(lineView);
  2821. } else if (cls) {
  2822. lineView.text.className = cls;
  2823. }
  2824. }
  2825. function updateLineClasses(lineView) {
  2826. updateLineBackground(lineView);
  2827. if (lineView.line.wrapClass)
  2828. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  2829. else if (lineView.node != lineView.text)
  2830. lineView.node.className = "";
  2831. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2832. lineView.text.className = textClass || "";
  2833. }
  2834. function updateLineGutter(cm, lineView, lineN, dims) {
  2835. if (lineView.gutter) {
  2836. lineView.node.removeChild(lineView.gutter);
  2837. lineView.gutter = null;
  2838. }
  2839. if (lineView.gutterBackground) {
  2840. lineView.node.removeChild(lineView.gutterBackground);
  2841. lineView.gutterBackground = null;
  2842. }
  2843. if (lineView.line.gutterClass) {
  2844. var wrap = ensureLineWrapped(lineView);
  2845. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2846. "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  2847. "px; width: " + dims.gutterTotalWidth + "px");
  2848. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2849. }
  2850. var markers = lineView.line.gutterMarkers;
  2851. if (cm.options.lineNumbers || markers) {
  2852. var wrap = ensureLineWrapped(lineView);
  2853. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  2854. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
  2855. cm.display.input.setUneditable(gutterWrap);
  2856. wrap.insertBefore(gutterWrap, lineView.text);
  2857. if (lineView.line.gutterClass)
  2858. gutterWrap.className += " " + lineView.line.gutterClass;
  2859. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2860. lineView.lineNumber = gutterWrap.appendChild(
  2861. elt("div", lineNumberFor(cm.options, lineN),
  2862. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2863. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  2864. + cm.display.lineNumInnerWidth + "px"));
  2865. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  2866. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  2867. if (found)
  2868. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  2869. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  2870. }
  2871. }
  2872. }
  2873. function updateLineWidgets(cm, lineView, dims) {
  2874. if (lineView.alignable) lineView.alignable = null;
  2875. for (var node = lineView.node.firstChild, next; node; node = next) {
  2876. var next = node.nextSibling;
  2877. if (node.className == "CodeMirror-linewidget")
  2878. lineView.node.removeChild(node);
  2879. }
  2880. insertLineWidgets(cm, lineView, dims);
  2881. }
  2882. // Build a line's DOM representation from scratch
  2883. function buildLineElement(cm, lineView, lineN, dims) {
  2884. var built = getLineContent(cm, lineView);
  2885. lineView.text = lineView.node = built.pre;
  2886. if (built.bgClass) lineView.bgClass = built.bgClass;
  2887. if (built.textClass) lineView.textClass = built.textClass;
  2888. updateLineClasses(lineView);
  2889. updateLineGutter(cm, lineView, lineN, dims);
  2890. insertLineWidgets(cm, lineView, dims);
  2891. return lineView.node;
  2892. }
  2893. // A lineView may contain multiple logical lines (when merged by
  2894. // collapsed spans). The widgets for all of them need to be drawn.
  2895. function insertLineWidgets(cm, lineView, dims) {
  2896. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2897. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2898. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  2899. }
  2900. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2901. if (!line.widgets) return;
  2902. var wrap = ensureLineWrapped(lineView);
  2903. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2904. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  2905. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  2906. positionLineWidget(widget, node, lineView, dims);
  2907. cm.display.input.setUneditable(node);
  2908. if (allowAbove && widget.above)
  2909. wrap.insertBefore(node, lineView.gutter || lineView.text);
  2910. else
  2911. wrap.appendChild(node);
  2912. signalLater(widget, "redraw");
  2913. }
  2914. }
  2915. function positionLineWidget(widget, node, lineView, dims) {
  2916. if (widget.noHScroll) {
  2917. (lineView.alignable || (lineView.alignable = [])).push(node);
  2918. var width = dims.wrapperWidth;
  2919. node.style.left = dims.fixedPos + "px";
  2920. if (!widget.coverGutter) {
  2921. width -= dims.gutterTotalWidth;
  2922. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2923. }
  2924. node.style.width = width + "px";
  2925. }
  2926. if (widget.coverGutter) {
  2927. node.style.zIndex = 5;
  2928. node.style.position = "relative";
  2929. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  2930. }
  2931. }
  2932. // POSITION OBJECT
  2933. // A Pos instance represents a position within the text.
  2934. var Pos = CodeMirror.Pos = function(line, ch) {
  2935. if (!(this instanceof Pos)) return new Pos(line, ch);
  2936. this.line = line; this.ch = ch;
  2937. };
  2938. // Compare two positions, return 0 if they are the same, a negative
  2939. // number when a is less, and a positive number otherwise.
  2940. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  2941. function copyPos(x) {return Pos(x.line, x.ch);}
  2942. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  2943. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  2944. // INPUT HANDLING
  2945. function ensureFocus(cm) {
  2946. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  2947. }
  2948. // This will be set to a {lineWise: bool, text: [string]} object, so
  2949. // that, when pasting, we know what kind of selections the copied
  2950. // text was made out of.
  2951. var lastCopied = null;
  2952. function applyTextInput(cm, inserted, deleted, sel, origin) {
  2953. var doc = cm.doc;
  2954. cm.display.shift = false;
  2955. if (!sel) sel = doc.sel;
  2956. var paste = cm.state.pasteIncoming || origin == "paste";
  2957. var textLines = doc.splitLines(inserted), multiPaste = null
  2958. // When pasing N lines into N selections, insert one line per selection
  2959. if (paste && sel.ranges.length > 1) {
  2960. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  2961. if (sel.ranges.length % lastCopied.text.length == 0) {
  2962. multiPaste = [];
  2963. for (var i = 0; i < lastCopied.text.length; i++)
  2964. multiPaste.push(doc.splitLines(lastCopied.text[i]));
  2965. }
  2966. } else if (textLines.length == sel.ranges.length) {
  2967. multiPaste = map(textLines, function(l) { return [l]; });
  2968. }
  2969. }
  2970. // Normal behavior is to insert the new text into every selection
  2971. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  2972. var range = sel.ranges[i];
  2973. var from = range.from(), to = range.to();
  2974. if (range.empty()) {
  2975. if (deleted && deleted > 0) // Handle deletion
  2976. from = Pos(from.line, from.ch - deleted);
  2977. else if (cm.state.overwrite && !paste) // Handle overwrite
  2978. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  2979. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  2980. from = to = Pos(from.line, 0)
  2981. }
  2982. var updateInput = cm.curOp.updateInput;
  2983. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  2984. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  2985. makeChange(cm.doc, changeEvent);
  2986. signalLater(cm, "inputRead", cm, changeEvent);
  2987. }
  2988. if (inserted && !paste)
  2989. triggerElectric(cm, inserted);
  2990. ensureCursorVisible(cm);
  2991. cm.curOp.updateInput = updateInput;
  2992. cm.curOp.typing = true;
  2993. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  2994. }
  2995. function handlePaste(e, cm) {
  2996. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  2997. if (pasted) {
  2998. e.preventDefault();
  2999. if (!cm.isReadOnly() && !cm.options.disableInput)
  3000. runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
  3001. return true;
  3002. }
  3003. }
  3004. function triggerElectric(cm, inserted) {
  3005. // When an 'electric' character is inserted, immediately trigger a reindent
  3006. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  3007. var sel = cm.doc.sel;
  3008. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  3009. var range = sel.ranges[i];
  3010. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  3011. var mode = cm.getModeAt(range.head);
  3012. var indented = false;
  3013. if (mode.electricChars) {
  3014. for (var j = 0; j < mode.electricChars.length; j++)
  3015. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  3016. indented = indentLine(cm, range.head.line, "smart");
  3017. break;
  3018. }
  3019. } else if (mode.electricInput) {
  3020. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  3021. indented = indentLine(cm, range.head.line, "smart");
  3022. }
  3023. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  3024. }
  3025. }
  3026. function copyableRanges(cm) {
  3027. var text = [], ranges = [];
  3028. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  3029. var line = cm.doc.sel.ranges[i].head.line;
  3030. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  3031. ranges.push(lineRange);
  3032. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  3033. }
  3034. return {text: text, ranges: ranges};
  3035. }
  3036. function disableBrowserMagic(field) {
  3037. field.setAttribute("autocorrect", "off");
  3038. field.setAttribute("autocapitalize", "off");
  3039. field.setAttribute("spellcheck", "false");
  3040. }
  3041. // TEXTAREA INPUT STYLE
  3042. function TextareaInput(cm) {
  3043. this.cm = cm;
  3044. // See input.poll and input.reset
  3045. this.prevInput = "";
  3046. // Flag that indicates whether we expect input to appear real soon
  3047. // now (after some event like 'keypress' or 'input') and are
  3048. // polling intensively.
  3049. this.pollingFast = false;
  3050. // Self-resetting timeout for the poller
  3051. this.polling = new Delayed();
  3052. // Tracks when input.reset has punted to just putting a short
  3053. // string into the textarea instead of the full selection.
  3054. this.inaccurateSelection = false;
  3055. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  3056. this.hasSelection = false;
  3057. this.composing = null;
  3058. };
  3059. function hiddenTextarea() {
  3060. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  3061. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  3062. // The textarea is kept positioned near the cursor to prevent the
  3063. // fact that it'll be scrolled into view on input from scrolling
  3064. // our fake cursor out of view. On webkit, when wrap=off, paste is
  3065. // very slow. So make the area wide instead.
  3066. if (webkit) te.style.width = "1000px";
  3067. else te.setAttribute("wrap", "off");
  3068. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  3069. if (ios) te.style.border = "1px solid black";
  3070. disableBrowserMagic(te);
  3071. return div;
  3072. }
  3073. TextareaInput.prototype = copyObj({
  3074. init: function(display) {
  3075. var input = this, cm = this.cm;
  3076. // Wraps and hides input textarea
  3077. var div = this.wrapper = hiddenTextarea();
  3078. // The semihidden textarea that is focused when the editor is
  3079. // focused, and receives input.
  3080. var te = this.textarea = div.firstChild;
  3081. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  3082. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  3083. if (ios) te.style.width = "0px";
  3084. on(te, "input", function() {
  3085. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  3086. input.poll();
  3087. });
  3088. on(te, "paste", function(e) {
  3089. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  3090. cm.state.pasteIncoming = true;
  3091. input.fastPoll();
  3092. });
  3093. function prepareCopyCut(e) {
  3094. if (signalDOMEvent(cm, e)) return
  3095. if (cm.somethingSelected()) {
  3096. lastCopied = {lineWise: false, text: cm.getSelections()};
  3097. if (input.inaccurateSelection) {
  3098. input.prevInput = "";
  3099. input.inaccurateSelection = false;
  3100. te.value = lastCopied.text.join("\n");
  3101. selectInput(te);
  3102. }
  3103. } else if (!cm.options.lineWiseCopyCut) {
  3104. return;
  3105. } else {
  3106. var ranges = copyableRanges(cm);
  3107. lastCopied = {lineWise: true, text: ranges.text};
  3108. if (e.type == "cut") {
  3109. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  3110. } else {
  3111. input.prevInput = "";
  3112. te.value = ranges.text.join("\n");
  3113. selectInput(te);
  3114. }
  3115. }
  3116. if (e.type == "cut") cm.state.cutIncoming = true;
  3117. }
  3118. on(te, "cut", prepareCopyCut);
  3119. on(te, "copy", prepareCopyCut);
  3120. on(display.scroller, "paste", function(e) {
  3121. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
  3122. cm.state.pasteIncoming = true;
  3123. input.focus();
  3124. });
  3125. // Prevent normal selection in the editor (we handle our own)
  3126. on(display.lineSpace, "selectstart", function(e) {
  3127. if (!eventInWidget(display, e)) e_preventDefault(e);
  3128. });
  3129. on(te, "compositionstart", function() {
  3130. var start = cm.getCursor("from");
  3131. if (input.composing) input.composing.range.clear()
  3132. input.composing = {
  3133. start: start,
  3134. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  3135. };
  3136. });
  3137. on(te, "compositionend", function() {
  3138. if (input.composing) {
  3139. input.poll();
  3140. input.composing.range.clear();
  3141. input.composing = null;
  3142. }
  3143. });
  3144. },
  3145. prepareSelection: function() {
  3146. // Redraw the selection and/or cursor
  3147. var cm = this.cm, display = cm.display, doc = cm.doc;
  3148. var result = prepareSelection(cm);
  3149. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  3150. if (cm.options.moveInputWithCursor) {
  3151. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  3152. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  3153. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  3154. headPos.top + lineOff.top - wrapOff.top));
  3155. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  3156. headPos.left + lineOff.left - wrapOff.left));
  3157. }
  3158. return result;
  3159. },
  3160. showSelection: function(drawn) {
  3161. var cm = this.cm, display = cm.display;
  3162. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  3163. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  3164. if (drawn.teTop != null) {
  3165. this.wrapper.style.top = drawn.teTop + "px";
  3166. this.wrapper.style.left = drawn.teLeft + "px";
  3167. }
  3168. },
  3169. // Reset the input to correspond to the selection (or to be empty,
  3170. // when not typing and nothing is selected)
  3171. reset: function(typing) {
  3172. if (this.contextMenuPending) return;
  3173. var minimal, selected, cm = this.cm, doc = cm.doc;
  3174. if (cm.somethingSelected()) {
  3175. this.prevInput = "";
  3176. var range = doc.sel.primary();
  3177. minimal = hasCopyEvent &&
  3178. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  3179. var content = minimal ? "-" : selected || cm.getSelection();
  3180. this.textarea.value = content;
  3181. if (cm.state.focused) selectInput(this.textarea);
  3182. if (ie && ie_version >= 9) this.hasSelection = content;
  3183. } else if (!typing) {
  3184. this.prevInput = this.textarea.value = "";
  3185. if (ie && ie_version >= 9) this.hasSelection = null;
  3186. }
  3187. this.inaccurateSelection = minimal;
  3188. },
  3189. getField: function() { return this.textarea; },
  3190. supportsTouch: function() { return false; },
  3191. focus: function() {
  3192. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  3193. try { this.textarea.focus(); }
  3194. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  3195. }
  3196. },
  3197. blur: function() { this.textarea.blur(); },
  3198. resetPosition: function() {
  3199. this.wrapper.style.top = this.wrapper.style.left = 0;
  3200. },
  3201. receivedFocus: function() { this.slowPoll(); },
  3202. // Poll for input changes, using the normal rate of polling. This
  3203. // runs as long as the editor is focused.
  3204. slowPoll: function() {
  3205. var input = this;
  3206. if (input.pollingFast) return;
  3207. input.polling.set(this.cm.options.pollInterval, function() {
  3208. input.poll();
  3209. if (input.cm.state.focused) input.slowPoll();
  3210. });
  3211. },
  3212. // When an event has just come in that is likely to add or change
  3213. // something in the input textarea, we poll faster, to ensure that
  3214. // the change appears on the screen quickly.
  3215. fastPoll: function() {
  3216. var missed = false, input = this;
  3217. input.pollingFast = true;
  3218. function p() {
  3219. var changed = input.poll();
  3220. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  3221. else {input.pollingFast = false; input.slowPoll();}
  3222. }
  3223. input.polling.set(20, p);
  3224. },
  3225. // Read input from the textarea, and update the document to match.
  3226. // When something is selected, it is present in the textarea, and
  3227. // selected (unless it is huge, in which case a placeholder is
  3228. // used). When nothing is selected, the cursor sits after previously
  3229. // seen text (can be empty), which is stored in prevInput (we must
  3230. // not reset the textarea when typing, because that breaks IME).
  3231. poll: function() {
  3232. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  3233. // Since this is called a *lot*, try to bail out as cheaply as
  3234. // possible when it is clear that nothing happened. hasSelection
  3235. // will be the case when there is a lot of text in the textarea,
  3236. // in which case reading its value would be expensive.
  3237. if (this.contextMenuPending || !cm.state.focused ||
  3238. (hasSelection(input) && !prevInput && !this.composing) ||
  3239. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  3240. return false;
  3241. var text = input.value;
  3242. // If nothing changed, bail.
  3243. if (text == prevInput && !cm.somethingSelected()) return false;
  3244. // Work around nonsensical selection resetting in IE9/10, and
  3245. // inexplicable appearance of private area unicode characters on
  3246. // some key combos in Mac (#2689).
  3247. if (ie && ie_version >= 9 && this.hasSelection === text ||
  3248. mac && /[\uf700-\uf7ff]/.test(text)) {
  3249. cm.display.input.reset();
  3250. return false;
  3251. }
  3252. if (cm.doc.sel == cm.display.selForContextMenu) {
  3253. var first = text.charCodeAt(0);
  3254. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  3255. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  3256. }
  3257. // Find the part of the input that is actually new
  3258. var same = 0, l = Math.min(prevInput.length, text.length);
  3259. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  3260. var self = this;
  3261. runInOp(cm, function() {
  3262. applyTextInput(cm, text.slice(same), prevInput.length - same,
  3263. null, self.composing ? "*compose" : null);
  3264. // Don't leave long text in the textarea, since it makes further polling slow
  3265. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  3266. else self.prevInput = text;
  3267. if (self.composing) {
  3268. self.composing.range.clear();
  3269. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  3270. {className: "CodeMirror-composing"});
  3271. }
  3272. });
  3273. return true;
  3274. },
  3275. ensurePolled: function() {
  3276. if (this.pollingFast && this.poll()) this.pollingFast = false;
  3277. },
  3278. onKeyPress: function() {
  3279. if (ie && ie_version >= 9) this.hasSelection = null;
  3280. this.fastPoll();
  3281. },
  3282. onContextMenu: function(e) {
  3283. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  3284. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  3285. if (!pos || presto) return; // Opera is difficult.
  3286. // Reset the current text selection only if the click is done outside of the selection
  3287. // and 'resetSelectionOnContextMenu' option is true.
  3288. var reset = cm.options.resetSelectionOnContextMenu;
  3289. if (reset && cm.doc.sel.contains(pos) == -1)
  3290. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  3291. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  3292. input.wrapper.style.cssText = "position: absolute"
  3293. var wrapperBox = input.wrapper.getBoundingClientRect()
  3294. te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
  3295. "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
  3296. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  3297. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  3298. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  3299. display.input.focus();
  3300. if (webkit) window.scrollTo(null, oldScrollY);
  3301. display.input.reset();
  3302. // Adds "Select all" to context menu in FF
  3303. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  3304. input.contextMenuPending = true;
  3305. display.selForContextMenu = cm.doc.sel;
  3306. clearTimeout(display.detectingSelectAll);
  3307. // Select-all will be greyed out if there's nothing to select, so
  3308. // this adds a zero-width space so that we can later check whether
  3309. // it got selected.
  3310. function prepareSelectAllHack() {
  3311. if (te.selectionStart != null) {
  3312. var selected = cm.somethingSelected();
  3313. var extval = "\u200b" + (selected ? te.value : "");
  3314. te.value = "\u21da"; // Used to catch context-menu undo
  3315. te.value = extval;
  3316. input.prevInput = selected ? "" : "\u200b";
  3317. te.selectionStart = 1; te.selectionEnd = extval.length;
  3318. // Re-set this, in case some other handler touched the
  3319. // selection in the meantime.
  3320. display.selForContextMenu = cm.doc.sel;
  3321. }
  3322. }
  3323. function rehide() {
  3324. input.contextMenuPending = false;
  3325. input.wrapper.style.cssText = oldWrapperCSS
  3326. te.style.cssText = oldCSS;
  3327. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  3328. // Try to detect the user choosing select-all
  3329. if (te.selectionStart != null) {
  3330. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  3331. var i = 0, poll = function() {
  3332. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  3333. te.selectionEnd > 0 && input.prevInput == "\u200b")
  3334. operation(cm, commands.selectAll)(cm);
  3335. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  3336. else display.input.reset();
  3337. };
  3338. display.detectingSelectAll = setTimeout(poll, 200);
  3339. }
  3340. }
  3341. if (ie && ie_version >= 9) prepareSelectAllHack();
  3342. if (captureRightClick) {
  3343. e_stop(e);
  3344. var mouseup = function() {
  3345. off(window, "mouseup", mouseup);
  3346. setTimeout(rehide, 20);
  3347. };
  3348. on(window, "mouseup", mouseup);
  3349. } else {
  3350. setTimeout(rehide, 50);
  3351. }
  3352. },
  3353. readOnlyChanged: function(val) {
  3354. if (!val) this.reset();
  3355. },
  3356. setUneditable: nothing,
  3357. needsContentAttribute: false
  3358. }, TextareaInput.prototype);
  3359. // CONTENTEDITABLE INPUT STYLE
  3360. function ContentEditableInput(cm) {
  3361. this.cm = cm;
  3362. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  3363. this.polling = new Delayed();
  3364. this.gracePeriod = false;
  3365. }
  3366. ContentEditableInput.prototype = copyObj({
  3367. init: function(display) {
  3368. var input = this, cm = input.cm;
  3369. var div = input.div = display.lineDiv;
  3370. disableBrowserMagic(div);
  3371. on(div, "paste", function(e) {
  3372. if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
  3373. })
  3374. on(div, "compositionstart", function(e) {
  3375. var data = e.data;
  3376. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  3377. if (!data) return;
  3378. var prim = cm.doc.sel.primary();
  3379. var line = cm.getLine(prim.head.line);
  3380. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  3381. if (found > -1 && found <= prim.head.ch)
  3382. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  3383. Pos(prim.head.line, found + data.length));
  3384. });
  3385. on(div, "compositionupdate", function(e) {
  3386. input.composing.data = e.data;
  3387. });
  3388. on(div, "compositionend", function(e) {
  3389. var ours = input.composing;
  3390. if (!ours) return;
  3391. if (e.data != ours.startData && !/\u200b/.test(e.data))
  3392. ours.data = e.data;
  3393. // Need a small delay to prevent other code (input event,
  3394. // selection polling) from doing damage when fired right after
  3395. // compositionend.
  3396. setTimeout(function() {
  3397. if (!ours.handled)
  3398. input.applyComposition(ours);
  3399. if (input.composing == ours)
  3400. input.composing = null;
  3401. }, 50);
  3402. });
  3403. on(div, "touchstart", function() {
  3404. input.forceCompositionEnd();
  3405. });
  3406. on(div, "input", function() {
  3407. if (input.composing) return;
  3408. if (cm.isReadOnly() || !input.pollContent())
  3409. runInOp(input.cm, function() {regChange(cm);});
  3410. });
  3411. function onCopyCut(e) {
  3412. if (signalDOMEvent(cm, e)) return
  3413. if (cm.somethingSelected()) {
  3414. lastCopied = {lineWise: false, text: cm.getSelections()};
  3415. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  3416. } else if (!cm.options.lineWiseCopyCut) {
  3417. return;
  3418. } else {
  3419. var ranges = copyableRanges(cm);
  3420. lastCopied = {lineWise: true, text: ranges.text};
  3421. if (e.type == "cut") {
  3422. cm.operation(function() {
  3423. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  3424. cm.replaceSelection("", null, "cut");
  3425. });
  3426. }
  3427. }
  3428. // iOS exposes the clipboard API, but seems to discard content inserted into it
  3429. if (e.clipboardData && !ios) {
  3430. e.preventDefault();
  3431. e.clipboardData.clearData();
  3432. e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
  3433. } else {
  3434. // Old-fashioned briefly-focus-a-textarea hack
  3435. var kludge = hiddenTextarea(), te = kludge.firstChild;
  3436. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  3437. te.value = lastCopied.text.join("\n");
  3438. var hadFocus = document.activeElement;
  3439. selectInput(te);
  3440. setTimeout(function() {
  3441. cm.display.lineSpace.removeChild(kludge);
  3442. hadFocus.focus();
  3443. }, 50);
  3444. }
  3445. }
  3446. on(div, "copy", onCopyCut);
  3447. on(div, "cut", onCopyCut);
  3448. },
  3449. prepareSelection: function() {
  3450. var result = prepareSelection(this.cm, false);
  3451. result.focus = this.cm.state.focused;
  3452. return result;
  3453. },
  3454. showSelection: function(info, takeFocus) {
  3455. if (!info || !this.cm.display.view.length) return;
  3456. if (info.focus || takeFocus) this.showPrimarySelection();
  3457. this.showMultipleSelections(info);
  3458. },
  3459. showPrimarySelection: function() {
  3460. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  3461. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  3462. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  3463. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  3464. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  3465. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  3466. return;
  3467. var start = posToDOM(this.cm, prim.from());
  3468. var end = posToDOM(this.cm, prim.to());
  3469. if (!start && !end) return;
  3470. var view = this.cm.display.view;
  3471. var old = sel.rangeCount && sel.getRangeAt(0);
  3472. if (!start) {
  3473. start = {node: view[0].measure.map[2], offset: 0};
  3474. } else if (!end) { // FIXME dangerously hacky
  3475. var measure = view[view.length - 1].measure;
  3476. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  3477. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  3478. }
  3479. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  3480. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  3481. if (rng) {
  3482. if (!gecko && this.cm.state.focused) {
  3483. sel.collapse(start.node, start.offset);
  3484. if (!rng.collapsed) sel.addRange(rng);
  3485. } else {
  3486. sel.removeAllRanges();
  3487. sel.addRange(rng);
  3488. }
  3489. if (old && sel.anchorNode == null) sel.addRange(old);
  3490. else if (gecko) this.startGracePeriod();
  3491. }
  3492. this.rememberSelection();
  3493. },
  3494. startGracePeriod: function() {
  3495. var input = this;
  3496. clearTimeout(this.gracePeriod);
  3497. this.gracePeriod = setTimeout(function() {
  3498. input.gracePeriod = false;
  3499. if (input.selectionChanged())
  3500. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  3501. }, 20);
  3502. },
  3503. showMultipleSelections: function(info) {
  3504. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  3505. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  3506. },
  3507. rememberSelection: function() {
  3508. var sel = window.getSelection();
  3509. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  3510. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  3511. },
  3512. selectionInEditor: function() {
  3513. var sel = window.getSelection();
  3514. if (!sel.rangeCount) return false;
  3515. var node = sel.getRangeAt(0).commonAncestorContainer;
  3516. return contains(this.div, node);
  3517. },
  3518. focus: function() {
  3519. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  3520. },
  3521. blur: function() { this.div.blur(); },
  3522. getField: function() { return this.div; },
  3523. supportsTouch: function() { return true; },
  3524. receivedFocus: function() {
  3525. var input = this;
  3526. if (this.selectionInEditor())
  3527. this.pollSelection();
  3528. else
  3529. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  3530. function poll() {
  3531. if (input.cm.state.focused) {
  3532. input.pollSelection();
  3533. input.polling.set(input.cm.options.pollInterval, poll);
  3534. }
  3535. }
  3536. this.polling.set(this.cm.options.pollInterval, poll);
  3537. },
  3538. selectionChanged: function() {
  3539. var sel = window.getSelection();
  3540. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  3541. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  3542. },
  3543. pollSelection: function() {
  3544. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  3545. var sel = window.getSelection(), cm = this.cm;
  3546. this.rememberSelection();
  3547. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  3548. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  3549. if (anchor && head) runInOp(cm, function() {
  3550. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  3551. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  3552. });
  3553. }
  3554. },
  3555. pollContent: function() {
  3556. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  3557. var from = sel.from(), to = sel.to();
  3558. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  3559. var fromIndex;
  3560. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  3561. var fromLine = lineNo(display.view[0].line);
  3562. var fromNode = display.view[0].node;
  3563. } else {
  3564. var fromLine = lineNo(display.view[fromIndex].line);
  3565. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  3566. }
  3567. var toIndex = findViewIndex(cm, to.line);
  3568. if (toIndex == display.view.length - 1) {
  3569. var toLine = display.viewTo - 1;
  3570. var toNode = display.lineDiv.lastChild;
  3571. } else {
  3572. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  3573. var toNode = display.view[toIndex + 1].node.previousSibling;
  3574. }
  3575. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  3576. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  3577. while (newText.length > 1 && oldText.length > 1) {
  3578. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  3579. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  3580. else break;
  3581. }
  3582. var cutFront = 0, cutEnd = 0;
  3583. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  3584. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  3585. ++cutFront;
  3586. var newBot = lst(newText), oldBot = lst(oldText);
  3587. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  3588. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  3589. while (cutEnd < maxCutEnd &&
  3590. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  3591. ++cutEnd;
  3592. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  3593. newText[0] = newText[0].slice(cutFront);
  3594. var chFrom = Pos(fromLine, cutFront);
  3595. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  3596. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  3597. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  3598. return true;
  3599. }
  3600. },
  3601. ensurePolled: function() {
  3602. this.forceCompositionEnd();
  3603. },
  3604. reset: function() {
  3605. this.forceCompositionEnd();
  3606. },
  3607. forceCompositionEnd: function() {
  3608. if (!this.composing || this.composing.handled) return;
  3609. this.applyComposition(this.composing);
  3610. this.composing.handled = true;
  3611. this.div.blur();
  3612. this.div.focus();
  3613. },
  3614. applyComposition: function(composing) {
  3615. if (this.cm.isReadOnly())
  3616. operation(this.cm, regChange)(this.cm)
  3617. else if (composing.data && composing.data != composing.startData)
  3618. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  3619. },
  3620. setUneditable: function(node) {
  3621. node.contentEditable = "false"
  3622. },
  3623. onKeyPress: function(e) {
  3624. e.preventDefault();
  3625. if (!this.cm.isReadOnly())
  3626. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  3627. },
  3628. readOnlyChanged: function(val) {
  3629. this.div.contentEditable = String(val != "nocursor")
  3630. },
  3631. onContextMenu: nothing,
  3632. resetPosition: nothing,
  3633. needsContentAttribute: true
  3634. }, ContentEditableInput.prototype);
  3635. function posToDOM(cm, pos) {
  3636. var view = findViewForLine(cm, pos.line);
  3637. if (!view || view.hidden) return null;
  3638. var line = getLine(cm.doc, pos.line);
  3639. var info = mapFromLineView(view, line, pos.line);
  3640. var order = getOrder(line), side = "left";
  3641. if (order) {
  3642. var partPos = getBidiPartAt(order, pos.ch);
  3643. side = partPos % 2 ? "right" : "left";
  3644. }
  3645. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  3646. result.offset = result.collapse == "right" ? result.end : result.start;
  3647. return result;
  3648. }
  3649. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  3650. function domToPos(cm, node, offset) {
  3651. var lineNode;
  3652. if (node == cm.display.lineDiv) {
  3653. lineNode = cm.display.lineDiv.childNodes[offset];
  3654. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  3655. node = null; offset = 0;
  3656. } else {
  3657. for (lineNode = node;; lineNode = lineNode.parentNode) {
  3658. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  3659. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  3660. }
  3661. }
  3662. for (var i = 0; i < cm.display.view.length; i++) {
  3663. var lineView = cm.display.view[i];
  3664. if (lineView.node == lineNode)
  3665. return locateNodeInLineView(lineView, node, offset);
  3666. }
  3667. }
  3668. function locateNodeInLineView(lineView, node, offset) {
  3669. var wrapper = lineView.text.firstChild, bad = false;
  3670. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  3671. if (node == wrapper) {
  3672. bad = true;
  3673. node = wrapper.childNodes[offset];
  3674. offset = 0;
  3675. if (!node) {
  3676. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  3677. return badPos(Pos(lineNo(line), line.text.length), bad);
  3678. }
  3679. }
  3680. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  3681. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  3682. textNode = node.firstChild;
  3683. if (offset) offset = textNode.nodeValue.length;
  3684. }
  3685. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  3686. var measure = lineView.measure, maps = measure.maps;
  3687. function find(textNode, topNode, offset) {
  3688. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  3689. var map = i < 0 ? measure.map : maps[i];
  3690. for (var j = 0; j < map.length; j += 3) {
  3691. var curNode = map[j + 2];
  3692. if (curNode == textNode || curNode == topNode) {
  3693. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  3694. var ch = map[j] + offset;
  3695. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  3696. return Pos(line, ch);
  3697. }
  3698. }
  3699. }
  3700. }
  3701. var found = find(textNode, topNode, offset);
  3702. if (found) return badPos(found, bad);
  3703. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  3704. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  3705. found = find(after, after.firstChild, 0);
  3706. if (found)
  3707. return badPos(Pos(found.line, found.ch - dist), bad);
  3708. else
  3709. dist += after.textContent.length;
  3710. }
  3711. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  3712. found = find(before, before.firstChild, -1);
  3713. if (found)
  3714. return badPos(Pos(found.line, found.ch + dist), bad);
  3715. else
  3716. dist += after.textContent.length;
  3717. }
  3718. }
  3719. function domTextBetween(cm, from, to, fromLine, toLine) {
  3720. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  3721. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  3722. function walk(node) {
  3723. if (node.nodeType == 1) {
  3724. var cmText = node.getAttribute("cm-text");
  3725. if (cmText != null) {
  3726. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  3727. text += cmText;
  3728. return;
  3729. }
  3730. var markerID = node.getAttribute("cm-marker"), range;
  3731. if (markerID) {
  3732. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  3733. if (found.length && (range = found[0].find()))
  3734. text += getBetween(cm.doc, range.from, range.to).join(lineSep);
  3735. return;
  3736. }
  3737. if (node.getAttribute("contenteditable") == "false") return;
  3738. for (var i = 0; i < node.childNodes.length; i++)
  3739. walk(node.childNodes[i]);
  3740. if (/^(pre|div|p)$/i.test(node.nodeName))
  3741. closing = true;
  3742. } else if (node.nodeType == 3) {
  3743. var val = node.nodeValue;
  3744. if (!val) return;
  3745. if (closing) {
  3746. text += lineSep;
  3747. closing = false;
  3748. }
  3749. text += val;
  3750. }
  3751. }
  3752. for (;;) {
  3753. walk(from);
  3754. if (from == to) break;
  3755. from = from.nextSibling;
  3756. }
  3757. return text;
  3758. }
  3759. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  3760. // SELECTION / CURSOR
  3761. // Selection objects are immutable. A new one is created every time
  3762. // the selection changes. A selection is one or more non-overlapping
  3763. // (and non-touching) ranges, sorted, and an integer that indicates
  3764. // which one is the primary selection (the one that's scrolled into
  3765. // view, that getCursor returns, etc).
  3766. function Selection(ranges, primIndex) {
  3767. this.ranges = ranges;
  3768. this.primIndex = primIndex;
  3769. }
  3770. Selection.prototype = {
  3771. primary: function() { return this.ranges[this.primIndex]; },
  3772. equals: function(other) {
  3773. if (other == this) return true;
  3774. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  3775. for (var i = 0; i < this.ranges.length; i++) {
  3776. var here = this.ranges[i], there = other.ranges[i];
  3777. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  3778. }
  3779. return true;
  3780. },
  3781. deepCopy: function() {
  3782. for (var out = [], i = 0; i < this.ranges.length; i++)
  3783. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  3784. return new Selection(out, this.primIndex);
  3785. },
  3786. somethingSelected: function() {
  3787. for (var i = 0; i < this.ranges.length; i++)
  3788. if (!this.ranges[i].empty()) return true;
  3789. return false;
  3790. },
  3791. contains: function(pos, end) {
  3792. if (!end) end = pos;
  3793. for (var i = 0; i < this.ranges.length; i++) {
  3794. var range = this.ranges[i];
  3795. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  3796. return i;
  3797. }
  3798. return -1;
  3799. }
  3800. };
  3801. function Range(anchor, head) {
  3802. this.anchor = anchor; this.head = head;
  3803. }
  3804. Range.prototype = {
  3805. from: function() { return minPos(this.anchor, this.head); },
  3806. to: function() { return maxPos(this.anchor, this.head); },
  3807. empty: function() {
  3808. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  3809. }
  3810. };
  3811. // Take an unsorted, potentially overlapping set of ranges, and
  3812. // build a selection out of it. 'Consumes' ranges array (modifying
  3813. // it).
  3814. function normalizeSelection(ranges, primIndex) {
  3815. var prim = ranges[primIndex];
  3816. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  3817. primIndex = indexOf(ranges, prim);
  3818. for (var i = 1; i < ranges.length; i++) {
  3819. var cur = ranges[i], prev = ranges[i - 1];
  3820. if (cmp(prev.to(), cur.from()) >= 0) {
  3821. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  3822. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  3823. if (i <= primIndex) --primIndex;
  3824. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  3825. }
  3826. }
  3827. return new Selection(ranges, primIndex);
  3828. }
  3829. function simpleSelection(anchor, head) {
  3830. return new Selection([new Range(anchor, head || anchor)], 0);
  3831. }
  3832. // Most of the external API clips given positions to make sure they
  3833. // actually exist within the document.
  3834. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  3835. function clipPos(doc, pos) {
  3836. if (pos.line < doc.first) return Pos(doc.first, 0);
  3837. var last = doc.first + doc.size - 1;
  3838. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  3839. return clipToLen(pos, getLine(doc, pos.line).text.length);
  3840. }
  3841. function clipToLen(pos, linelen) {
  3842. var ch = pos.ch;
  3843. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  3844. else if (ch < 0) return Pos(pos.line, 0);
  3845. else return pos;
  3846. }
  3847. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  3848. function clipPosArray(doc, array) {
  3849. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  3850. return out;
  3851. }
  3852. // SELECTION UPDATES
  3853. // The 'scroll' parameter given to many of these indicated whether
  3854. // the new cursor position should be scrolled into view after
  3855. // modifying the selection.
  3856. // If shift is held or the extend flag is set, extends a range to
  3857. // include a given position (and optionally a second position).
  3858. // Otherwise, simply returns the range between the given positions.
  3859. // Used for cursor motion and such.
  3860. function extendRange(doc, range, head, other) {
  3861. if (doc.cm && doc.cm.display.shift || doc.extend) {
  3862. var anchor = range.anchor;
  3863. if (other) {
  3864. var posBefore = cmp(head, anchor) < 0;
  3865. if (posBefore != (cmp(other, anchor) < 0)) {
  3866. anchor = head;
  3867. head = other;
  3868. } else if (posBefore != (cmp(head, other) < 0)) {
  3869. head = other;
  3870. }
  3871. }
  3872. return new Range(anchor, head);
  3873. } else {
  3874. return new Range(other || head, head);
  3875. }
  3876. }
  3877. // Extend the primary selection range, discard the rest.
  3878. function extendSelection(doc, head, other, options) {
  3879. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  3880. }
  3881. // Extend all selections (pos is an array of selections with length
  3882. // equal the number of selections)
  3883. function extendSelections(doc, heads, options) {
  3884. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  3885. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  3886. var newSel = normalizeSelection(out, doc.sel.primIndex);
  3887. setSelection(doc, newSel, options);
  3888. }
  3889. // Updates a single range in the selection.
  3890. function replaceOneSelection(doc, i, range, options) {
  3891. var ranges = doc.sel.ranges.slice(0);
  3892. ranges[i] = range;
  3893. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  3894. }
  3895. // Reset the selection to a single range.
  3896. function setSimpleSelection(doc, anchor, head, options) {
  3897. setSelection(doc, simpleSelection(anchor, head), options);
  3898. }
  3899. // Give beforeSelectionChange handlers a change to influence a
  3900. // selection update.
  3901. function filterSelectionChange(doc, sel, options) {
  3902. var obj = {
  3903. ranges: sel.ranges,
  3904. update: function(ranges) {
  3905. this.ranges = [];
  3906. for (var i = 0; i < ranges.length; i++)
  3907. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  3908. clipPos(doc, ranges[i].head));
  3909. },
  3910. origin: options && options.origin
  3911. };
  3912. signal(doc, "beforeSelectionChange", doc, obj);
  3913. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  3914. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  3915. else return sel;
  3916. }
  3917. function setSelectionReplaceHistory(doc, sel, options) {
  3918. var done = doc.history.done, last = lst(done);
  3919. if (last && last.ranges) {
  3920. done[done.length - 1] = sel;
  3921. setSelectionNoUndo(doc, sel, options);
  3922. } else {
  3923. setSelection(doc, sel, options);
  3924. }
  3925. }
  3926. // Set a new selection.
  3927. function setSelection(doc, sel, options) {
  3928. setSelectionNoUndo(doc, sel, options);
  3929. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  3930. }
  3931. function setSelectionNoUndo(doc, sel, options) {
  3932. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  3933. sel = filterSelectionChange(doc, sel, options);
  3934. var bias = options && options.bias ||
  3935. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  3936. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  3937. if (!(options && options.scroll === false) && doc.cm)
  3938. ensureCursorVisible(doc.cm);
  3939. }
  3940. function setSelectionInner(doc, sel) {
  3941. if (sel.equals(doc.sel)) return;
  3942. doc.sel = sel;
  3943. if (doc.cm) {
  3944. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  3945. signalCursorActivity(doc.cm);
  3946. }
  3947. signalLater(doc, "cursorActivity", doc);
  3948. }
  3949. // Verify that the selection does not partially select any atomic
  3950. // marked ranges.
  3951. function reCheckSelection(doc) {
  3952. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  3953. }
  3954. // Return a selection that does not partially select any atomic
  3955. // ranges.
  3956. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  3957. var out;
  3958. for (var i = 0; i < sel.ranges.length; i++) {
  3959. var range = sel.ranges[i];
  3960. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  3961. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  3962. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  3963. if (out || newAnchor != range.anchor || newHead != range.head) {
  3964. if (!out) out = sel.ranges.slice(0, i);
  3965. out[i] = new Range(newAnchor, newHead);
  3966. }
  3967. }
  3968. return out ? normalizeSelection(out, sel.primIndex) : sel;
  3969. }
  3970. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  3971. var line = getLine(doc, pos.line);
  3972. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  3973. var sp = line.markedSpans[i], m = sp.marker;
  3974. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  3975. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  3976. if (mayClear) {
  3977. signal(m, "beforeCursorEnter");
  3978. if (m.explicitlyCleared) {
  3979. if (!line.markedSpans) break;
  3980. else {--i; continue;}
  3981. }
  3982. }
  3983. if (!m.atomic) continue;
  3984. if (oldPos) {
  3985. var near = m.find(dir < 0 ? 1 : -1), diff;
  3986. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  3987. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
  3988. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  3989. return skipAtomicInner(doc, near, pos, dir, mayClear);
  3990. }
  3991. var far = m.find(dir < 0 ? -1 : 1);
  3992. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  3993. far = movePos(doc, far, dir, far.line == pos.line ? line : null);
  3994. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
  3995. }
  3996. }
  3997. return pos;
  3998. }
  3999. // Ensure a given position is not inside an atomic range.
  4000. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4001. var dir = bias || 1;
  4002. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4003. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4004. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4005. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4006. if (!found) {
  4007. doc.cantEdit = true;
  4008. return Pos(doc.first, 0);
  4009. }
  4010. return found;
  4011. }
  4012. function movePos(doc, pos, dir, line) {
  4013. if (dir < 0 && pos.ch == 0) {
  4014. if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
  4015. else return null;
  4016. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4017. if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
  4018. else return null;
  4019. } else {
  4020. return new Pos(pos.line, pos.ch + dir);
  4021. }
  4022. }
  4023. // SELECTION DRAWING
  4024. function updateSelection(cm) {
  4025. cm.display.input.showSelection(cm.display.input.prepareSelection());
  4026. }
  4027. function prepareSelection(cm, primary) {
  4028. var doc = cm.doc, result = {};
  4029. var curFragment = result.cursors = document.createDocumentFragment();
  4030. var selFragment = result.selection = document.createDocumentFragment();
  4031. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4032. if (primary === false && i == doc.sel.primIndex) continue;
  4033. var range = doc.sel.ranges[i];
  4034. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
  4035. var collapsed = range.empty();
  4036. if (collapsed || cm.options.showCursorWhenSelecting)
  4037. drawSelectionCursor(cm, range.head, curFragment);
  4038. if (!collapsed)
  4039. drawSelectionRange(cm, range, selFragment);
  4040. }
  4041. return result;
  4042. }
  4043. // Draws a cursor for the given range
  4044. function drawSelectionCursor(cm, head, output) {
  4045. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  4046. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  4047. cursor.style.left = pos.left + "px";
  4048. cursor.style.top = pos.top + "px";
  4049. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  4050. if (pos.other) {
  4051. // Secondary cursor, shown when on a 'jump' in bi-directional text
  4052. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  4053. otherCursor.style.display = "";
  4054. otherCursor.style.left = pos.other.left + "px";
  4055. otherCursor.style.top = pos.other.top + "px";
  4056. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  4057. }
  4058. }
  4059. // Draws the given range as a highlighted selection
  4060. function drawSelectionRange(cm, range, output) {
  4061. var display = cm.display, doc = cm.doc;
  4062. var fragment = document.createDocumentFragment();
  4063. var padding = paddingH(cm.display), leftSide = padding.left;
  4064. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  4065. function add(left, top, width, bottom) {
  4066. if (top < 0) top = 0;
  4067. top = Math.round(top);
  4068. bottom = Math.round(bottom);
  4069. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  4070. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  4071. "px; height: " + (bottom - top) + "px"));
  4072. }
  4073. function drawForLine(line, fromArg, toArg) {
  4074. var lineObj = getLine(doc, line);
  4075. var lineLen = lineObj.text.length;
  4076. var start, end;
  4077. function coords(ch, bias) {
  4078. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  4079. }
  4080. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  4081. var leftPos = coords(from, "left"), rightPos, left, right;
  4082. if (from == to) {
  4083. rightPos = leftPos;
  4084. left = right = leftPos.left;
  4085. } else {
  4086. rightPos = coords(to - 1, "right");
  4087. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  4088. left = leftPos.left;
  4089. right = rightPos.right;
  4090. }
  4091. if (fromArg == null && from == 0) left = leftSide;
  4092. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  4093. add(left, leftPos.top, null, leftPos.bottom);
  4094. left = leftSide;
  4095. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  4096. }
  4097. if (toArg == null && to == lineLen) right = rightSide;
  4098. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  4099. start = leftPos;
  4100. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  4101. end = rightPos;
  4102. if (left < leftSide + 1) left = leftSide;
  4103. add(left, rightPos.top, right - left, rightPos.bottom);
  4104. });
  4105. return {start: start, end: end};
  4106. }
  4107. var sFrom = range.from(), sTo = range.to();
  4108. if (sFrom.line == sTo.line) {
  4109. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  4110. } else {
  4111. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  4112. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  4113. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  4114. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  4115. if (singleVLine) {
  4116. if (leftEnd.top < rightStart.top - 2) {
  4117. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  4118. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  4119. } else {
  4120. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  4121. }
  4122. }
  4123. if (leftEnd.bottom < rightStart.top)
  4124. add(leftSide, leftEnd.bottom, null, rightStart.top);
  4125. }
  4126. output.appendChild(fragment);
  4127. }
  4128. // Cursor-blinking
  4129. function restartBlink(cm) {
  4130. if (!cm.state.focused) return;
  4131. var display = cm.display;
  4132. clearInterval(display.blinker);
  4133. var on = true;
  4134. display.cursorDiv.style.visibility = "";
  4135. if (cm.options.cursorBlinkRate > 0)
  4136. display.blinker = setInterval(function() {
  4137. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  4138. }, cm.options.cursorBlinkRate);
  4139. else if (cm.options.cursorBlinkRate < 0)
  4140. display.cursorDiv.style.visibility = "hidden";
  4141. }
  4142. // HIGHLIGHT WORKER
  4143. function startWorker(cm, time) {
  4144. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  4145. cm.state.highlight.set(time, bind(highlightWorker, cm));
  4146. }
  4147. function highlightWorker(cm) {
  4148. var doc = cm.doc;
  4149. if (doc.frontier < doc.first) doc.frontier = doc.first;
  4150. if (doc.frontier >= cm.display.viewTo) return;
  4151. var end = +new Date + cm.options.workTime;
  4152. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  4153. var changedLines = [];
  4154. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  4155. if (doc.frontier >= cm.display.viewFrom) { // Visible
  4156. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  4157. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  4158. line.styles = highlighted.styles;
  4159. var oldCls = line.styleClasses, newCls = highlighted.classes;
  4160. if (newCls) line.styleClasses = newCls;
  4161. else if (oldCls) line.styleClasses = null;
  4162. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  4163. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  4164. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  4165. if (ischange) changedLines.push(doc.frontier);
  4166. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  4167. } else {
  4168. if (line.text.length <= cm.options.maxHighlightLength)
  4169. processLine(cm, line.text, state);
  4170. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  4171. }
  4172. ++doc.frontier;
  4173. if (+new Date > end) {
  4174. startWorker(cm, cm.options.workDelay);
  4175. return true;
  4176. }
  4177. });
  4178. if (changedLines.length) runInOp(cm, function() {
  4179. for (var i = 0; i < changedLines.length; i++)
  4180. regLineChange(cm, changedLines[i], "text");
  4181. });
  4182. }
  4183. // Finds the line to start with when starting a parse. Tries to
  4184. // find a line with a stateAfter, so that it can start with a
  4185. // valid state. If that fails, it returns the line with the
  4186. // smallest indentation, which tends to need the least context to
  4187. // parse correctly.
  4188. function findStartLine(cm, n, precise) {
  4189. var minindent, minline, doc = cm.doc;
  4190. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  4191. for (var search = n; search > lim; --search) {
  4192. if (search <= doc.first) return doc.first;
  4193. var line = getLine(doc, search - 1);
  4194. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  4195. var indented = countColumn(line.text, null, cm.options.tabSize);
  4196. if (minline == null || minindent > indented) {
  4197. minline = search - 1;
  4198. minindent = indented;
  4199. }
  4200. }
  4201. return minline;
  4202. }
  4203. function getStateBefore(cm, n, precise) {
  4204. var doc = cm.doc, display = cm.display;
  4205. if (!doc.mode.startState) return true;
  4206. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  4207. if (!state) state = startState(doc.mode);
  4208. else state = copyState(doc.mode, state);
  4209. doc.iter(pos, n, function(line) {
  4210. processLine(cm, line.text, state);
  4211. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  4212. line.stateAfter = save ? copyState(doc.mode, state) : null;
  4213. ++pos;
  4214. });
  4215. if (precise) doc.frontier = pos;
  4216. return state;
  4217. }
  4218. // POSITION MEASUREMENT
  4219. function paddingTop(display) {return display.lineSpace.offsetTop;}
  4220. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  4221. function paddingH(display) {
  4222. if (display.cachedPaddingH) return display.cachedPaddingH;
  4223. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  4224. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  4225. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  4226. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  4227. return data;
  4228. }
  4229. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  4230. function displayWidth(cm) {
  4231. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  4232. }
  4233. function displayHeight(cm) {
  4234. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  4235. }
  4236. // Ensure the lineView.wrapping.heights array is populated. This is
  4237. // an array of bottom offsets for the lines that make up a drawn
  4238. // line. When lineWrapping is on, there might be more than one
  4239. // height.
  4240. function ensureLineHeights(cm, lineView, rect) {
  4241. var wrapping = cm.options.lineWrapping;
  4242. var curWidth = wrapping && displayWidth(cm);
  4243. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  4244. var heights = lineView.measure.heights = [];
  4245. if (wrapping) {
  4246. lineView.measure.width = curWidth;
  4247. var rects = lineView.text.firstChild.getClientRects();
  4248. for (var i = 0; i < rects.length - 1; i++) {
  4249. var cur = rects[i], next = rects[i + 1];
  4250. if (Math.abs(cur.bottom - next.bottom) > 2)
  4251. heights.push((cur.bottom + next.top) / 2 - rect.top);
  4252. }
  4253. }
  4254. heights.push(rect.bottom - rect.top);
  4255. }
  4256. }
  4257. // Find a line map (mapping character offsets to text nodes) and a
  4258. // measurement cache for the given line number. (A line view might
  4259. // contain multiple lines when collapsed ranges are present.)
  4260. function mapFromLineView(lineView, line, lineN) {
  4261. if (lineView.line == line)
  4262. return {map: lineView.measure.map, cache: lineView.measure.cache};
  4263. for (var i = 0; i < lineView.rest.length; i++)
  4264. if (lineView.rest[i] == line)
  4265. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  4266. for (var i = 0; i < lineView.rest.length; i++)
  4267. if (lineNo(lineView.rest[i]) > lineN)
  4268. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  4269. }
  4270. // Render a line into the hidden node display.externalMeasured. Used
  4271. // when measurement is needed for a line that's not in the viewport.
  4272. function updateExternalMeasurement(cm, line) {
  4273. line = visualLine(line);
  4274. var lineN = lineNo(line);
  4275. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  4276. view.lineN = lineN;
  4277. var built = view.built = buildLineContent(cm, view);
  4278. view.text = built.pre;
  4279. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  4280. return view;
  4281. }
  4282. // Get a {top, bottom, left, right} box (in line-local coordinates)
  4283. // for a given character.
  4284. function measureChar(cm, line, ch, bias) {
  4285. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  4286. }
  4287. // Find a line view that corresponds to the given line number.
  4288. function findViewForLine(cm, lineN) {
  4289. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  4290. return cm.display.view[findViewIndex(cm, lineN)];
  4291. var ext = cm.display.externalMeasured;
  4292. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  4293. return ext;
  4294. }
  4295. // Measurement can be split in two steps, the set-up work that
  4296. // applies to the whole line, and the measurement of the actual
  4297. // character. Functions like coordsChar, that need to do a lot of
  4298. // measurements in a row, can thus ensure that the set-up work is
  4299. // only done once.
  4300. function prepareMeasureForLine(cm, line) {
  4301. var lineN = lineNo(line);
  4302. var view = findViewForLine(cm, lineN);
  4303. if (view && !view.text) {
  4304. view = null;
  4305. } else if (view && view.changes) {
  4306. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  4307. cm.curOp.forceUpdate = true;
  4308. }
  4309. if (!view)
  4310. view = updateExternalMeasurement(cm, line);
  4311. var info = mapFromLineView(view, line, lineN);
  4312. return {
  4313. line: line, view: view, rect: null,
  4314. map: info.map, cache: info.cache, before: info.before,
  4315. hasHeights: false
  4316. };
  4317. }
  4318. // Given a prepared measurement object, measures the position of an
  4319. // actual character (or fetches it from the cache).
  4320. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  4321. if (prepared.before) ch = -1;
  4322. var key = ch + (bias || ""), found;
  4323. if (prepared.cache.hasOwnProperty(key)) {
  4324. found = prepared.cache[key];
  4325. } else {
  4326. if (!prepared.rect)
  4327. prepared.rect = prepared.view.text.getBoundingClientRect();
  4328. if (!prepared.hasHeights) {
  4329. ensureLineHeights(cm, prepared.view, prepared.rect);
  4330. prepared.hasHeights = true;
  4331. }
  4332. found = measureCharInner(cm, prepared, ch, bias);
  4333. if (!found.bogus) prepared.cache[key] = found;
  4334. }
  4335. return {left: found.left, right: found.right,
  4336. top: varHeight ? found.rtop : found.top,
  4337. bottom: varHeight ? found.rbottom : found.bottom};
  4338. }
  4339. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  4340. function nodeAndOffsetInLineMap(map, ch, bias) {
  4341. var node, start, end, collapse;
  4342. // First, search the line map for the text node corresponding to,
  4343. // or closest to, the target character.
  4344. for (var i = 0; i < map.length; i += 3) {
  4345. var mStart = map[i], mEnd = map[i + 1];
  4346. if (ch < mStart) {
  4347. start = 0; end = 1;
  4348. collapse = "left";
  4349. } else if (ch < mEnd) {
  4350. start = ch - mStart;
  4351. end = start + 1;
  4352. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  4353. end = mEnd - mStart;
  4354. start = end - 1;
  4355. if (ch >= mEnd) collapse = "right";
  4356. }
  4357. if (start != null) {
  4358. node = map[i + 2];
  4359. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  4360. collapse = bias;
  4361. if (bias == "left" && start == 0)
  4362. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  4363. node = map[(i -= 3) + 2];
  4364. collapse = "left";
  4365. }
  4366. if (bias == "right" && start == mEnd - mStart)
  4367. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  4368. node = map[(i += 3) + 2];
  4369. collapse = "right";
  4370. }
  4371. break;
  4372. }
  4373. }
  4374. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  4375. }
  4376. function measureCharInner(cm, prepared, ch, bias) {
  4377. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  4378. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  4379. var rect;
  4380. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  4381. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  4382. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  4383. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  4384. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  4385. rect = node.parentNode.getBoundingClientRect();
  4386. } else if (ie && cm.options.lineWrapping) {
  4387. var rects = range(node, start, end).getClientRects();
  4388. if (rects.length)
  4389. rect = rects[bias == "right" ? rects.length - 1 : 0];
  4390. else
  4391. rect = nullRect;
  4392. } else {
  4393. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  4394. }
  4395. if (rect.left || rect.right || start == 0) break;
  4396. end = start;
  4397. start = start - 1;
  4398. collapse = "right";
  4399. }
  4400. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  4401. } else { // If it is a widget, simply get the box for the whole widget.
  4402. if (start > 0) collapse = bias = "right";
  4403. var rects;
  4404. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  4405. rect = rects[bias == "right" ? rects.length - 1 : 0];
  4406. else
  4407. rect = node.getBoundingClientRect();
  4408. }
  4409. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  4410. var rSpan = node.parentNode.getClientRects()[0];
  4411. if (rSpan)
  4412. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  4413. else
  4414. rect = nullRect;
  4415. }
  4416. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  4417. var mid = (rtop + rbot) / 2;
  4418. var heights = prepared.view.measure.heights;
  4419. for (var i = 0; i < heights.length - 1; i++)
  4420. if (mid < heights[i]) break;
  4421. var top = i ? heights[i - 1] : 0, bot = heights[i];
  4422. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  4423. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  4424. top: top, bottom: bot};
  4425. if (!rect.left && !rect.right) result.bogus = true;
  4426. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  4427. return result;
  4428. }
  4429. // Work around problem with bounding client rects on ranges being
  4430. // returned incorrectly when zoomed on IE10 and below.
  4431. function maybeUpdateRectForZooming(measure, rect) {
  4432. if (!window.screen || screen.logicalXDPI == null ||
  4433. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  4434. return rect;
  4435. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  4436. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  4437. return {left: rect.left * scaleX, right: rect.right * scaleX,
  4438. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  4439. }
  4440. function clearLineMeasurementCacheFor(lineView) {
  4441. if (lineView.measure) {
  4442. lineView.measure.cache = {};
  4443. lineView.measure.heights = null;
  4444. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  4445. lineView.measure.caches[i] = {};
  4446. }
  4447. }
  4448. function clearLineMeasurementCache(cm) {
  4449. cm.display.externalMeasure = null;
  4450. removeChildren(cm.display.lineMeasure);
  4451. for (var i = 0; i < cm.display.view.length; i++)
  4452. clearLineMeasurementCacheFor(cm.display.view[i]);
  4453. }
  4454. function clearCaches(cm) {
  4455. clearLineMeasurementCache(cm);
  4456. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  4457. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  4458. cm.display.lineNumChars = null;
  4459. }
  4460. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  4461. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  4462. // Converts a {top, bottom, left, right} box from line-local
  4463. // coordinates into another coordinate system. Context may be one of
  4464. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  4465. // or "page".
  4466. function intoCoordSystem(cm, lineObj, rect, context) {
  4467. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  4468. var size = widgetHeight(lineObj.widgets[i]);
  4469. rect.top += size; rect.bottom += size;
  4470. }
  4471. if (context == "line") return rect;
  4472. if (!context) context = "local";
  4473. var yOff = heightAtLine(lineObj);
  4474. if (context == "local") yOff += paddingTop(cm.display);
  4475. else yOff -= cm.display.viewOffset;
  4476. if (context == "page" || context == "window") {
  4477. var lOff = cm.display.lineSpace.getBoundingClientRect();
  4478. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  4479. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  4480. rect.left += xOff; rect.right += xOff;
  4481. }
  4482. rect.top += yOff; rect.bottom += yOff;
  4483. return rect;
  4484. }
  4485. // Coverts a box from "div" coords to another coordinate system.
  4486. // Context may be "window", "page", "div", or "local"/null.
  4487. function fromCoordSystem(cm, coords, context) {
  4488. if (context == "div") return coords;
  4489. var left = coords.left, top = coords.top;
  4490. // First move into "page" coordinate system
  4491. if (context == "page") {
  4492. left -= pageScrollX();
  4493. top -= pageScrollY();
  4494. } else if (context == "local" || !context) {
  4495. var localBox = cm.display.sizer.getBoundingClientRect();
  4496. left += localBox.left;
  4497. top += localBox.top;
  4498. }
  4499. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  4500. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  4501. }
  4502. function charCoords(cm, pos, context, lineObj, bias) {
  4503. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  4504. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  4505. }
  4506. // Returns a box for a given cursor position, which may have an
  4507. // 'other' property containing the position of the secondary cursor
  4508. // on a bidi boundary.
  4509. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  4510. lineObj = lineObj || getLine(cm.doc, pos.line);
  4511. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4512. function get(ch, right) {
  4513. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  4514. if (right) m.left = m.right; else m.right = m.left;
  4515. return intoCoordSystem(cm, lineObj, m, context);
  4516. }
  4517. function getBidi(ch, partPos) {
  4518. var part = order[partPos], right = part.level % 2;
  4519. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  4520. part = order[--partPos];
  4521. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  4522. right = true;
  4523. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  4524. part = order[++partPos];
  4525. ch = bidiLeft(part) - part.level % 2;
  4526. right = false;
  4527. }
  4528. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  4529. return get(ch, right);
  4530. }
  4531. var order = getOrder(lineObj), ch = pos.ch;
  4532. if (!order) return get(ch);
  4533. var partPos = getBidiPartAt(order, ch);
  4534. var val = getBidi(ch, partPos);
  4535. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  4536. return val;
  4537. }
  4538. // Used to cheaply estimate the coordinates for a position. Used for
  4539. // intermediate scroll updates.
  4540. function estimateCoords(cm, pos) {
  4541. var left = 0, pos = clipPos(cm.doc, pos);
  4542. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  4543. var lineObj = getLine(cm.doc, pos.line);
  4544. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  4545. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  4546. }
  4547. // Positions returned by coordsChar contain some extra information.
  4548. // xRel is the relative x position of the input coordinates compared
  4549. // to the found position (so xRel > 0 means the coordinates are to
  4550. // the right of the character position, for example). When outside
  4551. // is true, that means the coordinates lie outside the line's
  4552. // vertical range.
  4553. function PosWithInfo(line, ch, outside, xRel) {
  4554. var pos = Pos(line, ch);
  4555. pos.xRel = xRel;
  4556. if (outside) pos.outside = true;
  4557. return pos;
  4558. }
  4559. // Compute the character position closest to the given coordinates.
  4560. // Input must be lineSpace-local ("div" coordinate system).
  4561. function coordsChar(cm, x, y) {
  4562. var doc = cm.doc;
  4563. y += cm.display.viewOffset;
  4564. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  4565. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  4566. if (lineN > last)
  4567. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  4568. if (x < 0) x = 0;
  4569. var lineObj = getLine(doc, lineN);
  4570. for (;;) {
  4571. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  4572. var merged = collapsedSpanAtEnd(lineObj);
  4573. var mergedPos = merged && merged.find(0, true);
  4574. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  4575. lineN = lineNo(lineObj = mergedPos.to.line);
  4576. else
  4577. return found;
  4578. }
  4579. }
  4580. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  4581. var innerOff = y - heightAtLine(lineObj);
  4582. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  4583. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4584. function getX(ch) {
  4585. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  4586. wrongLine = true;
  4587. if (innerOff > sp.bottom) return sp.left - adjust;
  4588. else if (innerOff < sp.top) return sp.left + adjust;
  4589. else wrongLine = false;
  4590. return sp.left;
  4591. }
  4592. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  4593. var from = lineLeft(lineObj), to = lineRight(lineObj);
  4594. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  4595. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  4596. // Do a binary search between these bounds.
  4597. for (;;) {
  4598. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  4599. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  4600. var xDiff = x - (ch == from ? fromX : toX);
  4601. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  4602. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  4603. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  4604. return pos;
  4605. }
  4606. var step = Math.ceil(dist / 2), middle = from + step;
  4607. if (bidi) {
  4608. middle = from;
  4609. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  4610. }
  4611. var middleX = getX(middle);
  4612. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  4613. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  4614. }
  4615. }
  4616. var measureText;
  4617. // Compute the default text height.
  4618. function textHeight(display) {
  4619. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  4620. if (measureText == null) {
  4621. measureText = elt("pre");
  4622. // Measure a bunch of lines, for browsers that compute
  4623. // fractional heights.
  4624. for (var i = 0; i < 49; ++i) {
  4625. measureText.appendChild(document.createTextNode("x"));
  4626. measureText.appendChild(elt("br"));
  4627. }
  4628. measureText.appendChild(document.createTextNode("x"));
  4629. }
  4630. removeChildrenAndAdd(display.measure, measureText);
  4631. var height = measureText.offsetHeight / 50;
  4632. if (height > 3) display.cachedTextHeight = height;
  4633. removeChildren(display.measure);
  4634. return height || 1;
  4635. }
  4636. // Compute the default character width.
  4637. function charWidth(display) {
  4638. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  4639. var anchor = elt("span", "xxxxxxxxxx");
  4640. var pre = elt("pre", [anchor]);
  4641. removeChildrenAndAdd(display.measure, pre);
  4642. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  4643. if (width > 2) display.cachedCharWidth = width;
  4644. return width || 10;
  4645. }
  4646. // OPERATIONS
  4647. // Operations are used to wrap a series of changes to the editor
  4648. // state in such a way that each change won't have to update the
  4649. // cursor and display (which would be awkward, slow, and
  4650. // error-prone). Instead, display updates are batched and then all
  4651. // combined and executed at once.
  4652. var operationGroup = null;
  4653. var nextOpId = 0;
  4654. // Start a new operation.
  4655. function startOperation(cm) {
  4656. cm.curOp = {
  4657. cm: cm,
  4658. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  4659. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  4660. forceUpdate: false, // Used to force a redraw
  4661. updateInput: null, // Whether to reset the input textarea
  4662. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  4663. changeObjs: null, // Accumulated changes, for firing change events
  4664. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  4665. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  4666. selectionChanged: false, // Whether the selection needs to be redrawn
  4667. updateMaxLine: false, // Set when the widest line needs to be determined anew
  4668. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  4669. scrollToPos: null, // Used to scroll to a specific position
  4670. focus: false,
  4671. id: ++nextOpId // Unique ID
  4672. };
  4673. if (operationGroup) {
  4674. operationGroup.ops.push(cm.curOp);
  4675. } else {
  4676. cm.curOp.ownsGroup = operationGroup = {
  4677. ops: [cm.curOp],
  4678. delayedCallbacks: []
  4679. };
  4680. }
  4681. }
  4682. function fireCallbacksForOps(group) {
  4683. // Calls delayed callbacks and cursorActivity handlers until no
  4684. // new ones appear
  4685. var callbacks = group.delayedCallbacks, i = 0;
  4686. do {
  4687. for (; i < callbacks.length; i++)
  4688. callbacks[i].call(null);
  4689. for (var j = 0; j < group.ops.length; j++) {
  4690. var op = group.ops[j];
  4691. if (op.cursorActivityHandlers)
  4692. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  4693. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  4694. }
  4695. } while (i < callbacks.length);
  4696. }
  4697. // Finish an operation, updating the display and signalling delayed events
  4698. function endOperation(cm) {
  4699. var op = cm.curOp, group = op.ownsGroup;
  4700. if (!group) return;
  4701. try { fireCallbacksForOps(group); }
  4702. finally {
  4703. operationGroup = null;
  4704. for (var i = 0; i < group.ops.length; i++)
  4705. group.ops[i].cm.curOp = null;
  4706. endOperations(group);
  4707. }
  4708. }
  4709. // The DOM updates done when an operation finishes are batched so
  4710. // that the minimum number of relayouts are required.
  4711. function endOperations(group) {
  4712. var ops = group.ops;
  4713. for (var i = 0; i < ops.length; i++) // Read DOM
  4714. endOperation_R1(ops[i]);
  4715. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  4716. endOperation_W1(ops[i]);
  4717. for (var i = 0; i < ops.length; i++) // Read DOM
  4718. endOperation_R2(ops[i]);
  4719. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  4720. endOperation_W2(ops[i]);
  4721. for (var i = 0; i < ops.length; i++) // Read DOM
  4722. endOperation_finish(ops[i]);
  4723. }
  4724. function endOperation_R1(op) {
  4725. var cm = op.cm, display = cm.display;
  4726. maybeClipScrollbars(cm);
  4727. if (op.updateMaxLine) findMaxLine(cm);
  4728. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  4729. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  4730. op.scrollToPos.to.line >= display.viewTo) ||
  4731. display.maxLineChanged && cm.options.lineWrapping;
  4732. op.update = op.mustUpdate &&
  4733. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  4734. }
  4735. function endOperation_W1(op) {
  4736. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  4737. }
  4738. function endOperation_R2(op) {
  4739. var cm = op.cm, display = cm.display;
  4740. if (op.updatedDisplay) updateHeightsInViewport(cm);
  4741. op.barMeasure = measureForScrollbars(cm);
  4742. // If the max line changed since it was last measured, measure it,
  4743. // and ensure the document's width matches it.
  4744. // updateDisplay_W2 will use these properties to do the actual resizing
  4745. if (display.maxLineChanged && !cm.options.lineWrapping) {
  4746. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  4747. cm.display.sizerWidth = op.adjustWidthTo;
  4748. op.barMeasure.scrollWidth =
  4749. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  4750. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  4751. }
  4752. if (op.updatedDisplay || op.selectionChanged)
  4753. op.preparedSelection = display.input.prepareSelection(op.focus);
  4754. }
  4755. function endOperation_W2(op) {
  4756. var cm = op.cm;
  4757. if (op.adjustWidthTo != null) {
  4758. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  4759. if (op.maxScrollLeft < cm.doc.scrollLeft)
  4760. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  4761. cm.display.maxLineChanged = false;
  4762. }
  4763. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  4764. if (op.preparedSelection)
  4765. cm.display.input.showSelection(op.preparedSelection, takeFocus);
  4766. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  4767. updateScrollbars(cm, op.barMeasure);
  4768. if (op.updatedDisplay)
  4769. setDocumentHeight(cm, op.barMeasure);
  4770. if (op.selectionChanged) restartBlink(cm);
  4771. if (cm.state.focused && op.updateInput)
  4772. cm.display.input.reset(op.typing);
  4773. if (takeFocus) ensureFocus(op.cm);
  4774. }
  4775. function endOperation_finish(op) {
  4776. var cm = op.cm, display = cm.display, doc = cm.doc;
  4777. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  4778. // Abort mouse wheel delta measurement, when scrolling explicitly
  4779. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  4780. display.wheelStartX = display.wheelStartY = null;
  4781. // Propagate the scroll position to the actual DOM scroller
  4782. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  4783. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  4784. display.scrollbars.setScrollTop(doc.scrollTop);
  4785. display.scroller.scrollTop = doc.scrollTop;
  4786. }
  4787. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  4788. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  4789. display.scrollbars.setScrollLeft(doc.scrollLeft);
  4790. display.scroller.scrollLeft = doc.scrollLeft;
  4791. alignHorizontally(cm);
  4792. }
  4793. // If we need to scroll a specific position into view, do so.
  4794. if (op.scrollToPos) {
  4795. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  4796. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  4797. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  4798. }
  4799. // Fire events for markers that are hidden/unidden by editing or
  4800. // undoing
  4801. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  4802. if (hidden) for (var i = 0; i < hidden.length; ++i)
  4803. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  4804. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  4805. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  4806. if (display.wrapper.offsetHeight)
  4807. doc.scrollTop = cm.display.scroller.scrollTop;
  4808. // Fire change events, and delayed event handlers
  4809. if (op.changeObjs)
  4810. signal(cm, "changes", cm, op.changeObjs);
  4811. if (op.update)
  4812. op.update.finish();
  4813. }
  4814. // Run the given function in an operation
  4815. function runInOp(cm, f) {
  4816. if (cm.curOp) return f();
  4817. startOperation(cm);
  4818. try { return f(); }
  4819. finally { endOperation(cm); }
  4820. }
  4821. // Wraps a function in an operation. Returns the wrapped function.
  4822. function operation(cm, f) {
  4823. return function() {
  4824. if (cm.curOp) return f.apply(cm, arguments);
  4825. startOperation(cm);
  4826. try { return f.apply(cm, arguments); }
  4827. finally { endOperation(cm); }
  4828. };
  4829. }
  4830. // Used to add methods to editor and doc instances, wrapping them in
  4831. // operations.
  4832. function methodOp(f) {
  4833. return function() {
  4834. if (this.curOp) return f.apply(this, arguments);
  4835. startOperation(this);
  4836. try { return f.apply(this, arguments); }
  4837. finally { endOperation(this); }
  4838. };
  4839. }
  4840. function docMethodOp(f) {
  4841. return function() {
  4842. var cm = this.cm;
  4843. if (!cm || cm.curOp) return f.apply(this, arguments);
  4844. startOperation(cm);
  4845. try { return f.apply(this, arguments); }
  4846. finally { endOperation(cm); }
  4847. };
  4848. }
  4849. // VIEW TRACKING
  4850. // These objects are used to represent the visible (currently drawn)
  4851. // part of the document. A LineView may correspond to multiple
  4852. // logical lines, if those are connected by collapsed ranges.
  4853. function LineView(doc, line, lineN) {
  4854. // The starting line
  4855. this.line = line;
  4856. // Continuing lines, if any
  4857. this.rest = visualLineContinued(line);
  4858. // Number of logical lines in this visual line
  4859. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  4860. this.node = this.text = null;
  4861. this.hidden = lineIsHidden(doc, line);
  4862. }
  4863. // Create a range of LineView objects for the given lines.
  4864. function buildViewArray(cm, from, to) {
  4865. var array = [], nextPos;
  4866. for (var pos = from; pos < to; pos = nextPos) {
  4867. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  4868. nextPos = pos + view.size;
  4869. array.push(view);
  4870. }
  4871. return array;
  4872. }
  4873. // Updates the display.view data structure for a given change to the
  4874. // document. From and to are in pre-change coordinates. Lendiff is
  4875. // the amount of lines added or subtracted by the change. This is
  4876. // used for changes that span multiple lines, or change the way
  4877. // lines are divided into visual lines. regLineChange (below)
  4878. // registers single-line changes.
  4879. function regChange(cm, from, to, lendiff) {
  4880. if (from == null) from = cm.doc.first;
  4881. if (to == null) to = cm.doc.first + cm.doc.size;
  4882. if (!lendiff) lendiff = 0;
  4883. var display = cm.display;
  4884. if (lendiff && to < display.viewTo &&
  4885. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  4886. display.updateLineNumbers = from;
  4887. cm.curOp.viewChanged = true;
  4888. if (from >= display.viewTo) { // Change after
  4889. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  4890. resetView(cm);
  4891. } else if (to <= display.viewFrom) { // Change before
  4892. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  4893. resetView(cm);
  4894. } else {
  4895. display.viewFrom += lendiff;
  4896. display.viewTo += lendiff;
  4897. }
  4898. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  4899. resetView(cm);
  4900. } else if (from <= display.viewFrom) { // Top overlap
  4901. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  4902. if (cut) {
  4903. display.view = display.view.slice(cut.index);
  4904. display.viewFrom = cut.lineN;
  4905. display.viewTo += lendiff;
  4906. } else {
  4907. resetView(cm);
  4908. }
  4909. } else if (to >= display.viewTo) { // Bottom overlap
  4910. var cut = viewCuttingPoint(cm, from, from, -1);
  4911. if (cut) {
  4912. display.view = display.view.slice(0, cut.index);
  4913. display.viewTo = cut.lineN;
  4914. } else {
  4915. resetView(cm);
  4916. }
  4917. } else { // Gap in the middle
  4918. var cutTop = viewCuttingPoint(cm, from, from, -1);
  4919. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  4920. if (cutTop && cutBot) {
  4921. display.view = display.view.slice(0, cutTop.index)
  4922. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  4923. .concat(display.view.slice(cutBot.index));
  4924. display.viewTo += lendiff;
  4925. } else {
  4926. resetView(cm);
  4927. }
  4928. }
  4929. var ext = display.externalMeasured;
  4930. if (ext) {
  4931. if (to < ext.lineN)
  4932. ext.lineN += lendiff;
  4933. else if (from < ext.lineN + ext.size)
  4934. display.externalMeasured = null;
  4935. }
  4936. }
  4937. // Register a change to a single line. Type must be one of "text",
  4938. // "gutter", "class", "widget"
  4939. function regLineChange(cm, line, type) {
  4940. cm.curOp.viewChanged = true;
  4941. var display = cm.display, ext = cm.display.externalMeasured;
  4942. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  4943. display.externalMeasured = null;
  4944. if (line < display.viewFrom || line >= display.viewTo) return;
  4945. var lineView = display.view[findViewIndex(cm, line)];
  4946. if (lineView.node == null) return;
  4947. var arr = lineView.changes || (lineView.changes = []);
  4948. if (indexOf(arr, type) == -1) arr.push(type);
  4949. }
  4950. // Clear the view.
  4951. function resetView(cm) {
  4952. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  4953. cm.display.view = [];
  4954. cm.display.viewOffset = 0;
  4955. }
  4956. // Find the view element corresponding to a given line. Return null
  4957. // when the line isn't visible.
  4958. function findViewIndex(cm, n) {
  4959. if (n >= cm.display.viewTo) return null;
  4960. n -= cm.display.viewFrom;
  4961. if (n < 0) return null;
  4962. var view = cm.display.view;
  4963. for (var i = 0; i < view.length; i++) {
  4964. n -= view[i].size;
  4965. if (n < 0) return i;
  4966. }
  4967. }
  4968. function viewCuttingPoint(cm, oldN, newN, dir) {
  4969. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  4970. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  4971. return {index: index, lineN: newN};
  4972. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  4973. n += view[i].size;
  4974. if (n != oldN) {
  4975. if (dir > 0) {
  4976. if (index == view.length - 1) return null;
  4977. diff = (n + view[index].size) - oldN;
  4978. index++;
  4979. } else {
  4980. diff = n - oldN;
  4981. }
  4982. oldN += diff; newN += diff;
  4983. }
  4984. while (visualLineNo(cm.doc, newN) != newN) {
  4985. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  4986. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  4987. index += dir;
  4988. }
  4989. return {index: index, lineN: newN};
  4990. }
  4991. // Force the view to cover a given range, adding empty view element
  4992. // or clipping off existing ones as needed.
  4993. function adjustView(cm, from, to) {
  4994. var display = cm.display, view = display.view;
  4995. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  4996. display.view = buildViewArray(cm, from, to);
  4997. display.viewFrom = from;
  4998. } else {
  4999. if (display.viewFrom > from)
  5000. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  5001. else if (display.viewFrom < from)
  5002. display.view = display.view.slice(findViewIndex(cm, from));
  5003. display.viewFrom = from;
  5004. if (display.viewTo < to)
  5005. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  5006. else if (display.viewTo > to)
  5007. display.view = display.view.slice(0, findViewIndex(cm, to));
  5008. }
  5009. display.viewTo = to;
  5010. }
  5011. // Count the number of lines in the view whose DOM representation is
  5012. // out of date (or nonexistent).
  5013. function countDirtyView(cm) {
  5014. var view = cm.display.view, dirty = 0;
  5015. for (var i = 0; i < view.length; i++) {
  5016. var lineView = view[i];
  5017. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  5018. }
  5019. return dirty;
  5020. }
  5021. // EVENT HANDLERS
  5022. // Attach the necessary event handlers when initializing the editor
  5023. function registerEventHandlers(cm) {
  5024. var d = cm.display;
  5025. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  5026. // Older IE's will not fire a second mousedown for a double click
  5027. if (ie && ie_version < 11)
  5028. on(d.scroller, "dblclick", operation(cm, function(e) {
  5029. if (signalDOMEvent(cm, e)) return;
  5030. var pos = posFromMouse(cm, e);
  5031. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  5032. e_preventDefault(e);
  5033. var word = cm.findWordAt(pos);
  5034. extendSelection(cm.doc, word.anchor, word.head);
  5035. }));
  5036. else
  5037. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  5038. // Some browsers fire contextmenu *after* opening the menu, at
  5039. // which point we can't mess with it anymore. Context menu is
  5040. // handled in onMouseDown for these browsers.
  5041. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  5042. // Used to suppress mouse event handling when a touch happens
  5043. var touchFinished, prevTouch = {end: 0};
  5044. function finishTouch() {
  5045. if (d.activeTouch) {
  5046. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  5047. prevTouch = d.activeTouch;
  5048. prevTouch.end = +new Date;
  5049. }
  5050. };
  5051. function isMouseLikeTouchEvent(e) {
  5052. if (e.touches.length != 1) return false;
  5053. var touch = e.touches[0];
  5054. return touch.radiusX <= 1 && touch.radiusY <= 1;
  5055. }
  5056. function farAway(touch, other) {
  5057. if (other.left == null) return true;
  5058. var dx = other.left - touch.left, dy = other.top - touch.top;
  5059. return dx * dx + dy * dy > 20 * 20;
  5060. }
  5061. on(d.scroller, "touchstart", function(e) {
  5062. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  5063. clearTimeout(touchFinished);
  5064. var now = +new Date;
  5065. d.activeTouch = {start: now, moved: false,
  5066. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  5067. if (e.touches.length == 1) {
  5068. d.activeTouch.left = e.touches[0].pageX;
  5069. d.activeTouch.top = e.touches[0].pageY;
  5070. }
  5071. }
  5072. });
  5073. on(d.scroller, "touchmove", function() {
  5074. if (d.activeTouch) d.activeTouch.moved = true;
  5075. });
  5076. on(d.scroller, "touchend", function(e) {
  5077. var touch = d.activeTouch;
  5078. if (touch && !eventInWidget(d, e) && touch.left != null &&
  5079. !touch.moved && new Date - touch.start < 300) {
  5080. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  5081. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  5082. range = new Range(pos, pos);
  5083. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  5084. range = cm.findWordAt(pos);
  5085. else // Triple tap
  5086. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  5087. cm.setSelection(range.anchor, range.head);
  5088. cm.focus();
  5089. e_preventDefault(e);
  5090. }
  5091. finishTouch();
  5092. });
  5093. on(d.scroller, "touchcancel", finishTouch);
  5094. // Sync scrolling between fake scrollbars and real scrollable
  5095. // area, ensure viewport is updated when scrolling.
  5096. on(d.scroller, "scroll", function() {
  5097. if (d.scroller.clientHeight) {
  5098. setScrollTop(cm, d.scroller.scrollTop);
  5099. setScrollLeft(cm, d.scroller.scrollLeft, true);
  5100. signal(cm, "scroll", cm);
  5101. }
  5102. });
  5103. // Listen to wheel events in order to try and update the viewport on time.
  5104. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  5105. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  5106. // Prevent wrapper from ever scrolling
  5107. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  5108. d.dragFunctions = {
  5109. enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  5110. over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  5111. start: function(e){onDragStart(cm, e);},
  5112. drop: operation(cm, onDrop),
  5113. leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  5114. };
  5115. var inp = d.input.getField();
  5116. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  5117. on(inp, "keydown", operation(cm, onKeyDown));
  5118. on(inp, "keypress", operation(cm, onKeyPress));
  5119. on(inp, "focus", bind(onFocus, cm));
  5120. on(inp, "blur", bind(onBlur, cm));
  5121. }
  5122. function dragDropChanged(cm, value, old) {
  5123. var wasOn = old && old != CodeMirror.Init;
  5124. if (!value != !wasOn) {
  5125. var funcs = cm.display.dragFunctions;
  5126. var toggle = value ? on : off;
  5127. toggle(cm.display.scroller, "dragstart", funcs.start);
  5128. toggle(cm.display.scroller, "dragenter", funcs.enter);
  5129. toggle(cm.display.scroller, "dragover", funcs.over);
  5130. toggle(cm.display.scroller, "dragleave", funcs.leave);
  5131. toggle(cm.display.scroller, "drop", funcs.drop);
  5132. }
  5133. }
  5134. // Called when the window resizes
  5135. function onResize(cm) {
  5136. var d = cm.display;
  5137. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5138. return;
  5139. // Might be a text scaling operation, clear size caches.
  5140. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5141. d.scrollbarsClipped = false;
  5142. cm.setSize();
  5143. }
  5144. // MOUSE EVENTS
  5145. // Return true when the given mouse event happened in a widget
  5146. function eventInWidget(display, e) {
  5147. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  5148. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  5149. (n.parentNode == display.sizer && n != display.mover))
  5150. return true;
  5151. }
  5152. }
  5153. // Given a mouse event, find the corresponding position. If liberal
  5154. // is false, it checks whether a gutter or scrollbar was clicked,
  5155. // and returns null if it was. forRect is used by rectangular
  5156. // selections, and tries to estimate a character position even for
  5157. // coordinates beyond the right of the text.
  5158. function posFromMouse(cm, e, liberal, forRect) {
  5159. var display = cm.display;
  5160. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  5161. var x, y, space = display.lineSpace.getBoundingClientRect();
  5162. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  5163. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  5164. catch (e) { return null; }
  5165. var coords = coordsChar(cm, x, y), line;
  5166. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  5167. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  5168. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  5169. }
  5170. return coords;
  5171. }
  5172. // A mouse down can be a single click, double click, triple click,
  5173. // start of selection drag, start of text drag, new cursor
  5174. // (ctrl-click), rectangle drag (alt-drag), or xwin
  5175. // middle-click-paste. Or it might be a click on something we should
  5176. // not interfere with, such as a scrollbar or widget.
  5177. function onMouseDown(e) {
  5178. var cm = this, display = cm.display;
  5179. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
  5180. display.shift = e.shiftKey;
  5181. if (eventInWidget(display, e)) {
  5182. if (!webkit) {
  5183. // Briefly turn off draggability, to allow widgets to do
  5184. // normal dragging things.
  5185. display.scroller.draggable = false;
  5186. setTimeout(function(){display.scroller.draggable = true;}, 100);
  5187. }
  5188. return;
  5189. }
  5190. if (clickInGutter(cm, e)) return;
  5191. var start = posFromMouse(cm, e);
  5192. window.focus();
  5193. switch (e_button(e)) {
  5194. case 1:
  5195. // #3261: make sure, that we're not starting a second selection
  5196. if (cm.state.selectingText)
  5197. cm.state.selectingText(e);
  5198. else if (start)
  5199. leftButtonDown(cm, e, start);
  5200. else if (e_target(e) == display.scroller)
  5201. e_preventDefault(e);
  5202. break;
  5203. case 2:
  5204. if (webkit) cm.state.lastMiddleDown = +new Date;
  5205. if (start) extendSelection(cm.doc, start);
  5206. setTimeout(function() {display.input.focus();}, 20);
  5207. e_preventDefault(e);
  5208. break;
  5209. case 3:
  5210. if (captureRightClick) onContextMenu(cm, e);
  5211. else delayBlurEvent(cm);
  5212. break;
  5213. }
  5214. }
  5215. var lastClick, lastDoubleClick;
  5216. function leftButtonDown(cm, e, start) {
  5217. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  5218. else cm.curOp.focus = activeElt();
  5219. var now = +new Date, type;
  5220. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  5221. type = "triple";
  5222. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  5223. type = "double";
  5224. lastDoubleClick = {time: now, pos: start};
  5225. } else {
  5226. type = "single";
  5227. lastClick = {time: now, pos: start};
  5228. }
  5229. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  5230. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  5231. type == "single" && (contained = sel.contains(start)) > -1 &&
  5232. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  5233. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  5234. leftButtonStartDrag(cm, e, start, modifier);
  5235. else
  5236. leftButtonSelect(cm, e, start, type, modifier);
  5237. }
  5238. // Start a text drag. When it ends, see if any dragging actually
  5239. // happen, and treat as a click if it didn't.
  5240. function leftButtonStartDrag(cm, e, start, modifier) {
  5241. var display = cm.display, startTime = +new Date;
  5242. var dragEnd = operation(cm, function(e2) {
  5243. if (webkit) display.scroller.draggable = false;
  5244. cm.state.draggingText = false;
  5245. off(document, "mouseup", dragEnd);
  5246. off(display.scroller, "drop", dragEnd);
  5247. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  5248. e_preventDefault(e2);
  5249. if (!modifier && +new Date - 200 < startTime)
  5250. extendSelection(cm.doc, start);
  5251. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  5252. if (webkit || ie && ie_version == 9)
  5253. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  5254. else
  5255. display.input.focus();
  5256. }
  5257. });
  5258. // Let the drag handler handle this.
  5259. if (webkit) display.scroller.draggable = true;
  5260. cm.state.draggingText = dragEnd;
  5261. // IE's approach to draggable
  5262. if (display.scroller.dragDrop) display.scroller.dragDrop();
  5263. on(document, "mouseup", dragEnd);
  5264. on(display.scroller, "drop", dragEnd);
  5265. }
  5266. // Normal selection, as opposed to text dragging.
  5267. function leftButtonSelect(cm, e, start, type, addNew) {
  5268. var display = cm.display, doc = cm.doc;
  5269. e_preventDefault(e);
  5270. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  5271. if (addNew && !e.shiftKey) {
  5272. ourIndex = doc.sel.contains(start);
  5273. if (ourIndex > -1)
  5274. ourRange = ranges[ourIndex];
  5275. else
  5276. ourRange = new Range(start, start);
  5277. } else {
  5278. ourRange = doc.sel.primary();
  5279. ourIndex = doc.sel.primIndex;
  5280. }
  5281. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  5282. type = "rect";
  5283. if (!addNew) ourRange = new Range(start, start);
  5284. start = posFromMouse(cm, e, true, true);
  5285. ourIndex = -1;
  5286. } else if (type == "double") {
  5287. var word = cm.findWordAt(start);
  5288. if (cm.display.shift || doc.extend)
  5289. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  5290. else
  5291. ourRange = word;
  5292. } else if (type == "triple") {
  5293. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  5294. if (cm.display.shift || doc.extend)
  5295. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  5296. else
  5297. ourRange = line;
  5298. } else {
  5299. ourRange = extendRange(doc, ourRange, start);
  5300. }
  5301. if (!addNew) {
  5302. ourIndex = 0;
  5303. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  5304. startSel = doc.sel;
  5305. } else if (ourIndex == -1) {
  5306. ourIndex = ranges.length;
  5307. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  5308. {scroll: false, origin: "*mouse"});
  5309. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  5310. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  5311. {scroll: false, origin: "*mouse"});
  5312. startSel = doc.sel;
  5313. } else {
  5314. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  5315. }
  5316. var lastPos = start;
  5317. function extendTo(pos) {
  5318. if (cmp(lastPos, pos) == 0) return;
  5319. lastPos = pos;
  5320. if (type == "rect") {
  5321. var ranges = [], tabSize = cm.options.tabSize;
  5322. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  5323. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  5324. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  5325. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  5326. line <= end; line++) {
  5327. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  5328. if (left == right)
  5329. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  5330. else if (text.length > leftPos)
  5331. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  5332. }
  5333. if (!ranges.length) ranges.push(new Range(start, start));
  5334. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  5335. {origin: "*mouse", scroll: false});
  5336. cm.scrollIntoView(pos);
  5337. } else {
  5338. var oldRange = ourRange;
  5339. var anchor = oldRange.anchor, head = pos;
  5340. if (type != "single") {
  5341. if (type == "double")
  5342. var range = cm.findWordAt(pos);
  5343. else
  5344. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  5345. if (cmp(range.anchor, anchor) > 0) {
  5346. head = range.head;
  5347. anchor = minPos(oldRange.from(), range.anchor);
  5348. } else {
  5349. head = range.anchor;
  5350. anchor = maxPos(oldRange.to(), range.head);
  5351. }
  5352. }
  5353. var ranges = startSel.ranges.slice(0);
  5354. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  5355. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  5356. }
  5357. }
  5358. var editorSize = display.wrapper.getBoundingClientRect();
  5359. // Used to ensure timeout re-tries don't fire when another extend
  5360. // happened in the meantime (clearTimeout isn't reliable -- at
  5361. // least on Chrome, the timeouts still happen even when cleared,
  5362. // if the clear happens after their scheduled firing time).
  5363. var counter = 0;
  5364. function extend(e) {
  5365. var curCount = ++counter;
  5366. var cur = posFromMouse(cm, e, true, type == "rect");
  5367. if (!cur) return;
  5368. if (cmp(cur, lastPos) != 0) {
  5369. cm.curOp.focus = activeElt();
  5370. extendTo(cur);
  5371. var visible = visibleLines(display, doc);
  5372. if (cur.line >= visible.to || cur.line < visible.from)
  5373. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  5374. } else {
  5375. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  5376. if (outside) setTimeout(operation(cm, function() {
  5377. if (counter != curCount) return;
  5378. display.scroller.scrollTop += outside;
  5379. extend(e);
  5380. }), 50);
  5381. }
  5382. }
  5383. function done(e) {
  5384. cm.state.selectingText = false;
  5385. counter = Infinity;
  5386. e_preventDefault(e);
  5387. display.input.focus();
  5388. off(document, "mousemove", move);
  5389. off(document, "mouseup", up);
  5390. doc.history.lastSelOrigin = null;
  5391. }
  5392. var move = operation(cm, function(e) {
  5393. if (!e_button(e)) done(e);
  5394. else extend(e);
  5395. });
  5396. var up = operation(cm, done);
  5397. cm.state.selectingText = up;
  5398. on(document, "mousemove", move);
  5399. on(document, "mouseup", up);
  5400. }
  5401. // Determines whether an event happened in the gutter, and fires the
  5402. // handlers for the corresponding event.
  5403. function gutterEvent(cm, e, type, prevent) {
  5404. try { var mX = e.clientX, mY = e.clientY; }
  5405. catch(e) { return false; }
  5406. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  5407. if (prevent) e_preventDefault(e);
  5408. var display = cm.display;
  5409. var lineBox = display.lineDiv.getBoundingClientRect();
  5410. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  5411. mY -= lineBox.top - display.viewOffset;
  5412. for (var i = 0; i < cm.options.gutters.length; ++i) {
  5413. var g = display.gutters.childNodes[i];
  5414. if (g && g.getBoundingClientRect().right >= mX) {
  5415. var line = lineAtHeight(cm.doc, mY);
  5416. var gutter = cm.options.gutters[i];
  5417. signal(cm, type, cm, line, gutter, e);
  5418. return e_defaultPrevented(e);
  5419. }
  5420. }
  5421. }
  5422. function clickInGutter(cm, e) {
  5423. return gutterEvent(cm, e, "gutterClick", true);
  5424. }
  5425. // Kludge to work around strange IE behavior where it'll sometimes
  5426. // re-fire a series of drag-related events right after the drop (#1551)
  5427. var lastDrop = 0;
  5428. function onDrop(e) {
  5429. var cm = this;
  5430. clearDragCursor(cm);
  5431. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5432. return;
  5433. e_preventDefault(e);
  5434. if (ie) lastDrop = +new Date;
  5435. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5436. if (!pos || cm.isReadOnly()) return;
  5437. // Might be a file drop, in which case we simply extract the text
  5438. // and insert it.
  5439. if (files && files.length && window.FileReader && window.File) {
  5440. var n = files.length, text = Array(n), read = 0;
  5441. var loadFile = function(file, i) {
  5442. if (cm.options.allowDropFileTypes &&
  5443. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5444. return;
  5445. var reader = new FileReader;
  5446. reader.onload = operation(cm, function() {
  5447. var content = reader.result;
  5448. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
  5449. text[i] = content;
  5450. if (++read == n) {
  5451. pos = clipPos(cm.doc, pos);
  5452. var change = {from: pos, to: pos,
  5453. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5454. origin: "paste"};
  5455. makeChange(cm.doc, change);
  5456. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  5457. }
  5458. });
  5459. reader.readAsText(file);
  5460. };
  5461. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  5462. } else { // Normal drop
  5463. // Don't do a replace if the drop happened inside of the selected text.
  5464. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5465. cm.state.draggingText(e);
  5466. // Ensure the editor is re-focused
  5467. setTimeout(function() {cm.display.input.focus();}, 20);
  5468. return;
  5469. }
  5470. try {
  5471. var text = e.dataTransfer.getData("Text");
  5472. if (text) {
  5473. if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
  5474. var selected = cm.listSelections();
  5475. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5476. if (selected) for (var i = 0; i < selected.length; ++i)
  5477. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  5478. cm.replaceSelection(text, "around", "paste");
  5479. cm.display.input.focus();
  5480. }
  5481. }
  5482. catch(e){}
  5483. }
  5484. }
  5485. function onDragStart(cm, e) {
  5486. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  5487. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  5488. e.dataTransfer.setData("Text", cm.getSelection());
  5489. e.dataTransfer.effectAllowed = "copyMove"
  5490. // Use dummy image instead of default browsers image.
  5491. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5492. if (e.dataTransfer.setDragImage && !safari) {
  5493. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5494. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5495. if (presto) {
  5496. img.width = img.height = 1;
  5497. cm.display.wrapper.appendChild(img);
  5498. // Force a relayout, or Opera won't use our image for some obscure reason
  5499. img._top = img.offsetTop;
  5500. }
  5501. e.dataTransfer.setDragImage(img, 0, 0);
  5502. if (presto) img.parentNode.removeChild(img);
  5503. }
  5504. }
  5505. function onDragOver(cm, e) {
  5506. var pos = posFromMouse(cm, e);
  5507. if (!pos) return;
  5508. var frag = document.createDocumentFragment();
  5509. drawSelectionCursor(cm, pos, frag);
  5510. if (!cm.display.dragCursor) {
  5511. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5512. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5513. }
  5514. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5515. }
  5516. function clearDragCursor(cm) {
  5517. if (cm.display.dragCursor) {
  5518. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5519. cm.display.dragCursor = null;
  5520. }
  5521. }
  5522. // SCROLL EVENTS
  5523. // Sync the scrollable area and scrollbars, ensure the viewport
  5524. // covers the visible area.
  5525. function setScrollTop(cm, val) {
  5526. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  5527. cm.doc.scrollTop = val;
  5528. if (!gecko) updateDisplaySimple(cm, {top: val});
  5529. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  5530. cm.display.scrollbars.setScrollTop(val);
  5531. if (gecko) updateDisplaySimple(cm);
  5532. startWorker(cm, 100);
  5533. }
  5534. // Sync scroller and scrollbar, ensure the gutter elements are
  5535. // aligned.
  5536. function setScrollLeft(cm, val, isScroller) {
  5537. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  5538. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  5539. cm.doc.scrollLeft = val;
  5540. alignHorizontally(cm);
  5541. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  5542. cm.display.scrollbars.setScrollLeft(val);
  5543. }
  5544. // Since the delta values reported on mouse wheel events are
  5545. // unstandardized between browsers and even browser versions, and
  5546. // generally horribly unpredictable, this code starts by measuring
  5547. // the scroll effect that the first few mouse wheel events have,
  5548. // and, from that, detects the way it can convert deltas to pixel
  5549. // offsets afterwards.
  5550. //
  5551. // The reason we want to know the amount a wheel event will scroll
  5552. // is that it gives us a chance to update the display before the
  5553. // actual scrolling happens, reducing flickering.
  5554. var wheelSamples = 0, wheelPixelsPerUnit = null;
  5555. // Fill in a browser-detected starting value on browsers where we
  5556. // know one. These don't have to be accurate -- the result of them
  5557. // being wrong would just be a slight flicker on the first wheel
  5558. // scroll (if it is large enough).
  5559. if (ie) wheelPixelsPerUnit = -.53;
  5560. else if (gecko) wheelPixelsPerUnit = 15;
  5561. else if (chrome) wheelPixelsPerUnit = -.7;
  5562. else if (safari) wheelPixelsPerUnit = -1/3;
  5563. var wheelEventDelta = function(e) {
  5564. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  5565. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  5566. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  5567. else if (dy == null) dy = e.wheelDelta;
  5568. return {x: dx, y: dy};
  5569. };
  5570. CodeMirror.wheelEventPixels = function(e) {
  5571. var delta = wheelEventDelta(e);
  5572. delta.x *= wheelPixelsPerUnit;
  5573. delta.y *= wheelPixelsPerUnit;
  5574. return delta;
  5575. };
  5576. function onScrollWheel(cm, e) {
  5577. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  5578. var display = cm.display, scroll = display.scroller;
  5579. // Quit if there's nothing to scroll here
  5580. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  5581. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  5582. if (!(dx && canScrollX || dy && canScrollY)) return;
  5583. // Webkit browsers on OS X abort momentum scrolls when the target
  5584. // of the scroll event is removed from the scrollable element.
  5585. // This hack (see related code in patchDisplay) makes sure the
  5586. // element is kept around.
  5587. if (dy && mac && webkit) {
  5588. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  5589. for (var i = 0; i < view.length; i++) {
  5590. if (view[i].node == cur) {
  5591. cm.display.currentWheelTarget = cur;
  5592. break outer;
  5593. }
  5594. }
  5595. }
  5596. }
  5597. // On some browsers, horizontal scrolling will cause redraws to
  5598. // happen before the gutter has been realigned, causing it to
  5599. // wriggle around in a most unseemly way. When we have an
  5600. // estimated pixels/delta value, we just handle horizontal
  5601. // scrolling entirely here. It'll be slightly off from native, but
  5602. // better than glitching out.
  5603. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  5604. if (dy && canScrollY)
  5605. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  5606. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  5607. // Only prevent default scrolling if vertical scrolling is
  5608. // actually possible. Otherwise, it causes vertical scroll
  5609. // jitter on OSX trackpads when deltaX is small and deltaY
  5610. // is large (issue #3579)
  5611. if (!dy || (dy && canScrollY))
  5612. e_preventDefault(e);
  5613. display.wheelStartX = null; // Abort measurement, if in progress
  5614. return;
  5615. }
  5616. // 'Project' the visible viewport to cover the area that is being
  5617. // scrolled into view (if we know enough to estimate it).
  5618. if (dy && wheelPixelsPerUnit != null) {
  5619. var pixels = dy * wheelPixelsPerUnit;
  5620. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  5621. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  5622. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  5623. updateDisplaySimple(cm, {top: top, bottom: bot});
  5624. }
  5625. if (wheelSamples < 20) {
  5626. if (display.wheelStartX == null) {
  5627. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  5628. display.wheelDX = dx; display.wheelDY = dy;
  5629. setTimeout(function() {
  5630. if (display.wheelStartX == null) return;
  5631. var movedX = scroll.scrollLeft - display.wheelStartX;
  5632. var movedY = scroll.scrollTop - display.wheelStartY;
  5633. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  5634. (movedX && display.wheelDX && movedX / display.wheelDX);
  5635. display.wheelStartX = display.wheelStartY = null;
  5636. if (!sample) return;
  5637. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  5638. ++wheelSamples;
  5639. }, 200);
  5640. } else {
  5641. display.wheelDX += dx; display.wheelDY += dy;
  5642. }
  5643. }
  5644. }
  5645. // KEY EVENTS
  5646. // Run a handler that was bound to a key.
  5647. function doHandleBinding(cm, bound, dropShift) {
  5648. if (typeof bound == "string") {
  5649. bound = commands[bound];
  5650. if (!bound) return false;
  5651. }
  5652. // Ensure previous input has been read, so that the handler sees a
  5653. // consistent view of the document
  5654. cm.display.input.ensurePolled();
  5655. var prevShift = cm.display.shift, done = false;
  5656. try {
  5657. if (cm.isReadOnly()) cm.state.suppressEdits = true;
  5658. if (dropShift) cm.display.shift = false;
  5659. done = bound(cm) != Pass;
  5660. } finally {
  5661. cm.display.shift = prevShift;
  5662. cm.state.suppressEdits = false;
  5663. }
  5664. return done;
  5665. }
  5666. function lookupKeyForEditor(cm, name, handle) {
  5667. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  5668. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  5669. if (result) return result;
  5670. }
  5671. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  5672. || lookupKey(name, cm.options.keyMap, handle, cm);
  5673. }
  5674. var stopSeq = new Delayed;
  5675. function dispatchKey(cm, name, e, handle) {
  5676. var seq = cm.state.keySeq;
  5677. if (seq) {
  5678. if (isModifierKey(name)) return "handled";
  5679. stopSeq.set(50, function() {
  5680. if (cm.state.keySeq == seq) {
  5681. cm.state.keySeq = null;
  5682. cm.display.input.reset();
  5683. }
  5684. });
  5685. name = seq + " " + name;
  5686. }
  5687. var result = lookupKeyForEditor(cm, name, handle);
  5688. if (result == "multi")
  5689. cm.state.keySeq = name;
  5690. if (result == "handled")
  5691. signalLater(cm, "keyHandled", cm, name, e);
  5692. if (result == "handled" || result == "multi") {
  5693. e_preventDefault(e);
  5694. restartBlink(cm);
  5695. }
  5696. if (seq && !result && /\'$/.test(name)) {
  5697. e_preventDefault(e);
  5698. return true;
  5699. }
  5700. return !!result;
  5701. }
  5702. // Handle a key from the keydown event.
  5703. function handleKeyBinding(cm, e) {
  5704. var name = keyName(e, true);
  5705. if (!name) return false;
  5706. if (e.shiftKey && !cm.state.keySeq) {
  5707. // First try to resolve full name (including 'Shift-'). Failing
  5708. // that, see if there is a cursor-motion command (starting with
  5709. // 'go') bound to the keyname without 'Shift-'.
  5710. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  5711. || dispatchKey(cm, name, e, function(b) {
  5712. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  5713. return doHandleBinding(cm, b);
  5714. });
  5715. } else {
  5716. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  5717. }
  5718. }
  5719. // Handle a key from the keypress event
  5720. function handleCharBinding(cm, e, ch) {
  5721. return dispatchKey(cm, "'" + ch + "'", e,
  5722. function(b) { return doHandleBinding(cm, b, true); });
  5723. }
  5724. var lastStoppedKey = null;
  5725. function onKeyDown(e) {
  5726. var cm = this;
  5727. cm.curOp.focus = activeElt();
  5728. if (signalDOMEvent(cm, e)) return;
  5729. // IE does strange things with escape.
  5730. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  5731. var code = e.keyCode;
  5732. cm.display.shift = code == 16 || e.shiftKey;
  5733. var handled = handleKeyBinding(cm, e);
  5734. if (presto) {
  5735. lastStoppedKey = handled ? code : null;
  5736. // Opera has no cut event... we try to at least catch the key combo
  5737. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  5738. cm.replaceSelection("", null, "cut");
  5739. }
  5740. // Turn mouse into crosshair when Alt is held on Mac.
  5741. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  5742. showCrossHair(cm);
  5743. }
  5744. function showCrossHair(cm) {
  5745. var lineDiv = cm.display.lineDiv;
  5746. addClass(lineDiv, "CodeMirror-crosshair");
  5747. function up(e) {
  5748. if (e.keyCode == 18 || !e.altKey) {
  5749. rmClass(lineDiv, "CodeMirror-crosshair");
  5750. off(document, "keyup", up);
  5751. off(document, "mouseover", up);
  5752. }
  5753. }
  5754. on(document, "keyup", up);
  5755. on(document, "mouseover", up);
  5756. }
  5757. function onKeyUp(e) {
  5758. if (e.keyCode == 16) this.doc.sel.shift = false;
  5759. signalDOMEvent(this, e);
  5760. }
  5761. function onKeyPress(e) {
  5762. var cm = this;
  5763. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  5764. var keyCode = e.keyCode, charCode = e.charCode;
  5765. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  5766. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  5767. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  5768. if (handleCharBinding(cm, e, ch)) return;
  5769. cm.display.input.onKeyPress(e);
  5770. }
  5771. // FOCUS/BLUR EVENTS
  5772. function delayBlurEvent(cm) {
  5773. cm.state.delayingBlurEvent = true;
  5774. setTimeout(function() {
  5775. if (cm.state.delayingBlurEvent) {
  5776. cm.state.delayingBlurEvent = false;
  5777. onBlur(cm);
  5778. }
  5779. }, 100);
  5780. }
  5781. function onFocus(cm) {
  5782. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  5783. if (cm.options.readOnly == "nocursor") return;
  5784. if (!cm.state.focused) {
  5785. signal(cm, "focus", cm);
  5786. cm.state.focused = true;
  5787. addClass(cm.display.wrapper, "CodeMirror-focused");
  5788. // This test prevents this from firing when a context
  5789. // menu is closed (since the input reset would kill the
  5790. // select-all detection hack)
  5791. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  5792. cm.display.input.reset();
  5793. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  5794. }
  5795. cm.display.input.receivedFocus();
  5796. }
  5797. restartBlink(cm);
  5798. }
  5799. function onBlur(cm) {
  5800. if (cm.state.delayingBlurEvent) return;
  5801. if (cm.state.focused) {
  5802. signal(cm, "blur", cm);
  5803. cm.state.focused = false;
  5804. rmClass(cm.display.wrapper, "CodeMirror-focused");
  5805. }
  5806. clearInterval(cm.display.blinker);
  5807. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  5808. }
  5809. // CONTEXT MENU HANDLING
  5810. // To make the context menu work, we need to briefly unhide the
  5811. // textarea (making it as unobtrusive as possible) to let the
  5812. // right-click take effect on it.
  5813. function onContextMenu(cm, e) {
  5814. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  5815. if (signalDOMEvent(cm, e, "contextmenu")) return;
  5816. cm.display.input.onContextMenu(e);
  5817. }
  5818. function contextMenuInGutter(cm, e) {
  5819. if (!hasHandler(cm, "gutterContextMenu")) return false;
  5820. return gutterEvent(cm, e, "gutterContextMenu", false);
  5821. }
  5822. // UPDATING
  5823. // Compute the position of the end of a change (its 'to' property
  5824. // refers to the pre-change end).
  5825. var changeEnd = CodeMirror.changeEnd = function(change) {
  5826. if (!change.text) return change.to;
  5827. return Pos(change.from.line + change.text.length - 1,
  5828. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  5829. };
  5830. // Adjust a position to refer to the post-change position of the
  5831. // same text, or the end of the change if the change covers it.
  5832. function adjustForChange(pos, change) {
  5833. if (cmp(pos, change.from) < 0) return pos;
  5834. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  5835. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  5836. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  5837. return Pos(line, ch);
  5838. }
  5839. function computeSelAfterChange(doc, change) {
  5840. var out = [];
  5841. for (var i = 0; i < doc.sel.ranges.length; i++) {
  5842. var range = doc.sel.ranges[i];
  5843. out.push(new Range(adjustForChange(range.anchor, change),
  5844. adjustForChange(range.head, change)));
  5845. }
  5846. return normalizeSelection(out, doc.sel.primIndex);
  5847. }
  5848. function offsetPos(pos, old, nw) {
  5849. if (pos.line == old.line)
  5850. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  5851. else
  5852. return Pos(nw.line + (pos.line - old.line), pos.ch);
  5853. }
  5854. // Used by replaceSelections to allow moving the selection to the
  5855. // start or around the replaced test. Hint may be "start" or "around".
  5856. function computeReplacedSel(doc, changes, hint) {
  5857. var out = [];
  5858. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  5859. for (var i = 0; i < changes.length; i++) {
  5860. var change = changes[i];
  5861. var from = offsetPos(change.from, oldPrev, newPrev);
  5862. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  5863. oldPrev = change.to;
  5864. newPrev = to;
  5865. if (hint == "around") {
  5866. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  5867. out[i] = new Range(inv ? to : from, inv ? from : to);
  5868. } else {
  5869. out[i] = new Range(from, from);
  5870. }
  5871. }
  5872. return new Selection(out, doc.sel.primIndex);
  5873. }
  5874. // Allow "beforeChange" event handlers to influence a change
  5875. function filterChange(doc, change, update) {
  5876. var obj = {
  5877. canceled: false,
  5878. from: change.from,
  5879. to: change.to,
  5880. text: change.text,
  5881. origin: change.origin,
  5882. cancel: function() { this.canceled = true; }
  5883. };
  5884. if (update) obj.update = function(from, to, text, origin) {
  5885. if (from) this.from = clipPos(doc, from);
  5886. if (to) this.to = clipPos(doc, to);
  5887. if (text) this.text = text;
  5888. if (origin !== undefined) this.origin = origin;
  5889. };
  5890. signal(doc, "beforeChange", doc, obj);
  5891. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  5892. if (obj.canceled) return null;
  5893. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  5894. }
  5895. // Apply a change to a document, and add it to the document's
  5896. // history, and propagating it to all linked documents.
  5897. function makeChange(doc, change, ignoreReadOnly) {
  5898. if (doc.cm) {
  5899. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  5900. if (doc.cm.state.suppressEdits) return;
  5901. }
  5902. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  5903. change = filterChange(doc, change, true);
  5904. if (!change) return;
  5905. }
  5906. // Possibly split or suppress the update based on the presence
  5907. // of read-only spans in its range.
  5908. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  5909. if (split) {
  5910. for (var i = split.length - 1; i >= 0; --i)
  5911. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  5912. } else {
  5913. makeChangeInner(doc, change);
  5914. }
  5915. }
  5916. function makeChangeInner(doc, change) {
  5917. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  5918. var selAfter = computeSelAfterChange(doc, change);
  5919. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  5920. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  5921. var rebased = [];
  5922. linkedDocs(doc, function(doc, sharedHist) {
  5923. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5924. rebaseHist(doc.history, change);
  5925. rebased.push(doc.history);
  5926. }
  5927. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  5928. });
  5929. }
  5930. // Revert a change stored in a document's history.
  5931. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  5932. if (doc.cm && doc.cm.state.suppressEdits) return;
  5933. var hist = doc.history, event, selAfter = doc.sel;
  5934. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  5935. // Verify that there is a useable event (so that ctrl-z won't
  5936. // needlessly clear selection events)
  5937. for (var i = 0; i < source.length; i++) {
  5938. event = source[i];
  5939. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  5940. break;
  5941. }
  5942. if (i == source.length) return;
  5943. hist.lastOrigin = hist.lastSelOrigin = null;
  5944. for (;;) {
  5945. event = source.pop();
  5946. if (event.ranges) {
  5947. pushSelectionToHistory(event, dest);
  5948. if (allowSelectionOnly && !event.equals(doc.sel)) {
  5949. setSelection(doc, event, {clearRedo: false});
  5950. return;
  5951. }
  5952. selAfter = event;
  5953. }
  5954. else break;
  5955. }
  5956. // Build up a reverse change object to add to the opposite history
  5957. // stack (redo when undoing, and vice versa).
  5958. var antiChanges = [];
  5959. pushSelectionToHistory(selAfter, dest);
  5960. dest.push({changes: antiChanges, generation: hist.generation});
  5961. hist.generation = event.generation || ++hist.maxGeneration;
  5962. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  5963. for (var i = event.changes.length - 1; i >= 0; --i) {
  5964. var change = event.changes[i];
  5965. change.origin = type;
  5966. if (filter && !filterChange(doc, change, false)) {
  5967. source.length = 0;
  5968. return;
  5969. }
  5970. antiChanges.push(historyChangeFromChange(doc, change));
  5971. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  5972. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  5973. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  5974. var rebased = [];
  5975. // Propagate to the linked documents
  5976. linkedDocs(doc, function(doc, sharedHist) {
  5977. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5978. rebaseHist(doc.history, change);
  5979. rebased.push(doc.history);
  5980. }
  5981. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  5982. });
  5983. }
  5984. }
  5985. // Sub-views need their line numbers shifted when text is added
  5986. // above or below them in the parent document.
  5987. function shiftDoc(doc, distance) {
  5988. if (distance == 0) return;
  5989. doc.first += distance;
  5990. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  5991. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  5992. Pos(range.head.line + distance, range.head.ch));
  5993. }), doc.sel.primIndex);
  5994. if (doc.cm) {
  5995. regChange(doc.cm, doc.first, doc.first - distance, distance);
  5996. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  5997. regLineChange(doc.cm, l, "gutter");
  5998. }
  5999. }
  6000. // More lower-level change function, handling only a single document
  6001. // (not linked ones).
  6002. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  6003. if (doc.cm && !doc.cm.curOp)
  6004. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  6005. if (change.to.line < doc.first) {
  6006. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  6007. return;
  6008. }
  6009. if (change.from.line > doc.lastLine()) return;
  6010. // Clip the change to the size of this doc
  6011. if (change.from.line < doc.first) {
  6012. var shift = change.text.length - 1 - (doc.first - change.from.line);
  6013. shiftDoc(doc, shift);
  6014. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  6015. text: [lst(change.text)], origin: change.origin};
  6016. }
  6017. var last = doc.lastLine();
  6018. if (change.to.line > last) {
  6019. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  6020. text: [change.text[0]], origin: change.origin};
  6021. }
  6022. change.removed = getBetween(doc, change.from, change.to);
  6023. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  6024. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  6025. else updateDoc(doc, change, spans);
  6026. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  6027. }
  6028. // Handle the interaction of a change to a document with the editor
  6029. // that this document is part of.
  6030. function makeChangeSingleDocInEditor(cm, change, spans) {
  6031. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  6032. var recomputeMaxLength = false, checkWidthStart = from.line;
  6033. if (!cm.options.lineWrapping) {
  6034. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  6035. doc.iter(checkWidthStart, to.line + 1, function(line) {
  6036. if (line == display.maxLine) {
  6037. recomputeMaxLength = true;
  6038. return true;
  6039. }
  6040. });
  6041. }
  6042. if (doc.sel.contains(change.from, change.to) > -1)
  6043. signalCursorActivity(cm);
  6044. updateDoc(doc, change, spans, estimateHeight(cm));
  6045. if (!cm.options.lineWrapping) {
  6046. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  6047. var len = lineLength(line);
  6048. if (len > display.maxLineLength) {
  6049. display.maxLine = line;
  6050. display.maxLineLength = len;
  6051. display.maxLineChanged = true;
  6052. recomputeMaxLength = false;
  6053. }
  6054. });
  6055. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  6056. }
  6057. // Adjust frontier, schedule worker
  6058. doc.frontier = Math.min(doc.frontier, from.line);
  6059. startWorker(cm, 400);
  6060. var lendiff = change.text.length - (to.line - from.line) - 1;
  6061. // Remember that these lines changed, for updating the display
  6062. if (change.full)
  6063. regChange(cm);
  6064. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  6065. regLineChange(cm, from.line, "text");
  6066. else
  6067. regChange(cm, from.line, to.line + 1, lendiff);
  6068. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  6069. if (changeHandler || changesHandler) {
  6070. var obj = {
  6071. from: from, to: to,
  6072. text: change.text,
  6073. removed: change.removed,
  6074. origin: change.origin
  6075. };
  6076. if (changeHandler) signalLater(cm, "change", cm, obj);
  6077. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  6078. }
  6079. cm.display.selForContextMenu = null;
  6080. }
  6081. function replaceRange(doc, code, from, to, origin) {
  6082. if (!to) to = from;
  6083. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  6084. if (typeof code == "string") code = doc.splitLines(code);
  6085. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  6086. }
  6087. // SCROLLING THINGS INTO VIEW
  6088. // If an editor sits on the top or bottom of the window, partially
  6089. // scrolled out of view, this ensures that the cursor is visible.
  6090. function maybeScrollWindow(cm, coords) {
  6091. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  6092. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  6093. if (coords.top + box.top < 0) doScroll = true;
  6094. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  6095. if (doScroll != null && !phantom) {
  6096. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  6097. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  6098. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  6099. coords.left + "px; width: 2px;");
  6100. cm.display.lineSpace.appendChild(scrollNode);
  6101. scrollNode.scrollIntoView(doScroll);
  6102. cm.display.lineSpace.removeChild(scrollNode);
  6103. }
  6104. }
  6105. // Scroll a given position into view (immediately), verifying that
  6106. // it actually became visible (as line heights are accurately
  6107. // measured, the position of something may 'drift' during drawing).
  6108. function scrollPosIntoView(cm, pos, end, margin) {
  6109. if (margin == null) margin = 0;
  6110. for (var limit = 0; limit < 5; limit++) {
  6111. var changed = false, coords = cursorCoords(cm, pos);
  6112. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  6113. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  6114. Math.min(coords.top, endCoords.top) - margin,
  6115. Math.max(coords.left, endCoords.left),
  6116. Math.max(coords.bottom, endCoords.bottom) + margin);
  6117. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  6118. if (scrollPos.scrollTop != null) {
  6119. setScrollTop(cm, scrollPos.scrollTop);
  6120. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  6121. }
  6122. if (scrollPos.scrollLeft != null) {
  6123. setScrollLeft(cm, scrollPos.scrollLeft);
  6124. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  6125. }
  6126. if (!changed) break;
  6127. }
  6128. return coords;
  6129. }
  6130. // Scroll a given set of coordinates into view (immediately).
  6131. function scrollIntoView(cm, x1, y1, x2, y2) {
  6132. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  6133. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  6134. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  6135. }
  6136. // Calculate a new scroll position needed to scroll the given
  6137. // rectangle into view. Returns an object with scrollTop and
  6138. // scrollLeft properties. When these are undefined, the
  6139. // vertical/horizontal position does not need to be adjusted.
  6140. function calculateScrollPos(cm, x1, y1, x2, y2) {
  6141. var display = cm.display, snapMargin = textHeight(cm.display);
  6142. if (y1 < 0) y1 = 0;
  6143. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  6144. var screen = displayHeight(cm), result = {};
  6145. if (y2 - y1 > screen) y2 = y1 + screen;
  6146. var docBottom = cm.doc.height + paddingVert(display);
  6147. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  6148. if (y1 < screentop) {
  6149. result.scrollTop = atTop ? 0 : y1;
  6150. } else if (y2 > screentop + screen) {
  6151. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  6152. if (newTop != screentop) result.scrollTop = newTop;
  6153. }
  6154. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  6155. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  6156. var tooWide = x2 - x1 > screenw;
  6157. if (tooWide) x2 = x1 + screenw;
  6158. if (x1 < 10)
  6159. result.scrollLeft = 0;
  6160. else if (x1 < screenleft)
  6161. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  6162. else if (x2 > screenw + screenleft - 3)
  6163. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  6164. return result;
  6165. }
  6166. // Store a relative adjustment to the scroll position in the current
  6167. // operation (to be applied when the operation finishes).
  6168. function addToScrollPos(cm, left, top) {
  6169. if (left != null || top != null) resolveScrollToPos(cm);
  6170. if (left != null)
  6171. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  6172. if (top != null)
  6173. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  6174. }
  6175. // Make sure that at the end of the operation the current cursor is
  6176. // shown.
  6177. function ensureCursorVisible(cm) {
  6178. resolveScrollToPos(cm);
  6179. var cur = cm.getCursor(), from = cur, to = cur;
  6180. if (!cm.options.lineWrapping) {
  6181. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  6182. to = Pos(cur.line, cur.ch + 1);
  6183. }
  6184. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  6185. }
  6186. // When an operation has its scrollToPos property set, and another
  6187. // scroll action is applied before the end of the operation, this
  6188. // 'simulates' scrolling that position into view in a cheap way, so
  6189. // that the effect of intermediate scroll commands is not ignored.
  6190. function resolveScrollToPos(cm) {
  6191. var range = cm.curOp.scrollToPos;
  6192. if (range) {
  6193. cm.curOp.scrollToPos = null;
  6194. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  6195. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  6196. Math.min(from.top, to.top) - range.margin,
  6197. Math.max(from.right, to.right),
  6198. Math.max(from.bottom, to.bottom) + range.margin);
  6199. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  6200. }
  6201. }
  6202. // API UTILITIES
  6203. // Indent the given line. The how parameter can be "smart",
  6204. // "add"/null, "subtract", or "prev". When aggressive is false
  6205. // (typically set to true for forced single-line indents), empty
  6206. // lines are not indented, and places where the mode returns Pass
  6207. // are left alone.
  6208. function indentLine(cm, n, how, aggressive) {
  6209. var doc = cm.doc, state;
  6210. if (how == null) how = "add";
  6211. if (how == "smart") {
  6212. // Fall back to "prev" when the mode doesn't have an indentation
  6213. // method.
  6214. if (!doc.mode.indent) how = "prev";
  6215. else state = getStateBefore(cm, n);
  6216. }
  6217. var tabSize = cm.options.tabSize;
  6218. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  6219. if (line.stateAfter) line.stateAfter = null;
  6220. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  6221. if (!aggressive && !/\S/.test(line.text)) {
  6222. indentation = 0;
  6223. how = "not";
  6224. } else if (how == "smart") {
  6225. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  6226. if (indentation == Pass || indentation > 150) {
  6227. if (!aggressive) return;
  6228. how = "prev";
  6229. }
  6230. }
  6231. if (how == "prev") {
  6232. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  6233. else indentation = 0;
  6234. } else if (how == "add") {
  6235. indentation = curSpace + cm.options.indentUnit;
  6236. } else if (how == "subtract") {
  6237. indentation = curSpace - cm.options.indentUnit;
  6238. } else if (typeof how == "number") {
  6239. indentation = curSpace + how;
  6240. }
  6241. indentation = Math.max(0, indentation);
  6242. var indentString = "", pos = 0;
  6243. if (cm.options.indentWithTabs)
  6244. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  6245. if (pos < indentation) indentString += spaceStr(indentation - pos);
  6246. if (indentString != curSpaceString) {
  6247. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  6248. line.stateAfter = null;
  6249. return true;
  6250. } else {
  6251. // Ensure that, if the cursor was in the whitespace at the start
  6252. // of the line, it is moved to the end of that space.
  6253. for (var i = 0; i < doc.sel.ranges.length; i++) {
  6254. var range = doc.sel.ranges[i];
  6255. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  6256. var pos = Pos(n, curSpaceString.length);
  6257. replaceOneSelection(doc, i, new Range(pos, pos));
  6258. break;
  6259. }
  6260. }
  6261. }
  6262. }
  6263. // Utility for applying a change to a line by handle or number,
  6264. // returning the number and optionally registering the line as
  6265. // changed.
  6266. function changeLine(doc, handle, changeType, op) {
  6267. var no = handle, line = handle;
  6268. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  6269. else no = lineNo(handle);
  6270. if (no == null) return null;
  6271. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  6272. return line;
  6273. }
  6274. // Helper for deleting text near the selection(s), used to implement
  6275. // backspace, delete, and similar functionality.
  6276. function deleteNearSelection(cm, compute) {
  6277. var ranges = cm.doc.sel.ranges, kill = [];
  6278. // Build up a set of ranges to kill first, merging overlapping
  6279. // ranges.
  6280. for (var i = 0; i < ranges.length; i++) {
  6281. var toKill = compute(ranges[i]);
  6282. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6283. var replaced = kill.pop();
  6284. if (cmp(replaced.from, toKill.from) < 0) {
  6285. toKill.from = replaced.from;
  6286. break;
  6287. }
  6288. }
  6289. kill.push(toKill);
  6290. }
  6291. // Next, remove those actual ranges.
  6292. runInOp(cm, function() {
  6293. for (var i = kill.length - 1; i >= 0; i--)
  6294. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  6295. ensureCursorVisible(cm);
  6296. });
  6297. }
  6298. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  6299. // right), unit can be "char", "column" (like char, but doesn't
  6300. // cross line boundaries), "word" (across next word), or "group" (to
  6301. // the start of next group of word or non-word-non-whitespace
  6302. // chars). The visually param controls whether, in right-to-left
  6303. // text, direction 1 means to move towards the next index in the
  6304. // string, or towards the character to the right of the current
  6305. // position. The resulting position will have a hitSide=true
  6306. // property if it reached the end of the document.
  6307. function findPosH(doc, pos, dir, unit, visually) {
  6308. var line = pos.line, ch = pos.ch, origDir = dir;
  6309. var lineObj = getLine(doc, line);
  6310. function findNextLine() {
  6311. var l = line + dir;
  6312. if (l < doc.first || l >= doc.first + doc.size) return false
  6313. line = l;
  6314. return lineObj = getLine(doc, l);
  6315. }
  6316. function moveOnce(boundToLine) {
  6317. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  6318. if (next == null) {
  6319. if (!boundToLine && findNextLine()) {
  6320. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  6321. else ch = dir < 0 ? lineObj.text.length : 0;
  6322. } else return false
  6323. } else ch = next;
  6324. return true;
  6325. }
  6326. if (unit == "char") {
  6327. moveOnce()
  6328. } else if (unit == "column") {
  6329. moveOnce(true)
  6330. } else if (unit == "word" || unit == "group") {
  6331. var sawType = null, group = unit == "group";
  6332. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  6333. for (var first = true;; first = false) {
  6334. if (dir < 0 && !moveOnce(!first)) break;
  6335. var cur = lineObj.text.charAt(ch) || "\n";
  6336. var type = isWordChar(cur, helper) ? "w"
  6337. : group && cur == "\n" ? "n"
  6338. : !group || /\s/.test(cur) ? null
  6339. : "p";
  6340. if (group && !first && !type) type = "s";
  6341. if (sawType && sawType != type) {
  6342. if (dir < 0) {dir = 1; moveOnce();}
  6343. break;
  6344. }
  6345. if (type) sawType = type;
  6346. if (dir > 0 && !moveOnce(!first)) break;
  6347. }
  6348. }
  6349. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
  6350. if (!cmp(pos, result)) result.hitSide = true;
  6351. return result;
  6352. }
  6353. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  6354. // "page" or "line". The resulting position will have a hitSide=true
  6355. // property if it reached the end of the document.
  6356. function findPosV(cm, pos, dir, unit) {
  6357. var doc = cm.doc, x = pos.left, y;
  6358. if (unit == "page") {
  6359. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  6360. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  6361. } else if (unit == "line") {
  6362. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  6363. }
  6364. for (;;) {
  6365. var target = coordsChar(cm, x, y);
  6366. if (!target.outside) break;
  6367. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  6368. y += dir * 5;
  6369. }
  6370. return target;
  6371. }
  6372. // EDITOR METHODS
  6373. // The publicly visible API. Note that methodOp(f) means
  6374. // 'wrap f in an operation, performed on its `this` parameter'.
  6375. // This is not the complete set of editor methods. Most of the
  6376. // methods defined on the Doc type are also injected into
  6377. // CodeMirror.prototype, for backwards compatibility and
  6378. // convenience.
  6379. CodeMirror.prototype = {
  6380. constructor: CodeMirror,
  6381. focus: function(){window.focus(); this.display.input.focus();},
  6382. setOption: function(option, value) {
  6383. var options = this.options, old = options[option];
  6384. if (options[option] == value && option != "mode") return;
  6385. options[option] = value;
  6386. if (optionHandlers.hasOwnProperty(option))
  6387. operation(this, optionHandlers[option])(this, value, old);
  6388. },
  6389. getOption: function(option) {return this.options[option];},
  6390. getDoc: function() {return this.doc;},
  6391. addKeyMap: function(map, bottom) {
  6392. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  6393. },
  6394. removeKeyMap: function(map) {
  6395. var maps = this.state.keyMaps;
  6396. for (var i = 0; i < maps.length; ++i)
  6397. if (maps[i] == map || maps[i].name == map) {
  6398. maps.splice(i, 1);
  6399. return true;
  6400. }
  6401. },
  6402. addOverlay: methodOp(function(spec, options) {
  6403. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  6404. if (mode.startState) throw new Error("Overlays may not be stateful.");
  6405. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  6406. this.state.modeGen++;
  6407. regChange(this);
  6408. }),
  6409. removeOverlay: methodOp(function(spec) {
  6410. var overlays = this.state.overlays;
  6411. for (var i = 0; i < overlays.length; ++i) {
  6412. var cur = overlays[i].modeSpec;
  6413. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  6414. overlays.splice(i, 1);
  6415. this.state.modeGen++;
  6416. regChange(this);
  6417. return;
  6418. }
  6419. }
  6420. }),
  6421. indentLine: methodOp(function(n, dir, aggressive) {
  6422. if (typeof dir != "string" && typeof dir != "number") {
  6423. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  6424. else dir = dir ? "add" : "subtract";
  6425. }
  6426. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  6427. }),
  6428. indentSelection: methodOp(function(how) {
  6429. var ranges = this.doc.sel.ranges, end = -1;
  6430. for (var i = 0; i < ranges.length; i++) {
  6431. var range = ranges[i];
  6432. if (!range.empty()) {
  6433. var from = range.from(), to = range.to();
  6434. var start = Math.max(end, from.line);
  6435. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  6436. for (var j = start; j < end; ++j)
  6437. indentLine(this, j, how);
  6438. var newRanges = this.doc.sel.ranges;
  6439. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  6440. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  6441. } else if (range.head.line > end) {
  6442. indentLine(this, range.head.line, how, true);
  6443. end = range.head.line;
  6444. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  6445. }
  6446. }
  6447. }),
  6448. // Fetch the parser token for a given character. Useful for hacks
  6449. // that want to inspect the mode state (say, for completion).
  6450. getTokenAt: function(pos, precise) {
  6451. return takeToken(this, pos, precise);
  6452. },
  6453. getLineTokens: function(line, precise) {
  6454. return takeToken(this, Pos(line), precise, true);
  6455. },
  6456. getTokenTypeAt: function(pos) {
  6457. pos = clipPos(this.doc, pos);
  6458. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  6459. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  6460. var type;
  6461. if (ch == 0) type = styles[2];
  6462. else for (;;) {
  6463. var mid = (before + after) >> 1;
  6464. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  6465. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  6466. else { type = styles[mid * 2 + 2]; break; }
  6467. }
  6468. var cut = type ? type.indexOf("cm-overlay ") : -1;
  6469. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  6470. },
  6471. getModeAt: function(pos) {
  6472. var mode = this.doc.mode;
  6473. if (!mode.innerMode) return mode;
  6474. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  6475. },
  6476. getHelper: function(pos, type) {
  6477. return this.getHelpers(pos, type)[0];
  6478. },
  6479. getHelpers: function(pos, type) {
  6480. var found = [];
  6481. if (!helpers.hasOwnProperty(type)) return found;
  6482. var help = helpers[type], mode = this.getModeAt(pos);
  6483. if (typeof mode[type] == "string") {
  6484. if (help[mode[type]]) found.push(help[mode[type]]);
  6485. } else if (mode[type]) {
  6486. for (var i = 0; i < mode[type].length; i++) {
  6487. var val = help[mode[type][i]];
  6488. if (val) found.push(val);
  6489. }
  6490. } else if (mode.helperType && help[mode.helperType]) {
  6491. found.push(help[mode.helperType]);
  6492. } else if (help[mode.name]) {
  6493. found.push(help[mode.name]);
  6494. }
  6495. for (var i = 0; i < help._global.length; i++) {
  6496. var cur = help._global[i];
  6497. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  6498. found.push(cur.val);
  6499. }
  6500. return found;
  6501. },
  6502. getStateAfter: function(line, precise) {
  6503. var doc = this.doc;
  6504. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  6505. return getStateBefore(this, line + 1, precise);
  6506. },
  6507. cursorCoords: function(start, mode) {
  6508. var pos, range = this.doc.sel.primary();
  6509. if (start == null) pos = range.head;
  6510. else if (typeof start == "object") pos = clipPos(this.doc, start);
  6511. else pos = start ? range.from() : range.to();
  6512. return cursorCoords(this, pos, mode || "page");
  6513. },
  6514. charCoords: function(pos, mode) {
  6515. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  6516. },
  6517. coordsChar: function(coords, mode) {
  6518. coords = fromCoordSystem(this, coords, mode || "page");
  6519. return coordsChar(this, coords.left, coords.top);
  6520. },
  6521. lineAtHeight: function(height, mode) {
  6522. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  6523. return lineAtHeight(this.doc, height + this.display.viewOffset);
  6524. },
  6525. heightAtLine: function(line, mode) {
  6526. var end = false, lineObj;
  6527. if (typeof line == "number") {
  6528. var last = this.doc.first + this.doc.size - 1;
  6529. if (line < this.doc.first) line = this.doc.first;
  6530. else if (line > last) { line = last; end = true; }
  6531. lineObj = getLine(this.doc, line);
  6532. } else {
  6533. lineObj = line;
  6534. }
  6535. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  6536. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  6537. },
  6538. defaultTextHeight: function() { return textHeight(this.display); },
  6539. defaultCharWidth: function() { return charWidth(this.display); },
  6540. setGutterMarker: methodOp(function(line, gutterID, value) {
  6541. return changeLine(this.doc, line, "gutter", function(line) {
  6542. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  6543. markers[gutterID] = value;
  6544. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  6545. return true;
  6546. });
  6547. }),
  6548. clearGutter: methodOp(function(gutterID) {
  6549. var cm = this, doc = cm.doc, i = doc.first;
  6550. doc.iter(function(line) {
  6551. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  6552. line.gutterMarkers[gutterID] = null;
  6553. regLineChange(cm, i, "gutter");
  6554. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  6555. }
  6556. ++i;
  6557. });
  6558. }),
  6559. lineInfo: function(line) {
  6560. if (typeof line == "number") {
  6561. if (!isLine(this.doc, line)) return null;
  6562. var n = line;
  6563. line = getLine(this.doc, line);
  6564. if (!line) return null;
  6565. } else {
  6566. var n = lineNo(line);
  6567. if (n == null) return null;
  6568. }
  6569. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  6570. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  6571. widgets: line.widgets};
  6572. },
  6573. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  6574. addWidget: function(pos, node, scroll, vert, horiz) {
  6575. var display = this.display;
  6576. pos = cursorCoords(this, clipPos(this.doc, pos));
  6577. var top = pos.bottom, left = pos.left;
  6578. node.style.position = "absolute";
  6579. node.setAttribute("cm-ignore-events", "true");
  6580. this.display.input.setUneditable(node);
  6581. display.sizer.appendChild(node);
  6582. if (vert == "over") {
  6583. top = pos.top;
  6584. } else if (vert == "above" || vert == "near") {
  6585. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  6586. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  6587. // Default to positioning above (if specified and possible); otherwise default to positioning below
  6588. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  6589. top = pos.top - node.offsetHeight;
  6590. else if (pos.bottom + node.offsetHeight <= vspace)
  6591. top = pos.bottom;
  6592. if (left + node.offsetWidth > hspace)
  6593. left = hspace - node.offsetWidth;
  6594. }
  6595. node.style.top = top + "px";
  6596. node.style.left = node.style.right = "";
  6597. if (horiz == "right") {
  6598. left = display.sizer.clientWidth - node.offsetWidth;
  6599. node.style.right = "0px";
  6600. } else {
  6601. if (horiz == "left") left = 0;
  6602. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  6603. node.style.left = left + "px";
  6604. }
  6605. if (scroll)
  6606. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  6607. },
  6608. triggerOnKeyDown: methodOp(onKeyDown),
  6609. triggerOnKeyPress: methodOp(onKeyPress),
  6610. triggerOnKeyUp: onKeyUp,
  6611. execCommand: function(cmd) {
  6612. if (commands.hasOwnProperty(cmd))
  6613. return commands[cmd].call(null, this);
  6614. },
  6615. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  6616. findPosH: function(from, amount, unit, visually) {
  6617. var dir = 1;
  6618. if (amount < 0) { dir = -1; amount = -amount; }
  6619. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  6620. cur = findPosH(this.doc, cur, dir, unit, visually);
  6621. if (cur.hitSide) break;
  6622. }
  6623. return cur;
  6624. },
  6625. moveH: methodOp(function(dir, unit) {
  6626. var cm = this;
  6627. cm.extendSelectionsBy(function(range) {
  6628. if (cm.display.shift || cm.doc.extend || range.empty())
  6629. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  6630. else
  6631. return dir < 0 ? range.from() : range.to();
  6632. }, sel_move);
  6633. }),
  6634. deleteH: methodOp(function(dir, unit) {
  6635. var sel = this.doc.sel, doc = this.doc;
  6636. if (sel.somethingSelected())
  6637. doc.replaceSelection("", null, "+delete");
  6638. else
  6639. deleteNearSelection(this, function(range) {
  6640. var other = findPosH(doc, range.head, dir, unit, false);
  6641. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  6642. });
  6643. }),
  6644. findPosV: function(from, amount, unit, goalColumn) {
  6645. var dir = 1, x = goalColumn;
  6646. if (amount < 0) { dir = -1; amount = -amount; }
  6647. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  6648. var coords = cursorCoords(this, cur, "div");
  6649. if (x == null) x = coords.left;
  6650. else coords.left = x;
  6651. cur = findPosV(this, coords, dir, unit);
  6652. if (cur.hitSide) break;
  6653. }
  6654. return cur;
  6655. },
  6656. moveV: methodOp(function(dir, unit) {
  6657. var cm = this, doc = this.doc, goals = [];
  6658. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  6659. doc.extendSelectionsBy(function(range) {
  6660. if (collapse)
  6661. return dir < 0 ? range.from() : range.to();
  6662. var headPos = cursorCoords(cm, range.head, "div");
  6663. if (range.goalColumn != null) headPos.left = range.goalColumn;
  6664. goals.push(headPos.left);
  6665. var pos = findPosV(cm, headPos, dir, unit);
  6666. if (unit == "page" && range == doc.sel.primary())
  6667. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  6668. return pos;
  6669. }, sel_move);
  6670. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  6671. doc.sel.ranges[i].goalColumn = goals[i];
  6672. }),
  6673. // Find the word at the given position (as returned by coordsChar).
  6674. findWordAt: function(pos) {
  6675. var doc = this.doc, line = getLine(doc, pos.line).text;
  6676. var start = pos.ch, end = pos.ch;
  6677. if (line) {
  6678. var helper = this.getHelper(pos, "wordChars");
  6679. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  6680. var startChar = line.charAt(start);
  6681. var check = isWordChar(startChar, helper)
  6682. ? function(ch) { return isWordChar(ch, helper); }
  6683. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  6684. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  6685. while (start > 0 && check(line.charAt(start - 1))) --start;
  6686. while (end < line.length && check(line.charAt(end))) ++end;
  6687. }
  6688. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  6689. },
  6690. toggleOverwrite: function(value) {
  6691. if (value != null && value == this.state.overwrite) return;
  6692. if (this.state.overwrite = !this.state.overwrite)
  6693. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  6694. else
  6695. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  6696. signal(this, "overwriteToggle", this, this.state.overwrite);
  6697. },
  6698. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  6699. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  6700. scrollTo: methodOp(function(x, y) {
  6701. if (x != null || y != null) resolveScrollToPos(this);
  6702. if (x != null) this.curOp.scrollLeft = x;
  6703. if (y != null) this.curOp.scrollTop = y;
  6704. }),
  6705. getScrollInfo: function() {
  6706. var scroller = this.display.scroller;
  6707. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  6708. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  6709. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  6710. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  6711. },
  6712. scrollIntoView: methodOp(function(range, margin) {
  6713. if (range == null) {
  6714. range = {from: this.doc.sel.primary().head, to: null};
  6715. if (margin == null) margin = this.options.cursorScrollMargin;
  6716. } else if (typeof range == "number") {
  6717. range = {from: Pos(range, 0), to: null};
  6718. } else if (range.from == null) {
  6719. range = {from: range, to: null};
  6720. }
  6721. if (!range.to) range.to = range.from;
  6722. range.margin = margin || 0;
  6723. if (range.from.line != null) {
  6724. resolveScrollToPos(this);
  6725. this.curOp.scrollToPos = range;
  6726. } else {
  6727. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  6728. Math.min(range.from.top, range.to.top) - range.margin,
  6729. Math.max(range.from.right, range.to.right),
  6730. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  6731. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  6732. }
  6733. }),
  6734. setSize: methodOp(function(width, height) {
  6735. var cm = this;
  6736. function interpret(val) {
  6737. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  6738. }
  6739. if (width != null) cm.display.wrapper.style.width = interpret(width);
  6740. if (height != null) cm.display.wrapper.style.height = interpret(height);
  6741. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  6742. var lineNo = cm.display.viewFrom;
  6743. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  6744. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  6745. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  6746. ++lineNo;
  6747. });
  6748. cm.curOp.forceUpdate = true;
  6749. signal(cm, "refresh", this);
  6750. }),
  6751. operation: function(f){return runInOp(this, f);},
  6752. refresh: methodOp(function() {
  6753. var oldHeight = this.display.cachedTextHeight;
  6754. regChange(this);
  6755. this.curOp.forceUpdate = true;
  6756. clearCaches(this);
  6757. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  6758. updateGutterSpace(this);
  6759. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  6760. estimateLineHeights(this);
  6761. signal(this, "refresh", this);
  6762. }),
  6763. swapDoc: methodOp(function(doc) {
  6764. var old = this.doc;
  6765. old.cm = null;
  6766. attachDoc(this, doc);
  6767. clearCaches(this);
  6768. this.display.input.reset();
  6769. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  6770. this.curOp.forceScroll = true;
  6771. signalLater(this, "swapDoc", this, old);
  6772. return old;
  6773. }),
  6774. getInputField: function(){return this.display.input.getField();},
  6775. getWrapperElement: function(){return this.display.wrapper;},
  6776. getScrollerElement: function(){return this.display.scroller;},
  6777. getGutterElement: function(){return this.display.gutters;}
  6778. };
  6779. eventMixin(CodeMirror);
  6780. // OPTION DEFAULTS
  6781. // The default configuration options.
  6782. var defaults = CodeMirror.defaults = {};
  6783. // Functions to run when options are changed.
  6784. var optionHandlers = CodeMirror.optionHandlers = {};
  6785. function option(name, deflt, handle, notOnInit) {
  6786. CodeMirror.defaults[name] = deflt;
  6787. if (handle) optionHandlers[name] =
  6788. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  6789. }
  6790. // Passed to option handlers when there is no old value.
  6791. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  6792. // These two are, on init, called from the constructor because they
  6793. // have to be initialized before the editor can start at all.
  6794. option("value", "", function(cm, val) {
  6795. cm.setValue(val);
  6796. }, true);
  6797. option("mode", null, function(cm, val) {
  6798. cm.doc.modeOption = val;
  6799. loadMode(cm);
  6800. }, true);
  6801. option("indentUnit", 2, loadMode, true);
  6802. option("indentWithTabs", false);
  6803. option("smartIndent", true);
  6804. option("tabSize", 4, function(cm) {
  6805. resetModeState(cm);
  6806. clearCaches(cm);
  6807. regChange(cm);
  6808. }, true);
  6809. option("lineSeparator", null, function(cm, val) {
  6810. cm.doc.lineSep = val;
  6811. if (!val) return;
  6812. var newBreaks = [], lineNo = cm.doc.first;
  6813. cm.doc.iter(function(line) {
  6814. for (var pos = 0;;) {
  6815. var found = line.text.indexOf(val, pos);
  6816. if (found == -1) break;
  6817. pos = found + val.length;
  6818. newBreaks.push(Pos(lineNo, found));
  6819. }
  6820. lineNo++;
  6821. });
  6822. for (var i = newBreaks.length - 1; i >= 0; i--)
  6823. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  6824. });
  6825. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  6826. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6827. if (old != CodeMirror.Init) cm.refresh();
  6828. });
  6829. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  6830. option("electricChars", true);
  6831. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  6832. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  6833. }, true);
  6834. option("rtlMoveVisually", !windows);
  6835. option("wholeLineUpdateBefore", true);
  6836. option("theme", "default", function(cm) {
  6837. themeChanged(cm);
  6838. guttersChanged(cm);
  6839. }, true);
  6840. option("keyMap", "default", function(cm, val, old) {
  6841. var next = getKeyMap(val);
  6842. var prev = old != CodeMirror.Init && getKeyMap(old);
  6843. if (prev && prev.detach) prev.detach(cm, next);
  6844. if (next.attach) next.attach(cm, prev || null);
  6845. });
  6846. option("extraKeys", null);
  6847. option("lineWrapping", false, wrappingChanged, true);
  6848. option("gutters", [], function(cm) {
  6849. setGuttersForLineNumbers(cm.options);
  6850. guttersChanged(cm);
  6851. }, true);
  6852. option("fixedGutter", true, function(cm, val) {
  6853. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  6854. cm.refresh();
  6855. }, true);
  6856. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  6857. option("scrollbarStyle", "native", function(cm) {
  6858. initScrollbars(cm);
  6859. updateScrollbars(cm);
  6860. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  6861. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  6862. }, true);
  6863. option("lineNumbers", false, function(cm) {
  6864. setGuttersForLineNumbers(cm.options);
  6865. guttersChanged(cm);
  6866. }, true);
  6867. option("firstLineNumber", 1, guttersChanged, true);
  6868. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  6869. option("showCursorWhenSelecting", false, updateSelection, true);
  6870. option("resetSelectionOnContextMenu", true);
  6871. option("lineWiseCopyCut", true);
  6872. option("readOnly", false, function(cm, val) {
  6873. if (val == "nocursor") {
  6874. onBlur(cm);
  6875. cm.display.input.blur();
  6876. cm.display.disabled = true;
  6877. } else {
  6878. cm.display.disabled = false;
  6879. }
  6880. cm.display.input.readOnlyChanged(val)
  6881. });
  6882. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  6883. option("dragDrop", true, dragDropChanged);
  6884. option("allowDropFileTypes", null);
  6885. option("cursorBlinkRate", 530);
  6886. option("cursorScrollMargin", 0);
  6887. option("cursorHeight", 1, updateSelection, true);
  6888. option("singleCursorHeightPerLine", true, updateSelection, true);
  6889. option("workTime", 100);
  6890. option("workDelay", 100);
  6891. option("flattenSpans", true, resetModeState, true);
  6892. option("addModeClass", false, resetModeState, true);
  6893. option("pollInterval", 100);
  6894. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  6895. option("historyEventDelay", 1250);
  6896. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  6897. option("maxHighlightLength", 10000, resetModeState, true);
  6898. option("moveInputWithCursor", true, function(cm, val) {
  6899. if (!val) cm.display.input.resetPosition();
  6900. });
  6901. option("tabindex", null, function(cm, val) {
  6902. cm.display.input.getField().tabIndex = val || "";
  6903. });
  6904. option("autofocus", null);
  6905. // MODE DEFINITION AND QUERYING
  6906. // Known modes, by name and by MIME
  6907. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  6908. // Extra arguments are stored as the mode's dependencies, which is
  6909. // used by (legacy) mechanisms like loadmode.js to automatically
  6910. // load a mode. (Preferred mechanism is the require/define calls.)
  6911. CodeMirror.defineMode = function(name, mode) {
  6912. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  6913. if (arguments.length > 2)
  6914. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  6915. modes[name] = mode;
  6916. };
  6917. CodeMirror.defineMIME = function(mime, spec) {
  6918. mimeModes[mime] = spec;
  6919. };
  6920. // Given a MIME type, a {name, ...options} config object, or a name
  6921. // string, return a mode config object.
  6922. CodeMirror.resolveMode = function(spec) {
  6923. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  6924. spec = mimeModes[spec];
  6925. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  6926. var found = mimeModes[spec.name];
  6927. if (typeof found == "string") found = {name: found};
  6928. spec = createObj(found, spec);
  6929. spec.name = found.name;
  6930. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  6931. return CodeMirror.resolveMode("application/xml");
  6932. }
  6933. if (typeof spec == "string") return {name: spec};
  6934. else return spec || {name: "null"};
  6935. };
  6936. // Given a mode spec (anything that resolveMode accepts), find and
  6937. // initialize an actual mode object.
  6938. CodeMirror.getMode = function(options, spec) {
  6939. var spec = CodeMirror.resolveMode(spec);
  6940. var mfactory = modes[spec.name];
  6941. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  6942. var modeObj = mfactory(options, spec);
  6943. if (modeExtensions.hasOwnProperty(spec.name)) {
  6944. var exts = modeExtensions[spec.name];
  6945. for (var prop in exts) {
  6946. if (!exts.hasOwnProperty(prop)) continue;
  6947. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  6948. modeObj[prop] = exts[prop];
  6949. }
  6950. }
  6951. modeObj.name = spec.name;
  6952. if (spec.helperType) modeObj.helperType = spec.helperType;
  6953. if (spec.modeProps) for (var prop in spec.modeProps)
  6954. modeObj[prop] = spec.modeProps[prop];
  6955. return modeObj;
  6956. };
  6957. // Minimal default mode.
  6958. CodeMirror.defineMode("null", function() {
  6959. return {token: function(stream) {stream.skipToEnd();}};
  6960. });
  6961. CodeMirror.defineMIME("text/plain", "null");
  6962. // This can be used to attach properties to mode objects from
  6963. // outside the actual mode definition.
  6964. var modeExtensions = CodeMirror.modeExtensions = {};
  6965. CodeMirror.extendMode = function(mode, properties) {
  6966. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  6967. copyObj(properties, exts);
  6968. };
  6969. // EXTENSIONS
  6970. CodeMirror.defineExtension = function(name, func) {
  6971. CodeMirror.prototype[name] = func;
  6972. };
  6973. CodeMirror.defineDocExtension = function(name, func) {
  6974. Doc.prototype[name] = func;
  6975. };
  6976. CodeMirror.defineOption = option;
  6977. var initHooks = [];
  6978. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  6979. var helpers = CodeMirror.helpers = {};
  6980. CodeMirror.registerHelper = function(type, name, value) {
  6981. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  6982. helpers[type][name] = value;
  6983. };
  6984. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  6985. CodeMirror.registerHelper(type, name, value);
  6986. helpers[type]._global.push({pred: predicate, val: value});
  6987. };
  6988. // MODE STATE HANDLING
  6989. // Utility functions for working with state. Exported because nested
  6990. // modes need to do this for their inner modes.
  6991. var copyState = CodeMirror.copyState = function(mode, state) {
  6992. if (state === true) return state;
  6993. if (mode.copyState) return mode.copyState(state);
  6994. var nstate = {};
  6995. for (var n in state) {
  6996. var val = state[n];
  6997. if (val instanceof Array) val = val.concat([]);
  6998. nstate[n] = val;
  6999. }
  7000. return nstate;
  7001. };
  7002. var startState = CodeMirror.startState = function(mode, a1, a2) {
  7003. return mode.startState ? mode.startState(a1, a2) : true;
  7004. };
  7005. // Given a mode and a state (for that mode), find the inner mode and
  7006. // state at the position that the state refers to.
  7007. CodeMirror.innerMode = function(mode, state) {
  7008. while (mode.innerMode) {
  7009. var info = mode.innerMode(state);
  7010. if (!info || info.mode == mode) break;
  7011. state = info.state;
  7012. mode = info.mode;
  7013. }
  7014. return info || {mode: mode, state: state};
  7015. };
  7016. // STANDARD COMMANDS
  7017. // Commands are parameter-less actions that can be performed on an
  7018. // editor, mostly used for keybindings.
  7019. var commands = CodeMirror.commands = {
  7020. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  7021. singleSelection: function(cm) {
  7022. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  7023. },
  7024. killLine: function(cm) {
  7025. deleteNearSelection(cm, function(range) {
  7026. if (range.empty()) {
  7027. var len = getLine(cm.doc, range.head.line).text.length;
  7028. if (range.head.ch == len && range.head.line < cm.lastLine())
  7029. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  7030. else
  7031. return {from: range.head, to: Pos(range.head.line, len)};
  7032. } else {
  7033. return {from: range.from(), to: range.to()};
  7034. }
  7035. });
  7036. },
  7037. deleteLine: function(cm) {
  7038. deleteNearSelection(cm, function(range) {
  7039. return {from: Pos(range.from().line, 0),
  7040. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  7041. });
  7042. },
  7043. delLineLeft: function(cm) {
  7044. deleteNearSelection(cm, function(range) {
  7045. return {from: Pos(range.from().line, 0), to: range.from()};
  7046. });
  7047. },
  7048. delWrappedLineLeft: function(cm) {
  7049. deleteNearSelection(cm, function(range) {
  7050. var top = cm.charCoords(range.head, "div").top + 5;
  7051. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  7052. return {from: leftPos, to: range.from()};
  7053. });
  7054. },
  7055. delWrappedLineRight: function(cm) {
  7056. deleteNearSelection(cm, function(range) {
  7057. var top = cm.charCoords(range.head, "div").top + 5;
  7058. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  7059. return {from: range.from(), to: rightPos };
  7060. });
  7061. },
  7062. undo: function(cm) {cm.undo();},
  7063. redo: function(cm) {cm.redo();},
  7064. undoSelection: function(cm) {cm.undoSelection();},
  7065. redoSelection: function(cm) {cm.redoSelection();},
  7066. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  7067. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  7068. goLineStart: function(cm) {
  7069. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  7070. {origin: "+move", bias: 1});
  7071. },
  7072. goLineStartSmart: function(cm) {
  7073. cm.extendSelectionsBy(function(range) {
  7074. return lineStartSmart(cm, range.head);
  7075. }, {origin: "+move", bias: 1});
  7076. },
  7077. goLineEnd: function(cm) {
  7078. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  7079. {origin: "+move", bias: -1});
  7080. },
  7081. goLineRight: function(cm) {
  7082. cm.extendSelectionsBy(function(range) {
  7083. var top = cm.charCoords(range.head, "div").top + 5;
  7084. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  7085. }, sel_move);
  7086. },
  7087. goLineLeft: function(cm) {
  7088. cm.extendSelectionsBy(function(range) {
  7089. var top = cm.charCoords(range.head, "div").top + 5;
  7090. return cm.coordsChar({left: 0, top: top}, "div");
  7091. }, sel_move);
  7092. },
  7093. goLineLeftSmart: function(cm) {
  7094. cm.extendSelectionsBy(function(range) {
  7095. var top = cm.charCoords(range.head, "div").top + 5;
  7096. var pos = cm.coordsChar({left: 0, top: top}, "div");
  7097. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  7098. return pos;
  7099. }, sel_move);
  7100. },
  7101. goLineUp: function(cm) {cm.moveV(-1, "line");},
  7102. goLineDown: function(cm) {cm.moveV(1, "line");},
  7103. goPageUp: function(cm) {cm.moveV(-1, "page");},
  7104. goPageDown: function(cm) {cm.moveV(1, "page");},
  7105. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  7106. goCharRight: function(cm) {cm.moveH(1, "char");},
  7107. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  7108. goColumnRight: function(cm) {cm.moveH(1, "column");},
  7109. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  7110. goGroupRight: function(cm) {cm.moveH(1, "group");},
  7111. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  7112. goWordRight: function(cm) {cm.moveH(1, "word");},
  7113. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  7114. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  7115. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  7116. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  7117. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  7118. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  7119. indentAuto: function(cm) {cm.indentSelection("smart");},
  7120. indentMore: function(cm) {cm.indentSelection("add");},
  7121. indentLess: function(cm) {cm.indentSelection("subtract");},
  7122. insertTab: function(cm) {cm.replaceSelection("\t");},
  7123. insertSoftTab: function(cm) {
  7124. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  7125. for (var i = 0; i < ranges.length; i++) {
  7126. var pos = ranges[i].from();
  7127. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  7128. spaces.push(spaceStr(tabSize - col % tabSize));
  7129. }
  7130. cm.replaceSelections(spaces);
  7131. },
  7132. defaultTab: function(cm) {
  7133. if (cm.somethingSelected()) cm.indentSelection("add");
  7134. else cm.execCommand("insertTab");
  7135. },
  7136. transposeChars: function(cm) {
  7137. runInOp(cm, function() {
  7138. var ranges = cm.listSelections(), newSel = [];
  7139. for (var i = 0; i < ranges.length; i++) {
  7140. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  7141. if (line) {
  7142. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  7143. if (cur.ch > 0) {
  7144. cur = new Pos(cur.line, cur.ch + 1);
  7145. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  7146. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  7147. } else if (cur.line > cm.doc.first) {
  7148. var prev = getLine(cm.doc, cur.line - 1).text;
  7149. if (prev)
  7150. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  7151. prev.charAt(prev.length - 1),
  7152. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  7153. }
  7154. }
  7155. newSel.push(new Range(cur, cur));
  7156. }
  7157. cm.setSelections(newSel);
  7158. });
  7159. },
  7160. newlineAndIndent: function(cm) {
  7161. runInOp(cm, function() {
  7162. var len = cm.listSelections().length;
  7163. for (var i = 0; i < len; i++) {
  7164. var range = cm.listSelections()[i];
  7165. cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
  7166. cm.indentLine(range.from().line + 1, null, true);
  7167. }
  7168. ensureCursorVisible(cm);
  7169. });
  7170. },
  7171. openLine: function(cm) {cm.replaceSelection("\n", "start")},
  7172. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  7173. };
  7174. // STANDARD KEYMAPS
  7175. var keyMap = CodeMirror.keyMap = {};
  7176. keyMap.basic = {
  7177. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  7178. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  7179. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  7180. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  7181. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  7182. "Esc": "singleSelection"
  7183. };
  7184. // Note that the save and find-related commands aren't defined by
  7185. // default. User code or addons can define them. Unknown commands
  7186. // are simply ignored.
  7187. keyMap.pcDefault = {
  7188. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  7189. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  7190. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  7191. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  7192. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  7193. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  7194. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  7195. fallthrough: "basic"
  7196. };
  7197. // Very basic readline/emacs-style bindings, which are standard on Mac.
  7198. keyMap.emacsy = {
  7199. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  7200. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  7201. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  7202. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  7203. "Ctrl-O": "openLine"
  7204. };
  7205. keyMap.macDefault = {
  7206. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  7207. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  7208. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  7209. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  7210. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  7211. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  7212. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  7213. fallthrough: ["basic", "emacsy"]
  7214. };
  7215. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  7216. // KEYMAP DISPATCH
  7217. function normalizeKeyName(name) {
  7218. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  7219. var alt, ctrl, shift, cmd;
  7220. for (var i = 0; i < parts.length - 1; i++) {
  7221. var mod = parts[i];
  7222. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  7223. else if (/^a(lt)?$/i.test(mod)) alt = true;
  7224. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  7225. else if (/^s(hift)$/i.test(mod)) shift = true;
  7226. else throw new Error("Unrecognized modifier name: " + mod);
  7227. }
  7228. if (alt) name = "Alt-" + name;
  7229. if (ctrl) name = "Ctrl-" + name;
  7230. if (cmd) name = "Cmd-" + name;
  7231. if (shift) name = "Shift-" + name;
  7232. return name;
  7233. }
  7234. // This is a kludge to keep keymaps mostly working as raw objects
  7235. // (backwards compatibility) while at the same time support features
  7236. // like normalization and multi-stroke key bindings. It compiles a
  7237. // new normalized keymap, and then updates the old object to reflect
  7238. // this.
  7239. CodeMirror.normalizeKeyMap = function(keymap) {
  7240. var copy = {};
  7241. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  7242. var value = keymap[keyname];
  7243. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  7244. if (value == "...") { delete keymap[keyname]; continue; }
  7245. var keys = map(keyname.split(" "), normalizeKeyName);
  7246. for (var i = 0; i < keys.length; i++) {
  7247. var val, name;
  7248. if (i == keys.length - 1) {
  7249. name = keys.join(" ");
  7250. val = value;
  7251. } else {
  7252. name = keys.slice(0, i + 1).join(" ");
  7253. val = "...";
  7254. }
  7255. var prev = copy[name];
  7256. if (!prev) copy[name] = val;
  7257. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  7258. }
  7259. delete keymap[keyname];
  7260. }
  7261. for (var prop in copy) keymap[prop] = copy[prop];
  7262. return keymap;
  7263. };
  7264. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  7265. map = getKeyMap(map);
  7266. var found = map.call ? map.call(key, context) : map[key];
  7267. if (found === false) return "nothing";
  7268. if (found === "...") return "multi";
  7269. if (found != null && handle(found)) return "handled";
  7270. if (map.fallthrough) {
  7271. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  7272. return lookupKey(key, map.fallthrough, handle, context);
  7273. for (var i = 0; i < map.fallthrough.length; i++) {
  7274. var result = lookupKey(key, map.fallthrough[i], handle, context);
  7275. if (result) return result;
  7276. }
  7277. }
  7278. };
  7279. // Modifier key presses don't count as 'real' key presses for the
  7280. // purpose of keymap fallthrough.
  7281. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  7282. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  7283. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  7284. };
  7285. // Look up the name of a key as indicated by an event object.
  7286. var keyName = CodeMirror.keyName = function(event, noShift) {
  7287. if (presto && event.keyCode == 34 && event["char"]) return false;
  7288. var base = keyNames[event.keyCode], name = base;
  7289. if (name == null || event.altGraphKey) return false;
  7290. if (event.altKey && base != "Alt") name = "Alt-" + name;
  7291. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  7292. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  7293. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  7294. return name;
  7295. };
  7296. function getKeyMap(val) {
  7297. return typeof val == "string" ? keyMap[val] : val;
  7298. }
  7299. // FROMTEXTAREA
  7300. CodeMirror.fromTextArea = function(textarea, options) {
  7301. options = options ? copyObj(options) : {};
  7302. options.value = textarea.value;
  7303. if (!options.tabindex && textarea.tabIndex)
  7304. options.tabindex = textarea.tabIndex;
  7305. if (!options.placeholder && textarea.placeholder)
  7306. options.placeholder = textarea.placeholder;
  7307. // Set autofocus to true if this textarea is focused, or if it has
  7308. // autofocus and no other element is focused.
  7309. if (options.autofocus == null) {
  7310. var hasFocus = activeElt();
  7311. options.autofocus = hasFocus == textarea ||
  7312. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  7313. }
  7314. function save() {textarea.value = cm.getValue();}
  7315. if (textarea.form) {
  7316. on(textarea.form, "submit", save);
  7317. // Deplorable hack to make the submit method do the right thing.
  7318. if (!options.leaveSubmitMethodAlone) {
  7319. var form = textarea.form, realSubmit = form.submit;
  7320. try {
  7321. var wrappedSubmit = form.submit = function() {
  7322. save();
  7323. form.submit = realSubmit;
  7324. form.submit();
  7325. form.submit = wrappedSubmit;
  7326. };
  7327. } catch(e) {}
  7328. }
  7329. }
  7330. options.finishInit = function(cm) {
  7331. cm.save = save;
  7332. cm.getTextArea = function() { return textarea; };
  7333. cm.toTextArea = function() {
  7334. cm.toTextArea = isNaN; // Prevent this from being ran twice
  7335. save();
  7336. textarea.parentNode.removeChild(cm.getWrapperElement());
  7337. textarea.style.display = "";
  7338. if (textarea.form) {
  7339. off(textarea.form, "submit", save);
  7340. if (typeof textarea.form.submit == "function")
  7341. textarea.form.submit = realSubmit;
  7342. }
  7343. };
  7344. };
  7345. textarea.style.display = "none";
  7346. var cm = CodeMirror(function(node) {
  7347. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  7348. }, options);
  7349. return cm;
  7350. };
  7351. // STRING STREAM
  7352. // Fed to the mode parsers, provides helper functions to make
  7353. // parsers more succinct.
  7354. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  7355. this.pos = this.start = 0;
  7356. this.string = string;
  7357. this.tabSize = tabSize || 8;
  7358. this.lastColumnPos = this.lastColumnValue = 0;
  7359. this.lineStart = 0;
  7360. };
  7361. StringStream.prototype = {
  7362. eol: function() {return this.pos >= this.string.length;},
  7363. sol: function() {return this.pos == this.lineStart;},
  7364. peek: function() {return this.string.charAt(this.pos) || undefined;},
  7365. next: function() {
  7366. if (this.pos < this.string.length)
  7367. return this.string.charAt(this.pos++);
  7368. },
  7369. eat: function(match) {
  7370. var ch = this.string.charAt(this.pos);
  7371. if (typeof match == "string") var ok = ch == match;
  7372. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  7373. if (ok) {++this.pos; return ch;}
  7374. },
  7375. eatWhile: function(match) {
  7376. var start = this.pos;
  7377. while (this.eat(match)){}
  7378. return this.pos > start;
  7379. },
  7380. eatSpace: function() {
  7381. var start = this.pos;
  7382. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  7383. return this.pos > start;
  7384. },
  7385. skipToEnd: function() {this.pos = this.string.length;},
  7386. skipTo: function(ch) {
  7387. var found = this.string.indexOf(ch, this.pos);
  7388. if (found > -1) {this.pos = found; return true;}
  7389. },
  7390. backUp: function(n) {this.pos -= n;},
  7391. column: function() {
  7392. if (this.lastColumnPos < this.start) {
  7393. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  7394. this.lastColumnPos = this.start;
  7395. }
  7396. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  7397. },
  7398. indentation: function() {
  7399. return countColumn(this.string, null, this.tabSize) -
  7400. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  7401. },
  7402. match: function(pattern, consume, caseInsensitive) {
  7403. if (typeof pattern == "string") {
  7404. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  7405. var substr = this.string.substr(this.pos, pattern.length);
  7406. if (cased(substr) == cased(pattern)) {
  7407. if (consume !== false) this.pos += pattern.length;
  7408. return true;
  7409. }
  7410. } else {
  7411. var match = this.string.slice(this.pos).match(pattern);
  7412. if (match && match.index > 0) return null;
  7413. if (match && consume !== false) this.pos += match[0].length;
  7414. return match;
  7415. }
  7416. },
  7417. current: function(){return this.string.slice(this.start, this.pos);},
  7418. hideFirstChars: function(n, inner) {
  7419. this.lineStart += n;
  7420. try { return inner(); }
  7421. finally { this.lineStart -= n; }
  7422. }
  7423. };
  7424. // TEXTMARKERS
  7425. // Created with markText and setBookmark methods. A TextMarker is a
  7426. // handle that can be used to clear or find a marked position in the
  7427. // document. Line objects hold arrays (markedSpans) containing
  7428. // {from, to, marker} object pointing to such marker objects, and
  7429. // indicating that such a marker is present on that line. Multiple
  7430. // lines may point to the same marker when it spans across lines.
  7431. // The spans will have null for their from/to properties when the
  7432. // marker continues beyond the start/end of the line. Markers have
  7433. // links back to the lines they currently touch.
  7434. var nextMarkerId = 0;
  7435. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  7436. this.lines = [];
  7437. this.type = type;
  7438. this.doc = doc;
  7439. this.id = ++nextMarkerId;
  7440. };
  7441. eventMixin(TextMarker);
  7442. // Clear the marker.
  7443. TextMarker.prototype.clear = function() {
  7444. if (this.explicitlyCleared) return;
  7445. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  7446. if (withOp) startOperation(cm);
  7447. if (hasHandler(this, "clear")) {
  7448. var found = this.find();
  7449. if (found) signalLater(this, "clear", found.from, found.to);
  7450. }
  7451. var min = null, max = null;
  7452. for (var i = 0; i < this.lines.length; ++i) {
  7453. var line = this.lines[i];
  7454. var span = getMarkedSpanFor(line.markedSpans, this);
  7455. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  7456. else if (cm) {
  7457. if (span.to != null) max = lineNo(line);
  7458. if (span.from != null) min = lineNo(line);
  7459. }
  7460. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  7461. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  7462. updateLineHeight(line, textHeight(cm.display));
  7463. }
  7464. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  7465. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  7466. if (len > cm.display.maxLineLength) {
  7467. cm.display.maxLine = visual;
  7468. cm.display.maxLineLength = len;
  7469. cm.display.maxLineChanged = true;
  7470. }
  7471. }
  7472. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  7473. this.lines.length = 0;
  7474. this.explicitlyCleared = true;
  7475. if (this.atomic && this.doc.cantEdit) {
  7476. this.doc.cantEdit = false;
  7477. if (cm) reCheckSelection(cm.doc);
  7478. }
  7479. if (cm) signalLater(cm, "markerCleared", cm, this);
  7480. if (withOp) endOperation(cm);
  7481. if (this.parent) this.parent.clear();
  7482. };
  7483. // Find the position of the marker in the document. Returns a {from,
  7484. // to} object by default. Side can be passed to get a specific side
  7485. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  7486. // Pos objects returned contain a line object, rather than a line
  7487. // number (used to prevent looking up the same line twice).
  7488. TextMarker.prototype.find = function(side, lineObj) {
  7489. if (side == null && this.type == "bookmark") side = 1;
  7490. var from, to;
  7491. for (var i = 0; i < this.lines.length; ++i) {
  7492. var line = this.lines[i];
  7493. var span = getMarkedSpanFor(line.markedSpans, this);
  7494. if (span.from != null) {
  7495. from = Pos(lineObj ? line : lineNo(line), span.from);
  7496. if (side == -1) return from;
  7497. }
  7498. if (span.to != null) {
  7499. to = Pos(lineObj ? line : lineNo(line), span.to);
  7500. if (side == 1) return to;
  7501. }
  7502. }
  7503. return from && {from: from, to: to};
  7504. };
  7505. // Signals that the marker's widget changed, and surrounding layout
  7506. // should be recomputed.
  7507. TextMarker.prototype.changed = function() {
  7508. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  7509. if (!pos || !cm) return;
  7510. runInOp(cm, function() {
  7511. var line = pos.line, lineN = lineNo(pos.line);
  7512. var view = findViewForLine(cm, lineN);
  7513. if (view) {
  7514. clearLineMeasurementCacheFor(view);
  7515. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  7516. }
  7517. cm.curOp.updateMaxLine = true;
  7518. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  7519. var oldHeight = widget.height;
  7520. widget.height = null;
  7521. var dHeight = widgetHeight(widget) - oldHeight;
  7522. if (dHeight)
  7523. updateLineHeight(line, line.height + dHeight);
  7524. }
  7525. });
  7526. };
  7527. TextMarker.prototype.attachLine = function(line) {
  7528. if (!this.lines.length && this.doc.cm) {
  7529. var op = this.doc.cm.curOp;
  7530. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  7531. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  7532. }
  7533. this.lines.push(line);
  7534. };
  7535. TextMarker.prototype.detachLine = function(line) {
  7536. this.lines.splice(indexOf(this.lines, line), 1);
  7537. if (!this.lines.length && this.doc.cm) {
  7538. var op = this.doc.cm.curOp;
  7539. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  7540. }
  7541. };
  7542. // Collapsed markers have unique ids, in order to be able to order
  7543. // them, which is needed for uniquely determining an outer marker
  7544. // when they overlap (they may nest, but not partially overlap).
  7545. var nextMarkerId = 0;
  7546. // Create a marker, wire it up to the right lines, and
  7547. function markText(doc, from, to, options, type) {
  7548. // Shared markers (across linked documents) are handled separately
  7549. // (markTextShared will call out to this again, once per
  7550. // document).
  7551. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  7552. // Ensure we are in an operation.
  7553. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  7554. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  7555. if (options) copyObj(options, marker, false);
  7556. // Don't connect empty markers unless clearWhenEmpty is false
  7557. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  7558. return marker;
  7559. if (marker.replacedWith) {
  7560. // Showing up as a widget implies collapsed (widget replaces text)
  7561. marker.collapsed = true;
  7562. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  7563. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  7564. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  7565. }
  7566. if (marker.collapsed) {
  7567. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  7568. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  7569. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  7570. sawCollapsedSpans = true;
  7571. }
  7572. if (marker.addToHistory)
  7573. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  7574. var curLine = from.line, cm = doc.cm, updateMaxLine;
  7575. doc.iter(curLine, to.line + 1, function(line) {
  7576. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  7577. updateMaxLine = true;
  7578. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  7579. addMarkedSpan(line, new MarkedSpan(marker,
  7580. curLine == from.line ? from.ch : null,
  7581. curLine == to.line ? to.ch : null));
  7582. ++curLine;
  7583. });
  7584. // lineIsHidden depends on the presence of the spans, so needs a second pass
  7585. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  7586. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  7587. });
  7588. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  7589. if (marker.readOnly) {
  7590. sawReadOnlySpans = true;
  7591. if (doc.history.done.length || doc.history.undone.length)
  7592. doc.clearHistory();
  7593. }
  7594. if (marker.collapsed) {
  7595. marker.id = ++nextMarkerId;
  7596. marker.atomic = true;
  7597. }
  7598. if (cm) {
  7599. // Sync editor state
  7600. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  7601. if (marker.collapsed)
  7602. regChange(cm, from.line, to.line + 1);
  7603. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  7604. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  7605. if (marker.atomic) reCheckSelection(cm.doc);
  7606. signalLater(cm, "markerAdded", cm, marker);
  7607. }
  7608. return marker;
  7609. }
  7610. // SHARED TEXTMARKERS
  7611. // A shared marker spans multiple linked documents. It is
  7612. // implemented as a meta-marker-object controlling multiple normal
  7613. // markers.
  7614. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  7615. this.markers = markers;
  7616. this.primary = primary;
  7617. for (var i = 0; i < markers.length; ++i)
  7618. markers[i].parent = this;
  7619. };
  7620. eventMixin(SharedTextMarker);
  7621. SharedTextMarker.prototype.clear = function() {
  7622. if (this.explicitlyCleared) return;
  7623. this.explicitlyCleared = true;
  7624. for (var i = 0; i < this.markers.length; ++i)
  7625. this.markers[i].clear();
  7626. signalLater(this, "clear");
  7627. };
  7628. SharedTextMarker.prototype.find = function(side, lineObj) {
  7629. return this.primary.find(side, lineObj);
  7630. };
  7631. function markTextShared(doc, from, to, options, type) {
  7632. options = copyObj(options);
  7633. options.shared = false;
  7634. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  7635. var widget = options.widgetNode;
  7636. linkedDocs(doc, function(doc) {
  7637. if (widget) options.widgetNode = widget.cloneNode(true);
  7638. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  7639. for (var i = 0; i < doc.linked.length; ++i)
  7640. if (doc.linked[i].isParent) return;
  7641. primary = lst(markers);
  7642. });
  7643. return new SharedTextMarker(markers, primary);
  7644. }
  7645. function findSharedMarkers(doc) {
  7646. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  7647. function(m) { return m.parent; });
  7648. }
  7649. function copySharedMarkers(doc, markers) {
  7650. for (var i = 0; i < markers.length; i++) {
  7651. var marker = markers[i], pos = marker.find();
  7652. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  7653. if (cmp(mFrom, mTo)) {
  7654. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  7655. marker.markers.push(subMark);
  7656. subMark.parent = marker;
  7657. }
  7658. }
  7659. }
  7660. function detachSharedMarkers(markers) {
  7661. for (var i = 0; i < markers.length; i++) {
  7662. var marker = markers[i], linked = [marker.primary.doc];;
  7663. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  7664. for (var j = 0; j < marker.markers.length; j++) {
  7665. var subMarker = marker.markers[j];
  7666. if (indexOf(linked, subMarker.doc) == -1) {
  7667. subMarker.parent = null;
  7668. marker.markers.splice(j--, 1);
  7669. }
  7670. }
  7671. }
  7672. }
  7673. // TEXTMARKER SPANS
  7674. function MarkedSpan(marker, from, to) {
  7675. this.marker = marker;
  7676. this.from = from; this.to = to;
  7677. }
  7678. // Search an array of spans for a span matching the given marker.
  7679. function getMarkedSpanFor(spans, marker) {
  7680. if (spans) for (var i = 0; i < spans.length; ++i) {
  7681. var span = spans[i];
  7682. if (span.marker == marker) return span;
  7683. }
  7684. }
  7685. // Remove a span from an array, returning undefined if no spans are
  7686. // left (we don't store arrays for lines without spans).
  7687. function removeMarkedSpan(spans, span) {
  7688. for (var r, i = 0; i < spans.length; ++i)
  7689. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  7690. return r;
  7691. }
  7692. // Add a span to a line.
  7693. function addMarkedSpan(line, span) {
  7694. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  7695. span.marker.attachLine(line);
  7696. }
  7697. // Used for the algorithm that adjusts markers for a change in the
  7698. // document. These functions cut an array of spans at a given
  7699. // character position, returning an array of remaining chunks (or
  7700. // undefined if nothing remains).
  7701. function markedSpansBefore(old, startCh, isInsert) {
  7702. if (old) for (var i = 0, nw; i < old.length; ++i) {
  7703. var span = old[i], marker = span.marker;
  7704. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  7705. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  7706. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  7707. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  7708. }
  7709. }
  7710. return nw;
  7711. }
  7712. function markedSpansAfter(old, endCh, isInsert) {
  7713. if (old) for (var i = 0, nw; i < old.length; ++i) {
  7714. var span = old[i], marker = span.marker;
  7715. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  7716. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  7717. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  7718. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  7719. span.to == null ? null : span.to - endCh));
  7720. }
  7721. }
  7722. return nw;
  7723. }
  7724. // Given a change object, compute the new set of marker spans that
  7725. // cover the line in which the change took place. Removes spans
  7726. // entirely within the change, reconnects spans belonging to the
  7727. // same marker that appear on both sides of the change, and cuts off
  7728. // spans partially within the change. Returns an array of span
  7729. // arrays with one element for each line in (after) the change.
  7730. function stretchSpansOverChange(doc, change) {
  7731. if (change.full) return null;
  7732. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  7733. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  7734. if (!oldFirst && !oldLast) return null;
  7735. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  7736. // Get the spans that 'stick out' on both sides
  7737. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  7738. var last = markedSpansAfter(oldLast, endCh, isInsert);
  7739. // Next, merge those two ends
  7740. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  7741. if (first) {
  7742. // Fix up .to properties of first
  7743. for (var i = 0; i < first.length; ++i) {
  7744. var span = first[i];
  7745. if (span.to == null) {
  7746. var found = getMarkedSpanFor(last, span.marker);
  7747. if (!found) span.to = startCh;
  7748. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  7749. }
  7750. }
  7751. }
  7752. if (last) {
  7753. // Fix up .from in last (or move them into first in case of sameLine)
  7754. for (var i = 0; i < last.length; ++i) {
  7755. var span = last[i];
  7756. if (span.to != null) span.to += offset;
  7757. if (span.from == null) {
  7758. var found = getMarkedSpanFor(first, span.marker);
  7759. if (!found) {
  7760. span.from = offset;
  7761. if (sameLine) (first || (first = [])).push(span);
  7762. }
  7763. } else {
  7764. span.from += offset;
  7765. if (sameLine) (first || (first = [])).push(span);
  7766. }
  7767. }
  7768. }
  7769. // Make sure we didn't create any zero-length spans
  7770. if (first) first = clearEmptySpans(first);
  7771. if (last && last != first) last = clearEmptySpans(last);
  7772. var newMarkers = [first];
  7773. if (!sameLine) {
  7774. // Fill gap with whole-line-spans
  7775. var gap = change.text.length - 2, gapMarkers;
  7776. if (gap > 0 && first)
  7777. for (var i = 0; i < first.length; ++i)
  7778. if (first[i].to == null)
  7779. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  7780. for (var i = 0; i < gap; ++i)
  7781. newMarkers.push(gapMarkers);
  7782. newMarkers.push(last);
  7783. }
  7784. return newMarkers;
  7785. }
  7786. // Remove spans that are empty and don't have a clearWhenEmpty
  7787. // option of false.
  7788. function clearEmptySpans(spans) {
  7789. for (var i = 0; i < spans.length; ++i) {
  7790. var span = spans[i];
  7791. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  7792. spans.splice(i--, 1);
  7793. }
  7794. if (!spans.length) return null;
  7795. return spans;
  7796. }
  7797. // Used for un/re-doing changes from the history. Combines the
  7798. // result of computing the existing spans with the set of spans that
  7799. // existed in the history (so that deleting around a span and then
  7800. // undoing brings back the span).
  7801. function mergeOldSpans(doc, change) {
  7802. var old = getOldSpans(doc, change);
  7803. var stretched = stretchSpansOverChange(doc, change);
  7804. if (!old) return stretched;
  7805. if (!stretched) return old;
  7806. for (var i = 0; i < old.length; ++i) {
  7807. var oldCur = old[i], stretchCur = stretched[i];
  7808. if (oldCur && stretchCur) {
  7809. spans: for (var j = 0; j < stretchCur.length; ++j) {
  7810. var span = stretchCur[j];
  7811. for (var k = 0; k < oldCur.length; ++k)
  7812. if (oldCur[k].marker == span.marker) continue spans;
  7813. oldCur.push(span);
  7814. }
  7815. } else if (stretchCur) {
  7816. old[i] = stretchCur;
  7817. }
  7818. }
  7819. return old;
  7820. }
  7821. // Used to 'clip' out readOnly ranges when making a change.
  7822. function removeReadOnlyRanges(doc, from, to) {
  7823. var markers = null;
  7824. doc.iter(from.line, to.line + 1, function(line) {
  7825. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  7826. var mark = line.markedSpans[i].marker;
  7827. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  7828. (markers || (markers = [])).push(mark);
  7829. }
  7830. });
  7831. if (!markers) return null;
  7832. var parts = [{from: from, to: to}];
  7833. for (var i = 0; i < markers.length; ++i) {
  7834. var mk = markers[i], m = mk.find(0);
  7835. for (var j = 0; j < parts.length; ++j) {
  7836. var p = parts[j];
  7837. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  7838. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  7839. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  7840. newParts.push({from: p.from, to: m.from});
  7841. if (dto > 0 || !mk.inclusiveRight && !dto)
  7842. newParts.push({from: m.to, to: p.to});
  7843. parts.splice.apply(parts, newParts);
  7844. j += newParts.length - 1;
  7845. }
  7846. }
  7847. return parts;
  7848. }
  7849. // Connect or disconnect spans from a line.
  7850. function detachMarkedSpans(line) {
  7851. var spans = line.markedSpans;
  7852. if (!spans) return;
  7853. for (var i = 0; i < spans.length; ++i)
  7854. spans[i].marker.detachLine(line);
  7855. line.markedSpans = null;
  7856. }
  7857. function attachMarkedSpans(line, spans) {
  7858. if (!spans) return;
  7859. for (var i = 0; i < spans.length; ++i)
  7860. spans[i].marker.attachLine(line);
  7861. line.markedSpans = spans;
  7862. }
  7863. // Helpers used when computing which overlapping collapsed span
  7864. // counts as the larger one.
  7865. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  7866. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  7867. // Returns a number indicating which of two overlapping collapsed
  7868. // spans is larger (and thus includes the other). Falls back to
  7869. // comparing ids when the spans cover exactly the same range.
  7870. function compareCollapsedMarkers(a, b) {
  7871. var lenDiff = a.lines.length - b.lines.length;
  7872. if (lenDiff != 0) return lenDiff;
  7873. var aPos = a.find(), bPos = b.find();
  7874. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  7875. if (fromCmp) return -fromCmp;
  7876. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  7877. if (toCmp) return toCmp;
  7878. return b.id - a.id;
  7879. }
  7880. // Find out whether a line ends or starts in a collapsed span. If
  7881. // so, return the marker for that span.
  7882. function collapsedSpanAtSide(line, start) {
  7883. var sps = sawCollapsedSpans && line.markedSpans, found;
  7884. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  7885. sp = sps[i];
  7886. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  7887. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  7888. found = sp.marker;
  7889. }
  7890. return found;
  7891. }
  7892. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  7893. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  7894. // Test whether there exists a collapsed span that partially
  7895. // overlaps (covers the start or end, but not both) of a new span.
  7896. // Such overlap is not allowed.
  7897. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  7898. var line = getLine(doc, lineNo);
  7899. var sps = sawCollapsedSpans && line.markedSpans;
  7900. if (sps) for (var i = 0; i < sps.length; ++i) {
  7901. var sp = sps[i];
  7902. if (!sp.marker.collapsed) continue;
  7903. var found = sp.marker.find(0);
  7904. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  7905. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  7906. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  7907. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  7908. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  7909. return true;
  7910. }
  7911. }
  7912. // A visual line is a line as drawn on the screen. Folding, for
  7913. // example, can cause multiple logical lines to appear on the same
  7914. // visual line. This finds the start of the visual line that the
  7915. // given line is part of (usually that is the line itself).
  7916. function visualLine(line) {
  7917. var merged;
  7918. while (merged = collapsedSpanAtStart(line))
  7919. line = merged.find(-1, true).line;
  7920. return line;
  7921. }
  7922. // Returns an array of logical lines that continue the visual line
  7923. // started by the argument, or undefined if there are no such lines.
  7924. function visualLineContinued(line) {
  7925. var merged, lines;
  7926. while (merged = collapsedSpanAtEnd(line)) {
  7927. line = merged.find(1, true).line;
  7928. (lines || (lines = [])).push(line);
  7929. }
  7930. return lines;
  7931. }
  7932. // Get the line number of the start of the visual line that the
  7933. // given line number is part of.
  7934. function visualLineNo(doc, lineN) {
  7935. var line = getLine(doc, lineN), vis = visualLine(line);
  7936. if (line == vis) return lineN;
  7937. return lineNo(vis);
  7938. }
  7939. // Get the line number of the start of the next visual line after
  7940. // the given line.
  7941. function visualLineEndNo(doc, lineN) {
  7942. if (lineN > doc.lastLine()) return lineN;
  7943. var line = getLine(doc, lineN), merged;
  7944. if (!lineIsHidden(doc, line)) return lineN;
  7945. while (merged = collapsedSpanAtEnd(line))
  7946. line = merged.find(1, true).line;
  7947. return lineNo(line) + 1;
  7948. }
  7949. // Compute whether a line is hidden. Lines count as hidden when they
  7950. // are part of a visual line that starts with another line, or when
  7951. // they are entirely covered by collapsed, non-widget span.
  7952. function lineIsHidden(doc, line) {
  7953. var sps = sawCollapsedSpans && line.markedSpans;
  7954. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  7955. sp = sps[i];
  7956. if (!sp.marker.collapsed) continue;
  7957. if (sp.from == null) return true;
  7958. if (sp.marker.widgetNode) continue;
  7959. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  7960. return true;
  7961. }
  7962. }
  7963. function lineIsHiddenInner(doc, line, span) {
  7964. if (span.to == null) {
  7965. var end = span.marker.find(1, true);
  7966. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  7967. }
  7968. if (span.marker.inclusiveRight && span.to == line.text.length)
  7969. return true;
  7970. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  7971. sp = line.markedSpans[i];
  7972. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  7973. (sp.to == null || sp.to != span.from) &&
  7974. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  7975. lineIsHiddenInner(doc, line, sp)) return true;
  7976. }
  7977. }
  7978. // LINE WIDGETS
  7979. // Line widgets are block elements displayed above or below a line.
  7980. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  7981. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  7982. this[opt] = options[opt];
  7983. this.doc = doc;
  7984. this.node = node;
  7985. };
  7986. eventMixin(LineWidget);
  7987. function adjustScrollWhenAboveVisible(cm, line, diff) {
  7988. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  7989. addToScrollPos(cm, null, diff);
  7990. }
  7991. LineWidget.prototype.clear = function() {
  7992. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  7993. if (no == null || !ws) return;
  7994. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  7995. if (!ws.length) line.widgets = null;
  7996. var height = widgetHeight(this);
  7997. updateLineHeight(line, Math.max(0, line.height - height));
  7998. if (cm) runInOp(cm, function() {
  7999. adjustScrollWhenAboveVisible(cm, line, -height);
  8000. regLineChange(cm, no, "widget");
  8001. });
  8002. };
  8003. LineWidget.prototype.changed = function() {
  8004. var oldH = this.height, cm = this.doc.cm, line = this.line;
  8005. this.height = null;
  8006. var diff = widgetHeight(this) - oldH;
  8007. if (!diff) return;
  8008. updateLineHeight(line, line.height + diff);
  8009. if (cm) runInOp(cm, function() {
  8010. cm.curOp.forceUpdate = true;
  8011. adjustScrollWhenAboveVisible(cm, line, diff);
  8012. });
  8013. };
  8014. function widgetHeight(widget) {
  8015. if (widget.height != null) return widget.height;
  8016. var cm = widget.doc.cm;
  8017. if (!cm) return 0;
  8018. if (!contains(document.body, widget.node)) {
  8019. var parentStyle = "position: relative;";
  8020. if (widget.coverGutter)
  8021. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  8022. if (widget.noHScroll)
  8023. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  8024. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  8025. }
  8026. return widget.height = widget.node.parentNode.offsetHeight;
  8027. }
  8028. function addLineWidget(doc, handle, node, options) {
  8029. var widget = new LineWidget(doc, node, options);
  8030. var cm = doc.cm;
  8031. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  8032. changeLine(doc, handle, "widget", function(line) {
  8033. var widgets = line.widgets || (line.widgets = []);
  8034. if (widget.insertAt == null) widgets.push(widget);
  8035. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  8036. widget.line = line;
  8037. if (cm && !lineIsHidden(doc, line)) {
  8038. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  8039. updateLineHeight(line, line.height + widgetHeight(widget));
  8040. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  8041. cm.curOp.forceUpdate = true;
  8042. }
  8043. return true;
  8044. });
  8045. return widget;
  8046. }
  8047. // LINE DATA STRUCTURE
  8048. // Line objects. These hold state related to a line, including
  8049. // highlighting info (the styles array).
  8050. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  8051. this.text = text;
  8052. attachMarkedSpans(this, markedSpans);
  8053. this.height = estimateHeight ? estimateHeight(this) : 1;
  8054. };
  8055. eventMixin(Line);
  8056. Line.prototype.lineNo = function() { return lineNo(this); };
  8057. // Change the content (text, markers) of a line. Automatically
  8058. // invalidates cached information and tries to re-estimate the
  8059. // line's height.
  8060. function updateLine(line, text, markedSpans, estimateHeight) {
  8061. line.text = text;
  8062. if (line.stateAfter) line.stateAfter = null;
  8063. if (line.styles) line.styles = null;
  8064. if (line.order != null) line.order = null;
  8065. detachMarkedSpans(line);
  8066. attachMarkedSpans(line, markedSpans);
  8067. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  8068. if (estHeight != line.height) updateLineHeight(line, estHeight);
  8069. }
  8070. // Detach a line from the document tree and its markers.
  8071. function cleanUpLine(line) {
  8072. line.parent = null;
  8073. detachMarkedSpans(line);
  8074. }
  8075. function extractLineClasses(type, output) {
  8076. if (type) for (;;) {
  8077. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  8078. if (!lineClass) break;
  8079. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  8080. var prop = lineClass[1] ? "bgClass" : "textClass";
  8081. if (output[prop] == null)
  8082. output[prop] = lineClass[2];
  8083. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  8084. output[prop] += " " + lineClass[2];
  8085. }
  8086. return type;
  8087. }
  8088. function callBlankLine(mode, state) {
  8089. if (mode.blankLine) return mode.blankLine(state);
  8090. if (!mode.innerMode) return;
  8091. var inner = CodeMirror.innerMode(mode, state);
  8092. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  8093. }
  8094. function readToken(mode, stream, state, inner) {
  8095. for (var i = 0; i < 10; i++) {
  8096. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  8097. var style = mode.token(stream, state);
  8098. if (stream.pos > stream.start) return style;
  8099. }
  8100. throw new Error("Mode " + mode.name + " failed to advance stream.");
  8101. }
  8102. // Utility for getTokenAt and getLineTokens
  8103. function takeToken(cm, pos, precise, asArray) {
  8104. function getObj(copy) {
  8105. return {start: stream.start, end: stream.pos,
  8106. string: stream.current(),
  8107. type: style || null,
  8108. state: copy ? copyState(doc.mode, state) : state};
  8109. }
  8110. var doc = cm.doc, mode = doc.mode, style;
  8111. pos = clipPos(doc, pos);
  8112. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  8113. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  8114. if (asArray) tokens = [];
  8115. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  8116. stream.start = stream.pos;
  8117. style = readToken(mode, stream, state);
  8118. if (asArray) tokens.push(getObj(true));
  8119. }
  8120. return asArray ? tokens : getObj();
  8121. }
  8122. // Run the given mode's parser over a line, calling f for each token.
  8123. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  8124. var flattenSpans = mode.flattenSpans;
  8125. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  8126. var curStart = 0, curStyle = null;
  8127. var stream = new StringStream(text, cm.options.tabSize), style;
  8128. var inner = cm.options.addModeClass && [null];
  8129. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  8130. while (!stream.eol()) {
  8131. if (stream.pos > cm.options.maxHighlightLength) {
  8132. flattenSpans = false;
  8133. if (forceToEnd) processLine(cm, text, state, stream.pos);
  8134. stream.pos = text.length;
  8135. style = null;
  8136. } else {
  8137. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  8138. }
  8139. if (inner) {
  8140. var mName = inner[0].name;
  8141. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  8142. }
  8143. if (!flattenSpans || curStyle != style) {
  8144. while (curStart < stream.start) {
  8145. curStart = Math.min(stream.start, curStart + 50000);
  8146. f(curStart, curStyle);
  8147. }
  8148. curStyle = style;
  8149. }
  8150. stream.start = stream.pos;
  8151. }
  8152. while (curStart < stream.pos) {
  8153. // Webkit seems to refuse to render text nodes longer than 57444 characters
  8154. var pos = Math.min(stream.pos, curStart + 50000);
  8155. f(pos, curStyle);
  8156. curStart = pos;
  8157. }
  8158. }
  8159. // Compute a style array (an array starting with a mode generation
  8160. // -- for invalidation -- followed by pairs of end positions and
  8161. // style strings), which is used to highlight the tokens on the
  8162. // line.
  8163. function highlightLine(cm, line, state, forceToEnd) {
  8164. // A styles array always starts with a number identifying the
  8165. // mode/overlays that it is based on (for easy invalidation).
  8166. var st = [cm.state.modeGen], lineClasses = {};
  8167. // Compute the base array of styles
  8168. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  8169. st.push(end, style);
  8170. }, lineClasses, forceToEnd);
  8171. // Run overlays, adjust style array.
  8172. for (var o = 0; o < cm.state.overlays.length; ++o) {
  8173. var overlay = cm.state.overlays[o], i = 1, at = 0;
  8174. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  8175. var start = i;
  8176. // Ensure there's a token end at the current position, and that i points at it
  8177. while (at < end) {
  8178. var i_end = st[i];
  8179. if (i_end > end)
  8180. st.splice(i, 1, end, st[i+1], i_end);
  8181. i += 2;
  8182. at = Math.min(end, i_end);
  8183. }
  8184. if (!style) return;
  8185. if (overlay.opaque) {
  8186. st.splice(start, i - start, end, "cm-overlay " + style);
  8187. i = start + 2;
  8188. } else {
  8189. for (; start < i; start += 2) {
  8190. var cur = st[start+1];
  8191. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  8192. }
  8193. }
  8194. }, lineClasses);
  8195. }
  8196. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  8197. }
  8198. function getLineStyles(cm, line, updateFrontier) {
  8199. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  8200. var state = getStateBefore(cm, lineNo(line));
  8201. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  8202. line.stateAfter = state;
  8203. line.styles = result.styles;
  8204. if (result.classes) line.styleClasses = result.classes;
  8205. else if (line.styleClasses) line.styleClasses = null;
  8206. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  8207. }
  8208. return line.styles;
  8209. }
  8210. // Lightweight form of highlight -- proceed over this line and
  8211. // update state, but don't save a style array. Used for lines that
  8212. // aren't currently visible.
  8213. function processLine(cm, text, state, startAt) {
  8214. var mode = cm.doc.mode;
  8215. var stream = new StringStream(text, cm.options.tabSize);
  8216. stream.start = stream.pos = startAt || 0;
  8217. if (text == "") callBlankLine(mode, state);
  8218. while (!stream.eol()) {
  8219. readToken(mode, stream, state);
  8220. stream.start = stream.pos;
  8221. }
  8222. }
  8223. // Convert a style as returned by a mode (either null, or a string
  8224. // containing one or more styles) to a CSS style. This is cached,
  8225. // and also looks for line-wide styles.
  8226. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  8227. function interpretTokenStyle(style, options) {
  8228. if (!style || /^\s*$/.test(style)) return null;
  8229. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  8230. return cache[style] ||
  8231. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  8232. }
  8233. // Render the DOM representation of the text of a line. Also builds
  8234. // up a 'line map', which points at the DOM nodes that represent
  8235. // specific stretches of text, and is used by the measuring code.
  8236. // The returned object contains the DOM node, this map, and
  8237. // information about line-wide styles that were set by the mode.
  8238. function buildLineContent(cm, lineView) {
  8239. // The padding-right forces the element to have a 'border', which
  8240. // is needed on Webkit to be able to get line-level bounding
  8241. // rectangles for it (in measureChar).
  8242. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  8243. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  8244. col: 0, pos: 0, cm: cm,
  8245. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  8246. lineView.measure = {};
  8247. // Iterate over the logical lines that make up this visual line.
  8248. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  8249. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  8250. builder.pos = 0;
  8251. builder.addToken = buildToken;
  8252. // Optionally wire in some hacks into the token-rendering
  8253. // algorithm, to deal with browser quirks.
  8254. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  8255. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  8256. builder.map = [];
  8257. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  8258. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  8259. if (line.styleClasses) {
  8260. if (line.styleClasses.bgClass)
  8261. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  8262. if (line.styleClasses.textClass)
  8263. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  8264. }
  8265. // Ensure at least a single node is present, for measuring.
  8266. if (builder.map.length == 0)
  8267. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  8268. // Store the map and a cache object for the current logical line
  8269. if (i == 0) {
  8270. lineView.measure.map = builder.map;
  8271. lineView.measure.cache = {};
  8272. } else {
  8273. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  8274. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  8275. }
  8276. }
  8277. // See issue #2901
  8278. if (webkit) {
  8279. var last = builder.content.lastChild
  8280. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  8281. builder.content.className = "cm-tab-wrap-hack";
  8282. }
  8283. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  8284. if (builder.pre.className)
  8285. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  8286. return builder;
  8287. }
  8288. function defaultSpecialCharPlaceholder(ch) {
  8289. var token = elt("span", "\u2022", "cm-invalidchar");
  8290. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  8291. token.setAttribute("aria-label", token.title);
  8292. return token;
  8293. }
  8294. // Build up the DOM representation for a single token, and add it to
  8295. // the line map. Takes care to render special characters separately.
  8296. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  8297. if (!text) return;
  8298. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  8299. var special = builder.cm.state.specialChars, mustWrap = false;
  8300. if (!special.test(text)) {
  8301. builder.col += text.length;
  8302. var content = document.createTextNode(displayText);
  8303. builder.map.push(builder.pos, builder.pos + text.length, content);
  8304. if (ie && ie_version < 9) mustWrap = true;
  8305. builder.pos += text.length;
  8306. } else {
  8307. var content = document.createDocumentFragment(), pos = 0;
  8308. while (true) {
  8309. special.lastIndex = pos;
  8310. var m = special.exec(text);
  8311. var skipped = m ? m.index - pos : text.length - pos;
  8312. if (skipped) {
  8313. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  8314. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  8315. else content.appendChild(txt);
  8316. builder.map.push(builder.pos, builder.pos + skipped, txt);
  8317. builder.col += skipped;
  8318. builder.pos += skipped;
  8319. }
  8320. if (!m) break;
  8321. pos += skipped + 1;
  8322. if (m[0] == "\t") {
  8323. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  8324. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  8325. txt.setAttribute("role", "presentation");
  8326. txt.setAttribute("cm-text", "\t");
  8327. builder.col += tabWidth;
  8328. } else if (m[0] == "\r" || m[0] == "\n") {
  8329. var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  8330. txt.setAttribute("cm-text", m[0]);
  8331. builder.col += 1;
  8332. } else {
  8333. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  8334. txt.setAttribute("cm-text", m[0]);
  8335. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  8336. else content.appendChild(txt);
  8337. builder.col += 1;
  8338. }
  8339. builder.map.push(builder.pos, builder.pos + 1, txt);
  8340. builder.pos++;
  8341. }
  8342. }
  8343. if (style || startStyle || endStyle || mustWrap || css) {
  8344. var fullStyle = style || "";
  8345. if (startStyle) fullStyle += startStyle;
  8346. if (endStyle) fullStyle += endStyle;
  8347. var token = elt("span", [content], fullStyle, css);
  8348. if (title) token.title = title;
  8349. return builder.content.appendChild(token);
  8350. }
  8351. builder.content.appendChild(content);
  8352. }
  8353. function splitSpaces(old) {
  8354. var out = " ";
  8355. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  8356. out += " ";
  8357. return out;
  8358. }
  8359. // Work around nonsense dimensions being reported for stretches of
  8360. // right-to-left text.
  8361. function buildTokenBadBidi(inner, order) {
  8362. return function(builder, text, style, startStyle, endStyle, title, css) {
  8363. style = style ? style + " cm-force-border" : "cm-force-border";
  8364. var start = builder.pos, end = start + text.length;
  8365. for (;;) {
  8366. // Find the part that overlaps with the start of this text
  8367. for (var i = 0; i < order.length; i++) {
  8368. var part = order[i];
  8369. if (part.to > start && part.from <= start) break;
  8370. }
  8371. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  8372. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  8373. startStyle = null;
  8374. text = text.slice(part.to - start);
  8375. start = part.to;
  8376. }
  8377. };
  8378. }
  8379. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  8380. var widget = !ignoreWidget && marker.widgetNode;
  8381. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  8382. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  8383. if (!widget)
  8384. widget = builder.content.appendChild(document.createElement("span"));
  8385. widget.setAttribute("cm-marker", marker.id);
  8386. }
  8387. if (widget) {
  8388. builder.cm.display.input.setUneditable(widget);
  8389. builder.content.appendChild(widget);
  8390. }
  8391. builder.pos += size;
  8392. }
  8393. // Outputs a number of spans to make up a line, taking highlighting
  8394. // and marked text into account.
  8395. function insertLineContent(line, builder, styles) {
  8396. var spans = line.markedSpans, allText = line.text, at = 0;
  8397. if (!spans) {
  8398. for (var i = 1; i < styles.length; i+=2)
  8399. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  8400. return;
  8401. }
  8402. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  8403. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  8404. for (;;) {
  8405. if (nextChange == pos) { // Update current marker set
  8406. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  8407. collapsed = null; nextChange = Infinity;
  8408. var foundBookmarks = [], endStyles
  8409. for (var j = 0; j < spans.length; ++j) {
  8410. var sp = spans[j], m = sp.marker;
  8411. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  8412. foundBookmarks.push(m);
  8413. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  8414. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  8415. nextChange = sp.to;
  8416. spanEndStyle = "";
  8417. }
  8418. if (m.className) spanStyle += " " + m.className;
  8419. if (m.css) css = (css ? css + ";" : "") + m.css;
  8420. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  8421. if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  8422. if (m.title && !title) title = m.title;
  8423. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  8424. collapsed = sp;
  8425. } else if (sp.from > pos && nextChange > sp.from) {
  8426. nextChange = sp.from;
  8427. }
  8428. }
  8429. if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
  8430. if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  8431. if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
  8432. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  8433. if (collapsed && (collapsed.from || 0) == pos) {
  8434. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  8435. collapsed.marker, collapsed.from == null);
  8436. if (collapsed.to == null) return;
  8437. if (collapsed.to == pos) collapsed = false;
  8438. }
  8439. }
  8440. if (pos >= len) break;
  8441. var upto = Math.min(len, nextChange);
  8442. while (true) {
  8443. if (text) {
  8444. var end = pos + text.length;
  8445. if (!collapsed) {
  8446. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  8447. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  8448. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  8449. }
  8450. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  8451. pos = end;
  8452. spanStartStyle = "";
  8453. }
  8454. text = allText.slice(at, at = styles[i++]);
  8455. style = interpretTokenStyle(styles[i++], builder.cm.options);
  8456. }
  8457. }
  8458. }
  8459. // DOCUMENT DATA STRUCTURE
  8460. // By default, updates that start and end at the beginning of a line
  8461. // are treated specially, in order to make the association of line
  8462. // widgets and marker elements with the text behave more intuitive.
  8463. function isWholeLineUpdate(doc, change) {
  8464. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  8465. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  8466. }
  8467. // Perform a change on the document data structure.
  8468. function updateDoc(doc, change, markedSpans, estimateHeight) {
  8469. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  8470. function update(line, text, spans) {
  8471. updateLine(line, text, spans, estimateHeight);
  8472. signalLater(line, "change", line, change);
  8473. }
  8474. function linesFor(start, end) {
  8475. for (var i = start, result = []; i < end; ++i)
  8476. result.push(new Line(text[i], spansFor(i), estimateHeight));
  8477. return result;
  8478. }
  8479. var from = change.from, to = change.to, text = change.text;
  8480. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  8481. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  8482. // Adjust the line structure
  8483. if (change.full) {
  8484. doc.insert(0, linesFor(0, text.length));
  8485. doc.remove(text.length, doc.size - text.length);
  8486. } else if (isWholeLineUpdate(doc, change)) {
  8487. // This is a whole-line replace. Treated specially to make
  8488. // sure line objects move the way they are supposed to.
  8489. var added = linesFor(0, text.length - 1);
  8490. update(lastLine, lastLine.text, lastSpans);
  8491. if (nlines) doc.remove(from.line, nlines);
  8492. if (added.length) doc.insert(from.line, added);
  8493. } else if (firstLine == lastLine) {
  8494. if (text.length == 1) {
  8495. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  8496. } else {
  8497. var added = linesFor(1, text.length - 1);
  8498. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  8499. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  8500. doc.insert(from.line + 1, added);
  8501. }
  8502. } else if (text.length == 1) {
  8503. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  8504. doc.remove(from.line + 1, nlines);
  8505. } else {
  8506. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  8507. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  8508. var added = linesFor(1, text.length - 1);
  8509. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  8510. doc.insert(from.line + 1, added);
  8511. }
  8512. signalLater(doc, "change", doc, change);
  8513. }
  8514. // The document is represented as a BTree consisting of leaves, with
  8515. // chunk of lines in them, and branches, with up to ten leaves or
  8516. // other branch nodes below them. The top node is always a branch
  8517. // node, and is the document object itself (meaning it has
  8518. // additional methods and properties).
  8519. //
  8520. // All nodes have parent links. The tree is used both to go from
  8521. // line numbers to line objects, and to go from objects to numbers.
  8522. // It also indexes by height, and is used to convert between height
  8523. // and line object, and to find the total height of the document.
  8524. //
  8525. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  8526. function LeafChunk(lines) {
  8527. this.lines = lines;
  8528. this.parent = null;
  8529. for (var i = 0, height = 0; i < lines.length; ++i) {
  8530. lines[i].parent = this;
  8531. height += lines[i].height;
  8532. }
  8533. this.height = height;
  8534. }
  8535. LeafChunk.prototype = {
  8536. chunkSize: function() { return this.lines.length; },
  8537. // Remove the n lines at offset 'at'.
  8538. removeInner: function(at, n) {
  8539. for (var i = at, e = at + n; i < e; ++i) {
  8540. var line = this.lines[i];
  8541. this.height -= line.height;
  8542. cleanUpLine(line);
  8543. signalLater(line, "delete");
  8544. }
  8545. this.lines.splice(at, n);
  8546. },
  8547. // Helper used to collapse a small branch into a single leaf.
  8548. collapse: function(lines) {
  8549. lines.push.apply(lines, this.lines);
  8550. },
  8551. // Insert the given array of lines at offset 'at', count them as
  8552. // having the given height.
  8553. insertInner: function(at, lines, height) {
  8554. this.height += height;
  8555. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  8556. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  8557. },
  8558. // Used to iterate over a part of the tree.
  8559. iterN: function(at, n, op) {
  8560. for (var e = at + n; at < e; ++at)
  8561. if (op(this.lines[at])) return true;
  8562. }
  8563. };
  8564. function BranchChunk(children) {
  8565. this.children = children;
  8566. var size = 0, height = 0;
  8567. for (var i = 0; i < children.length; ++i) {
  8568. var ch = children[i];
  8569. size += ch.chunkSize(); height += ch.height;
  8570. ch.parent = this;
  8571. }
  8572. this.size = size;
  8573. this.height = height;
  8574. this.parent = null;
  8575. }
  8576. BranchChunk.prototype = {
  8577. chunkSize: function() { return this.size; },
  8578. removeInner: function(at, n) {
  8579. this.size -= n;
  8580. for (var i = 0; i < this.children.length; ++i) {
  8581. var child = this.children[i], sz = child.chunkSize();
  8582. if (at < sz) {
  8583. var rm = Math.min(n, sz - at), oldHeight = child.height;
  8584. child.removeInner(at, rm);
  8585. this.height -= oldHeight - child.height;
  8586. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  8587. if ((n -= rm) == 0) break;
  8588. at = 0;
  8589. } else at -= sz;
  8590. }
  8591. // If the result is smaller than 25 lines, ensure that it is a
  8592. // single leaf node.
  8593. if (this.size - n < 25 &&
  8594. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  8595. var lines = [];
  8596. this.collapse(lines);
  8597. this.children = [new LeafChunk(lines)];
  8598. this.children[0].parent = this;
  8599. }
  8600. },
  8601. collapse: function(lines) {
  8602. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  8603. },
  8604. insertInner: function(at, lines, height) {
  8605. this.size += lines.length;
  8606. this.height += height;
  8607. for (var i = 0; i < this.children.length; ++i) {
  8608. var child = this.children[i], sz = child.chunkSize();
  8609. if (at <= sz) {
  8610. child.insertInner(at, lines, height);
  8611. if (child.lines && child.lines.length > 50) {
  8612. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  8613. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  8614. var remaining = child.lines.length % 25 + 25
  8615. for (var pos = remaining; pos < child.lines.length;) {
  8616. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  8617. child.height -= leaf.height;
  8618. this.children.splice(++i, 0, leaf);
  8619. leaf.parent = this;
  8620. }
  8621. child.lines = child.lines.slice(0, remaining);
  8622. this.maybeSpill();
  8623. }
  8624. break;
  8625. }
  8626. at -= sz;
  8627. }
  8628. },
  8629. // When a node has grown, check whether it should be split.
  8630. maybeSpill: function() {
  8631. if (this.children.length <= 10) return;
  8632. var me = this;
  8633. do {
  8634. var spilled = me.children.splice(me.children.length - 5, 5);
  8635. var sibling = new BranchChunk(spilled);
  8636. if (!me.parent) { // Become the parent node
  8637. var copy = new BranchChunk(me.children);
  8638. copy.parent = me;
  8639. me.children = [copy, sibling];
  8640. me = copy;
  8641. } else {
  8642. me.size -= sibling.size;
  8643. me.height -= sibling.height;
  8644. var myIndex = indexOf(me.parent.children, me);
  8645. me.parent.children.splice(myIndex + 1, 0, sibling);
  8646. }
  8647. sibling.parent = me.parent;
  8648. } while (me.children.length > 10);
  8649. me.parent.maybeSpill();
  8650. },
  8651. iterN: function(at, n, op) {
  8652. for (var i = 0; i < this.children.length; ++i) {
  8653. var child = this.children[i], sz = child.chunkSize();
  8654. if (at < sz) {
  8655. var used = Math.min(n, sz - at);
  8656. if (child.iterN(at, used, op)) return true;
  8657. if ((n -= used) == 0) break;
  8658. at = 0;
  8659. } else at -= sz;
  8660. }
  8661. }
  8662. };
  8663. var nextDocId = 0;
  8664. var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
  8665. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
  8666. if (firstLine == null) firstLine = 0;
  8667. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  8668. this.first = firstLine;
  8669. this.scrollTop = this.scrollLeft = 0;
  8670. this.cantEdit = false;
  8671. this.cleanGeneration = 1;
  8672. this.frontier = firstLine;
  8673. var start = Pos(firstLine, 0);
  8674. this.sel = simpleSelection(start);
  8675. this.history = new History(null);
  8676. this.id = ++nextDocId;
  8677. this.modeOption = mode;
  8678. this.lineSep = lineSep;
  8679. this.extend = false;
  8680. if (typeof text == "string") text = this.splitLines(text);
  8681. updateDoc(this, {from: start, to: start, text: text});
  8682. setSelection(this, simpleSelection(start), sel_dontScroll);
  8683. };
  8684. Doc.prototype = createObj(BranchChunk.prototype, {
  8685. constructor: Doc,
  8686. // Iterate over the document. Supports two forms -- with only one
  8687. // argument, it calls that for each line in the document. With
  8688. // three, it iterates over the range given by the first two (with
  8689. // the second being non-inclusive).
  8690. iter: function(from, to, op) {
  8691. if (op) this.iterN(from - this.first, to - from, op);
  8692. else this.iterN(this.first, this.first + this.size, from);
  8693. },
  8694. // Non-public interface for adding and removing lines.
  8695. insert: function(at, lines) {
  8696. var height = 0;
  8697. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  8698. this.insertInner(at - this.first, lines, height);
  8699. },
  8700. remove: function(at, n) { this.removeInner(at - this.first, n); },
  8701. // From here, the methods are part of the public interface. Most
  8702. // are also available from CodeMirror (editor) instances.
  8703. getValue: function(lineSep) {
  8704. var lines = getLines(this, this.first, this.first + this.size);
  8705. if (lineSep === false) return lines;
  8706. return lines.join(lineSep || this.lineSeparator());
  8707. },
  8708. setValue: docMethodOp(function(code) {
  8709. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  8710. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  8711. text: this.splitLines(code), origin: "setValue", full: true}, true);
  8712. setSelection(this, simpleSelection(top));
  8713. }),
  8714. replaceRange: function(code, from, to, origin) {
  8715. from = clipPos(this, from);
  8716. to = to ? clipPos(this, to) : from;
  8717. replaceRange(this, code, from, to, origin);
  8718. },
  8719. getRange: function(from, to, lineSep) {
  8720. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  8721. if (lineSep === false) return lines;
  8722. return lines.join(lineSep || this.lineSeparator());
  8723. },
  8724. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  8725. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  8726. getLineNumber: function(line) {return lineNo(line);},
  8727. getLineHandleVisualStart: function(line) {
  8728. if (typeof line == "number") line = getLine(this, line);
  8729. return visualLine(line);
  8730. },
  8731. lineCount: function() {return this.size;},
  8732. firstLine: function() {return this.first;},
  8733. lastLine: function() {return this.first + this.size - 1;},
  8734. clipPos: function(pos) {return clipPos(this, pos);},
  8735. getCursor: function(start) {
  8736. var range = this.sel.primary(), pos;
  8737. if (start == null || start == "head") pos = range.head;
  8738. else if (start == "anchor") pos = range.anchor;
  8739. else if (start == "end" || start == "to" || start === false) pos = range.to();
  8740. else pos = range.from();
  8741. return pos;
  8742. },
  8743. listSelections: function() { return this.sel.ranges; },
  8744. somethingSelected: function() {return this.sel.somethingSelected();},
  8745. setCursor: docMethodOp(function(line, ch, options) {
  8746. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  8747. }),
  8748. setSelection: docMethodOp(function(anchor, head, options) {
  8749. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  8750. }),
  8751. extendSelection: docMethodOp(function(head, other, options) {
  8752. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  8753. }),
  8754. extendSelections: docMethodOp(function(heads, options) {
  8755. extendSelections(this, clipPosArray(this, heads), options);
  8756. }),
  8757. extendSelectionsBy: docMethodOp(function(f, options) {
  8758. var heads = map(this.sel.ranges, f);
  8759. extendSelections(this, clipPosArray(this, heads), options);
  8760. }),
  8761. setSelections: docMethodOp(function(ranges, primary, options) {
  8762. if (!ranges.length) return;
  8763. for (var i = 0, out = []; i < ranges.length; i++)
  8764. out[i] = new Range(clipPos(this, ranges[i].anchor),
  8765. clipPos(this, ranges[i].head));
  8766. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  8767. setSelection(this, normalizeSelection(out, primary), options);
  8768. }),
  8769. addSelection: docMethodOp(function(anchor, head, options) {
  8770. var ranges = this.sel.ranges.slice(0);
  8771. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  8772. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  8773. }),
  8774. getSelection: function(lineSep) {
  8775. var ranges = this.sel.ranges, lines;
  8776. for (var i = 0; i < ranges.length; i++) {
  8777. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  8778. lines = lines ? lines.concat(sel) : sel;
  8779. }
  8780. if (lineSep === false) return lines;
  8781. else return lines.join(lineSep || this.lineSeparator());
  8782. },
  8783. getSelections: function(lineSep) {
  8784. var parts = [], ranges = this.sel.ranges;
  8785. for (var i = 0; i < ranges.length; i++) {
  8786. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  8787. if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
  8788. parts[i] = sel;
  8789. }
  8790. return parts;
  8791. },
  8792. replaceSelection: function(code, collapse, origin) {
  8793. var dup = [];
  8794. for (var i = 0; i < this.sel.ranges.length; i++)
  8795. dup[i] = code;
  8796. this.replaceSelections(dup, collapse, origin || "+input");
  8797. },
  8798. replaceSelections: docMethodOp(function(code, collapse, origin) {
  8799. var changes = [], sel = this.sel;
  8800. for (var i = 0; i < sel.ranges.length; i++) {
  8801. var range = sel.ranges[i];
  8802. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  8803. }
  8804. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  8805. for (var i = changes.length - 1; i >= 0; i--)
  8806. makeChange(this, changes[i]);
  8807. if (newSel) setSelectionReplaceHistory(this, newSel);
  8808. else if (this.cm) ensureCursorVisible(this.cm);
  8809. }),
  8810. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  8811. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  8812. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  8813. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  8814. setExtending: function(val) {this.extend = val;},
  8815. getExtending: function() {return this.extend;},
  8816. historySize: function() {
  8817. var hist = this.history, done = 0, undone = 0;
  8818. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  8819. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  8820. return {undo: done, redo: undone};
  8821. },
  8822. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  8823. markClean: function() {
  8824. this.cleanGeneration = this.changeGeneration(true);
  8825. },
  8826. changeGeneration: function(forceSplit) {
  8827. if (forceSplit)
  8828. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  8829. return this.history.generation;
  8830. },
  8831. isClean: function (gen) {
  8832. return this.history.generation == (gen || this.cleanGeneration);
  8833. },
  8834. getHistory: function() {
  8835. return {done: copyHistoryArray(this.history.done),
  8836. undone: copyHistoryArray(this.history.undone)};
  8837. },
  8838. setHistory: function(histData) {
  8839. var hist = this.history = new History(this.history.maxGeneration);
  8840. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  8841. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  8842. },
  8843. addLineClass: docMethodOp(function(handle, where, cls) {
  8844. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  8845. var prop = where == "text" ? "textClass"
  8846. : where == "background" ? "bgClass"
  8847. : where == "gutter" ? "gutterClass" : "wrapClass";
  8848. if (!line[prop]) line[prop] = cls;
  8849. else if (classTest(cls).test(line[prop])) return false;
  8850. else line[prop] += " " + cls;
  8851. return true;
  8852. });
  8853. }),
  8854. removeLineClass: docMethodOp(function(handle, where, cls) {
  8855. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  8856. var prop = where == "text" ? "textClass"
  8857. : where == "background" ? "bgClass"
  8858. : where == "gutter" ? "gutterClass" : "wrapClass";
  8859. var cur = line[prop];
  8860. if (!cur) return false;
  8861. else if (cls == null) line[prop] = null;
  8862. else {
  8863. var found = cur.match(classTest(cls));
  8864. if (!found) return false;
  8865. var end = found.index + found[0].length;
  8866. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  8867. }
  8868. return true;
  8869. });
  8870. }),
  8871. addLineWidget: docMethodOp(function(handle, node, options) {
  8872. return addLineWidget(this, handle, node, options);
  8873. }),
  8874. removeLineWidget: function(widget) { widget.clear(); },
  8875. markText: function(from, to, options) {
  8876. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
  8877. },
  8878. setBookmark: function(pos, options) {
  8879. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  8880. insertLeft: options && options.insertLeft,
  8881. clearWhenEmpty: false, shared: options && options.shared,
  8882. handleMouseEvents: options && options.handleMouseEvents};
  8883. pos = clipPos(this, pos);
  8884. return markText(this, pos, pos, realOpts, "bookmark");
  8885. },
  8886. findMarksAt: function(pos) {
  8887. pos = clipPos(this, pos);
  8888. var markers = [], spans = getLine(this, pos.line).markedSpans;
  8889. if (spans) for (var i = 0; i < spans.length; ++i) {
  8890. var span = spans[i];
  8891. if ((span.from == null || span.from <= pos.ch) &&
  8892. (span.to == null || span.to >= pos.ch))
  8893. markers.push(span.marker.parent || span.marker);
  8894. }
  8895. return markers;
  8896. },
  8897. findMarks: function(from, to, filter) {
  8898. from = clipPos(this, from); to = clipPos(this, to);
  8899. var found = [], lineNo = from.line;
  8900. this.iter(from.line, to.line + 1, function(line) {
  8901. var spans = line.markedSpans;
  8902. if (spans) for (var i = 0; i < spans.length; i++) {
  8903. var span = spans[i];
  8904. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  8905. span.from == null && lineNo != from.line ||
  8906. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  8907. (!filter || filter(span.marker)))
  8908. found.push(span.marker.parent || span.marker);
  8909. }
  8910. ++lineNo;
  8911. });
  8912. return found;
  8913. },
  8914. getAllMarks: function() {
  8915. var markers = [];
  8916. this.iter(function(line) {
  8917. var sps = line.markedSpans;
  8918. if (sps) for (var i = 0; i < sps.length; ++i)
  8919. if (sps[i].from != null) markers.push(sps[i].marker);
  8920. });
  8921. return markers;
  8922. },
  8923. posFromIndex: function(off) {
  8924. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  8925. this.iter(function(line) {
  8926. var sz = line.text.length + sepSize;
  8927. if (sz > off) { ch = off; return true; }
  8928. off -= sz;
  8929. ++lineNo;
  8930. });
  8931. return clipPos(this, Pos(lineNo, ch));
  8932. },
  8933. indexFromPos: function (coords) {
  8934. coords = clipPos(this, coords);
  8935. var index = coords.ch;
  8936. if (coords.line < this.first || coords.ch < 0) return 0;
  8937. var sepSize = this.lineSeparator().length;
  8938. this.iter(this.first, coords.line, function (line) {
  8939. index += line.text.length + sepSize;
  8940. });
  8941. return index;
  8942. },
  8943. copy: function(copyHistory) {
  8944. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  8945. this.modeOption, this.first, this.lineSep);
  8946. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  8947. doc.sel = this.sel;
  8948. doc.extend = false;
  8949. if (copyHistory) {
  8950. doc.history.undoDepth = this.history.undoDepth;
  8951. doc.setHistory(this.getHistory());
  8952. }
  8953. return doc;
  8954. },
  8955. linkedDoc: function(options) {
  8956. if (!options) options = {};
  8957. var from = this.first, to = this.first + this.size;
  8958. if (options.from != null && options.from > from) from = options.from;
  8959. if (options.to != null && options.to < to) to = options.to;
  8960. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
  8961. if (options.sharedHist) copy.history = this.history;
  8962. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  8963. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  8964. copySharedMarkers(copy, findSharedMarkers(this));
  8965. return copy;
  8966. },
  8967. unlinkDoc: function(other) {
  8968. if (other instanceof CodeMirror) other = other.doc;
  8969. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  8970. var link = this.linked[i];
  8971. if (link.doc != other) continue;
  8972. this.linked.splice(i, 1);
  8973. other.unlinkDoc(this);
  8974. detachSharedMarkers(findSharedMarkers(this));
  8975. break;
  8976. }
  8977. // If the histories were shared, split them again
  8978. if (other.history == this.history) {
  8979. var splitIds = [other.id];
  8980. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  8981. other.history = new History(null);
  8982. other.history.done = copyHistoryArray(this.history.done, splitIds);
  8983. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  8984. }
  8985. },
  8986. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  8987. getMode: function() {return this.mode;},
  8988. getEditor: function() {return this.cm;},
  8989. splitLines: function(str) {
  8990. if (this.lineSep) return str.split(this.lineSep);
  8991. return splitLinesAuto(str);
  8992. },
  8993. lineSeparator: function() { return this.lineSep || "\n"; }
  8994. });
  8995. // Public alias.
  8996. Doc.prototype.eachLine = Doc.prototype.iter;
  8997. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8998. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8999. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  9000. CodeMirror.prototype[prop] = (function(method) {
  9001. return function() {return method.apply(this.doc, arguments);};
  9002. })(Doc.prototype[prop]);
  9003. eventMixin(Doc);
  9004. // Call f for all linked documents.
  9005. function linkedDocs(doc, f, sharedHistOnly) {
  9006. function propagate(doc, skip, sharedHist) {
  9007. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  9008. var rel = doc.linked[i];
  9009. if (rel.doc == skip) continue;
  9010. var shared = sharedHist && rel.sharedHist;
  9011. if (sharedHistOnly && !shared) continue;
  9012. f(rel.doc, shared);
  9013. propagate(rel.doc, doc, shared);
  9014. }
  9015. }
  9016. propagate(doc, null, true);
  9017. }
  9018. // Attach a document to an editor.
  9019. function attachDoc(cm, doc) {
  9020. if (doc.cm) throw new Error("This document is already in use.");
  9021. cm.doc = doc;
  9022. doc.cm = cm;
  9023. estimateLineHeights(cm);
  9024. loadMode(cm);
  9025. if (!cm.options.lineWrapping) findMaxLine(cm);
  9026. cm.options.mode = doc.modeOption;
  9027. regChange(cm);
  9028. }
  9029. // LINE UTILITIES
  9030. // Find the line object corresponding to the given line number.
  9031. function getLine(doc, n) {
  9032. n -= doc.first;
  9033. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  9034. for (var chunk = doc; !chunk.lines;) {
  9035. for (var i = 0;; ++i) {
  9036. var child = chunk.children[i], sz = child.chunkSize();
  9037. if (n < sz) { chunk = child; break; }
  9038. n -= sz;
  9039. }
  9040. }
  9041. return chunk.lines[n];
  9042. }
  9043. // Get the part of a document between two positions, as an array of
  9044. // strings.
  9045. function getBetween(doc, start, end) {
  9046. var out = [], n = start.line;
  9047. doc.iter(start.line, end.line + 1, function(line) {
  9048. var text = line.text;
  9049. if (n == end.line) text = text.slice(0, end.ch);
  9050. if (n == start.line) text = text.slice(start.ch);
  9051. out.push(text);
  9052. ++n;
  9053. });
  9054. return out;
  9055. }
  9056. // Get the lines between from and to, as array of strings.
  9057. function getLines(doc, from, to) {
  9058. var out = [];
  9059. doc.iter(from, to, function(line) { out.push(line.text); });
  9060. return out;
  9061. }
  9062. // Update the height of a line, propagating the height change
  9063. // upwards to parent nodes.
  9064. function updateLineHeight(line, height) {
  9065. var diff = height - line.height;
  9066. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  9067. }
  9068. // Given a line object, find its line number by walking up through
  9069. // its parent links.
  9070. function lineNo(line) {
  9071. if (line.parent == null) return null;
  9072. var cur = line.parent, no = indexOf(cur.lines, line);
  9073. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  9074. for (var i = 0;; ++i) {
  9075. if (chunk.children[i] == cur) break;
  9076. no += chunk.children[i].chunkSize();
  9077. }
  9078. }
  9079. return no + cur.first;
  9080. }
  9081. // Find the line at the given vertical position, using the height
  9082. // information in the document tree.
  9083. function lineAtHeight(chunk, h) {
  9084. var n = chunk.first;
  9085. outer: do {
  9086. for (var i = 0; i < chunk.children.length; ++i) {
  9087. var child = chunk.children[i], ch = child.height;
  9088. if (h < ch) { chunk = child; continue outer; }
  9089. h -= ch;
  9090. n += child.chunkSize();
  9091. }
  9092. return n;
  9093. } while (!chunk.lines);
  9094. for (var i = 0; i < chunk.lines.length; ++i) {
  9095. var line = chunk.lines[i], lh = line.height;
  9096. if (h < lh) break;
  9097. h -= lh;
  9098. }
  9099. return n + i;
  9100. }
  9101. // Find the height above the given line.
  9102. function heightAtLine(lineObj) {
  9103. lineObj = visualLine(lineObj);
  9104. var h = 0, chunk = lineObj.parent;
  9105. for (var i = 0; i < chunk.lines.length; ++i) {
  9106. var line = chunk.lines[i];
  9107. if (line == lineObj) break;
  9108. else h += line.height;
  9109. }
  9110. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  9111. for (var i = 0; i < p.children.length; ++i) {
  9112. var cur = p.children[i];
  9113. if (cur == chunk) break;
  9114. else h += cur.height;
  9115. }
  9116. }
  9117. return h;
  9118. }
  9119. // Get the bidi ordering for the given line (and cache it). Returns
  9120. // false for lines that are fully left-to-right, and an array of
  9121. // BidiSpan objects otherwise.
  9122. function getOrder(line) {
  9123. var order = line.order;
  9124. if (order == null) order = line.order = bidiOrdering(line.text);
  9125. return order;
  9126. }
  9127. // HISTORY
  9128. function History(startGen) {
  9129. // Arrays of change events and selections. Doing something adds an
  9130. // event to done and clears undo. Undoing moves events from done
  9131. // to undone, redoing moves them in the other direction.
  9132. this.done = []; this.undone = [];
  9133. this.undoDepth = Infinity;
  9134. // Used to track when changes can be merged into a single undo
  9135. // event
  9136. this.lastModTime = this.lastSelTime = 0;
  9137. this.lastOp = this.lastSelOp = null;
  9138. this.lastOrigin = this.lastSelOrigin = null;
  9139. // Used by the isClean() method
  9140. this.generation = this.maxGeneration = startGen || 1;
  9141. }
  9142. // Create a history change event from an updateDoc-style change
  9143. // object.
  9144. function historyChangeFromChange(doc, change) {
  9145. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  9146. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  9147. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  9148. return histChange;
  9149. }
  9150. // Pop all selection events off the end of a history array. Stop at
  9151. // a change event.
  9152. function clearSelectionEvents(array) {
  9153. while (array.length) {
  9154. var last = lst(array);
  9155. if (last.ranges) array.pop();
  9156. else break;
  9157. }
  9158. }
  9159. // Find the top change event in the history. Pop off selection
  9160. // events that are in the way.
  9161. function lastChangeEvent(hist, force) {
  9162. if (force) {
  9163. clearSelectionEvents(hist.done);
  9164. return lst(hist.done);
  9165. } else if (hist.done.length && !lst(hist.done).ranges) {
  9166. return lst(hist.done);
  9167. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  9168. hist.done.pop();
  9169. return lst(hist.done);
  9170. }
  9171. }
  9172. // Register a change in the history. Merges changes that are within
  9173. // a single operation, ore are close together with an origin that
  9174. // allows merging (starting with "+") into a single event.
  9175. function addChangeToHistory(doc, change, selAfter, opId) {
  9176. var hist = doc.history;
  9177. hist.undone.length = 0;
  9178. var time = +new Date, cur;
  9179. if ((hist.lastOp == opId ||
  9180. hist.lastOrigin == change.origin && change.origin &&
  9181. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  9182. change.origin.charAt(0) == "*")) &&
  9183. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  9184. // Merge this change into the last event
  9185. var last = lst(cur.changes);
  9186. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  9187. // Optimized case for simple insertion -- don't want to add
  9188. // new changesets for every character typed
  9189. last.to = changeEnd(change);
  9190. } else {
  9191. // Add new sub-event
  9192. cur.changes.push(historyChangeFromChange(doc, change));
  9193. }
  9194. } else {
  9195. // Can not be merged, start a new event.
  9196. var before = lst(hist.done);
  9197. if (!before || !before.ranges)
  9198. pushSelectionToHistory(doc.sel, hist.done);
  9199. cur = {changes: [historyChangeFromChange(doc, change)],
  9200. generation: hist.generation};
  9201. hist.done.push(cur);
  9202. while (hist.done.length > hist.undoDepth) {
  9203. hist.done.shift();
  9204. if (!hist.done[0].ranges) hist.done.shift();
  9205. }
  9206. }
  9207. hist.done.push(selAfter);
  9208. hist.generation = ++hist.maxGeneration;
  9209. hist.lastModTime = hist.lastSelTime = time;
  9210. hist.lastOp = hist.lastSelOp = opId;
  9211. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  9212. if (!last) signal(doc, "historyAdded");
  9213. }
  9214. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  9215. var ch = origin.charAt(0);
  9216. return ch == "*" ||
  9217. ch == "+" &&
  9218. prev.ranges.length == sel.ranges.length &&
  9219. prev.somethingSelected() == sel.somethingSelected() &&
  9220. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  9221. }
  9222. // Called whenever the selection changes, sets the new selection as
  9223. // the pending selection in the history, and pushes the old pending
  9224. // selection into the 'done' array when it was significantly
  9225. // different (in number of selected ranges, emptiness, or time).
  9226. function addSelectionToHistory(doc, sel, opId, options) {
  9227. var hist = doc.history, origin = options && options.origin;
  9228. // A new event is started when the previous origin does not match
  9229. // the current, or the origins don't allow matching. Origins
  9230. // starting with * are always merged, those starting with + are
  9231. // merged when similar and close together in time.
  9232. if (opId == hist.lastSelOp ||
  9233. (origin && hist.lastSelOrigin == origin &&
  9234. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  9235. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  9236. hist.done[hist.done.length - 1] = sel;
  9237. else
  9238. pushSelectionToHistory(sel, hist.done);
  9239. hist.lastSelTime = +new Date;
  9240. hist.lastSelOrigin = origin;
  9241. hist.lastSelOp = opId;
  9242. if (options && options.clearRedo !== false)
  9243. clearSelectionEvents(hist.undone);
  9244. }
  9245. function pushSelectionToHistory(sel, dest) {
  9246. var top = lst(dest);
  9247. if (!(top && top.ranges && top.equals(sel)))
  9248. dest.push(sel);
  9249. }
  9250. // Used to store marked span information in the history.
  9251. function attachLocalSpans(doc, change, from, to) {
  9252. var existing = change["spans_" + doc.id], n = 0;
  9253. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  9254. if (line.markedSpans)
  9255. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  9256. ++n;
  9257. });
  9258. }
  9259. // When un/re-doing restores text containing marked spans, those
  9260. // that have been explicitly cleared should not be restored.
  9261. function removeClearedSpans(spans) {
  9262. if (!spans) return null;
  9263. for (var i = 0, out; i < spans.length; ++i) {
  9264. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  9265. else if (out) out.push(spans[i]);
  9266. }
  9267. return !out ? spans : out.length ? out : null;
  9268. }
  9269. // Retrieve and filter the old marked spans stored in a change event.
  9270. function getOldSpans(doc, change) {
  9271. var found = change["spans_" + doc.id];
  9272. if (!found) return null;
  9273. for (var i = 0, nw = []; i < change.text.length; ++i)
  9274. nw.push(removeClearedSpans(found[i]));
  9275. return nw;
  9276. }
  9277. // Used both to provide a JSON-safe object in .getHistory, and, when
  9278. // detaching a document, to split the history in two
  9279. function copyHistoryArray(events, newGroup, instantiateSel) {
  9280. for (var i = 0, copy = []; i < events.length; ++i) {
  9281. var event = events[i];
  9282. if (event.ranges) {
  9283. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  9284. continue;
  9285. }
  9286. var changes = event.changes, newChanges = [];
  9287. copy.push({changes: newChanges});
  9288. for (var j = 0; j < changes.length; ++j) {
  9289. var change = changes[j], m;
  9290. newChanges.push({from: change.from, to: change.to, text: change.text});
  9291. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  9292. if (indexOf(newGroup, Number(m[1])) > -1) {
  9293. lst(newChanges)[prop] = change[prop];
  9294. delete change[prop];
  9295. }
  9296. }
  9297. }
  9298. }
  9299. return copy;
  9300. }
  9301. // Rebasing/resetting history to deal with externally-sourced changes
  9302. function rebaseHistSelSingle(pos, from, to, diff) {
  9303. if (to < pos.line) {
  9304. pos.line += diff;
  9305. } else if (from < pos.line) {
  9306. pos.line = from;
  9307. pos.ch = 0;
  9308. }
  9309. }
  9310. // Tries to rebase an array of history events given a change in the
  9311. // document. If the change touches the same lines as the event, the
  9312. // event, and everything 'behind' it, is discarded. If the change is
  9313. // before the event, the event's positions are updated. Uses a
  9314. // copy-on-write scheme for the positions, to avoid having to
  9315. // reallocate them all on every rebase, but also avoid problems with
  9316. // shared position objects being unsafely updated.
  9317. function rebaseHistArray(array, from, to, diff) {
  9318. for (var i = 0; i < array.length; ++i) {
  9319. var sub = array[i], ok = true;
  9320. if (sub.ranges) {
  9321. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  9322. for (var j = 0; j < sub.ranges.length; j++) {
  9323. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  9324. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  9325. }
  9326. continue;
  9327. }
  9328. for (var j = 0; j < sub.changes.length; ++j) {
  9329. var cur = sub.changes[j];
  9330. if (to < cur.from.line) {
  9331. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  9332. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  9333. } else if (from <= cur.to.line) {
  9334. ok = false;
  9335. break;
  9336. }
  9337. }
  9338. if (!ok) {
  9339. array.splice(0, i + 1);
  9340. i = 0;
  9341. }
  9342. }
  9343. }
  9344. function rebaseHist(hist, change) {
  9345. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  9346. rebaseHistArray(hist.done, from, to, diff);
  9347. rebaseHistArray(hist.undone, from, to, diff);
  9348. }
  9349. // EVENT UTILITIES
  9350. // Due to the fact that we still support jurassic IE versions, some
  9351. // compatibility wrappers are needed.
  9352. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  9353. if (e.preventDefault) e.preventDefault();
  9354. else e.returnValue = false;
  9355. };
  9356. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  9357. if (e.stopPropagation) e.stopPropagation();
  9358. else e.cancelBubble = true;
  9359. };
  9360. function e_defaultPrevented(e) {
  9361. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  9362. }
  9363. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  9364. function e_target(e) {return e.target || e.srcElement;}
  9365. function e_button(e) {
  9366. var b = e.which;
  9367. if (b == null) {
  9368. if (e.button & 1) b = 1;
  9369. else if (e.button & 2) b = 3;
  9370. else if (e.button & 4) b = 2;
  9371. }
  9372. if (mac && e.ctrlKey && b == 1) b = 3;
  9373. return b;
  9374. }
  9375. // EVENT HANDLING
  9376. // Lightweight event framework. on/off also work on DOM nodes,
  9377. // registering native DOM handlers.
  9378. var on = CodeMirror.on = function(emitter, type, f) {
  9379. if (emitter.addEventListener)
  9380. emitter.addEventListener(type, f, false);
  9381. else if (emitter.attachEvent)
  9382. emitter.attachEvent("on" + type, f);
  9383. else {
  9384. var map = emitter._handlers || (emitter._handlers = {});
  9385. var arr = map[type] || (map[type] = []);
  9386. arr.push(f);
  9387. }
  9388. };
  9389. var noHandlers = []
  9390. function getHandlers(emitter, type, copy) {
  9391. var arr = emitter._handlers && emitter._handlers[type]
  9392. if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
  9393. else return arr || noHandlers
  9394. }
  9395. var off = CodeMirror.off = function(emitter, type, f) {
  9396. if (emitter.removeEventListener)
  9397. emitter.removeEventListener(type, f, false);
  9398. else if (emitter.detachEvent)
  9399. emitter.detachEvent("on" + type, f);
  9400. else {
  9401. var handlers = getHandlers(emitter, type, false)
  9402. for (var i = 0; i < handlers.length; ++i)
  9403. if (handlers[i] == f) { handlers.splice(i, 1); break; }
  9404. }
  9405. };
  9406. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  9407. var handlers = getHandlers(emitter, type, true)
  9408. if (!handlers.length) return;
  9409. var args = Array.prototype.slice.call(arguments, 2);
  9410. for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
  9411. };
  9412. var orphanDelayedCallbacks = null;
  9413. // Often, we want to signal events at a point where we are in the
  9414. // middle of some work, but don't want the handler to start calling
  9415. // other methods on the editor, which might be in an inconsistent
  9416. // state or simply not expect any other events to happen.
  9417. // signalLater looks whether there are any handlers, and schedules
  9418. // them to be executed when the last operation ends, or, if no
  9419. // operation is active, when a timeout fires.
  9420. function signalLater(emitter, type /*, values...*/) {
  9421. var arr = getHandlers(emitter, type, false)
  9422. if (!arr.length) return;
  9423. var args = Array.prototype.slice.call(arguments, 2), list;
  9424. if (operationGroup) {
  9425. list = operationGroup.delayedCallbacks;
  9426. } else if (orphanDelayedCallbacks) {
  9427. list = orphanDelayedCallbacks;
  9428. } else {
  9429. list = orphanDelayedCallbacks = [];
  9430. setTimeout(fireOrphanDelayed, 0);
  9431. }
  9432. function bnd(f) {return function(){f.apply(null, args);};};
  9433. for (var i = 0; i < arr.length; ++i)
  9434. list.push(bnd(arr[i]));
  9435. }
  9436. function fireOrphanDelayed() {
  9437. var delayed = orphanDelayedCallbacks;
  9438. orphanDelayedCallbacks = null;
  9439. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  9440. }
  9441. // The DOM events that CodeMirror handles can be overridden by
  9442. // registering a (non-DOM) handler on the editor for the event name,
  9443. // and preventDefault-ing the event in that handler.
  9444. function signalDOMEvent(cm, e, override) {
  9445. if (typeof e == "string")
  9446. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  9447. signal(cm, override || e.type, cm, e);
  9448. return e_defaultPrevented(e) || e.codemirrorIgnore;
  9449. }
  9450. function signalCursorActivity(cm) {
  9451. var arr = cm._handlers && cm._handlers.cursorActivity;
  9452. if (!arr) return;
  9453. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  9454. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  9455. set.push(arr[i]);
  9456. }
  9457. function hasHandler(emitter, type) {
  9458. return getHandlers(emitter, type).length > 0
  9459. }
  9460. // Add on and off methods to a constructor's prototype, to make
  9461. // registering events on such objects more convenient.
  9462. function eventMixin(ctor) {
  9463. ctor.prototype.on = function(type, f) {on(this, type, f);};
  9464. ctor.prototype.off = function(type, f) {off(this, type, f);};
  9465. }
  9466. // MISC UTILITIES
  9467. // Number of pixels added to scroller and sizer to hide scrollbar
  9468. var scrollerGap = 30;
  9469. // Returned or thrown by various protocols to signal 'I'm not
  9470. // handling this'.
  9471. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  9472. // Reused option objects for setSelection & friends
  9473. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  9474. function Delayed() {this.id = null;}
  9475. Delayed.prototype.set = function(ms, f) {
  9476. clearTimeout(this.id);
  9477. this.id = setTimeout(f, ms);
  9478. };
  9479. // Counts the column offset in a string, taking tabs into account.
  9480. // Used mostly to find indentation.
  9481. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  9482. if (end == null) {
  9483. end = string.search(/[^\s\u00a0]/);
  9484. if (end == -1) end = string.length;
  9485. }
  9486. for (var i = startIndex || 0, n = startValue || 0;;) {
  9487. var nextTab = string.indexOf("\t", i);
  9488. if (nextTab < 0 || nextTab >= end)
  9489. return n + (end - i);
  9490. n += nextTab - i;
  9491. n += tabSize - (n % tabSize);
  9492. i = nextTab + 1;
  9493. }
  9494. };
  9495. // The inverse of countColumn -- find the offset that corresponds to
  9496. // a particular column.
  9497. var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
  9498. for (var pos = 0, col = 0;;) {
  9499. var nextTab = string.indexOf("\t", pos);
  9500. if (nextTab == -1) nextTab = string.length;
  9501. var skipped = nextTab - pos;
  9502. if (nextTab == string.length || col + skipped >= goal)
  9503. return pos + Math.min(skipped, goal - col);
  9504. col += nextTab - pos;
  9505. col += tabSize - (col % tabSize);
  9506. pos = nextTab + 1;
  9507. if (col >= goal) return pos;
  9508. }
  9509. }
  9510. var spaceStrs = [""];
  9511. function spaceStr(n) {
  9512. while (spaceStrs.length <= n)
  9513. spaceStrs.push(lst(spaceStrs) + " ");
  9514. return spaceStrs[n];
  9515. }
  9516. function lst(arr) { return arr[arr.length-1]; }
  9517. var selectInput = function(node) { node.select(); };
  9518. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  9519. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  9520. else if (ie) // Suppress mysterious IE10 errors
  9521. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  9522. function indexOf(array, elt) {
  9523. for (var i = 0; i < array.length; ++i)
  9524. if (array[i] == elt) return i;
  9525. return -1;
  9526. }
  9527. function map(array, f) {
  9528. var out = [];
  9529. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  9530. return out;
  9531. }
  9532. function nothing() {}
  9533. function createObj(base, props) {
  9534. var inst;
  9535. if (Object.create) {
  9536. inst = Object.create(base);
  9537. } else {
  9538. nothing.prototype = base;
  9539. inst = new nothing();
  9540. }
  9541. if (props) copyObj(props, inst);
  9542. return inst;
  9543. };
  9544. function copyObj(obj, target, overwrite) {
  9545. if (!target) target = {};
  9546. for (var prop in obj)
  9547. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  9548. target[prop] = obj[prop];
  9549. return target;
  9550. }
  9551. function bind(f) {
  9552. var args = Array.prototype.slice.call(arguments, 1);
  9553. return function(){return f.apply(null, args);};
  9554. }
  9555. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  9556. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  9557. return /\w/.test(ch) || ch > "\x80" &&
  9558. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  9559. };
  9560. function isWordChar(ch, helper) {
  9561. if (!helper) return isWordCharBasic(ch);
  9562. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  9563. return helper.test(ch);
  9564. }
  9565. function isEmpty(obj) {
  9566. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  9567. return true;
  9568. }
  9569. // Extending unicode characters. A series of a non-extending char +
  9570. // any number of extending chars is treated as a single unit as far
  9571. // as editing and measuring is concerned. This is not fully correct,
  9572. // since some scripts/fonts/browsers also treat other configurations
  9573. // of code points as a group.
  9574. 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]/;
  9575. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  9576. // DOM UTILITIES
  9577. function elt(tag, content, className, style) {
  9578. var e = document.createElement(tag);
  9579. if (className) e.className = className;
  9580. if (style) e.style.cssText = style;
  9581. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  9582. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  9583. return e;
  9584. }
  9585. var range;
  9586. if (document.createRange) range = function(node, start, end, endNode) {
  9587. var r = document.createRange();
  9588. r.setEnd(endNode || node, end);
  9589. r.setStart(node, start);
  9590. return r;
  9591. };
  9592. else range = function(node, start, end) {
  9593. var r = document.body.createTextRange();
  9594. try { r.moveToElementText(node.parentNode); }
  9595. catch(e) { return r; }
  9596. r.collapse(true);
  9597. r.moveEnd("character", end);
  9598. r.moveStart("character", start);
  9599. return r;
  9600. };
  9601. function removeChildren(e) {
  9602. for (var count = e.childNodes.length; count > 0; --count)
  9603. e.removeChild(e.firstChild);
  9604. return e;
  9605. }
  9606. function removeChildrenAndAdd(parent, e) {
  9607. return removeChildren(parent).appendChild(e);
  9608. }
  9609. var contains = CodeMirror.contains = function(parent, child) {
  9610. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  9611. child = child.parentNode;
  9612. if (parent.contains)
  9613. return parent.contains(child);
  9614. do {
  9615. if (child.nodeType == 11) child = child.host;
  9616. if (child == parent) return true;
  9617. } while (child = child.parentNode);
  9618. };
  9619. function activeElt() {
  9620. var activeElement = document.activeElement;
  9621. while (activeElement && activeElement.root && activeElement.root.activeElement)
  9622. activeElement = activeElement.root.activeElement;
  9623. return activeElement;
  9624. }
  9625. // Older versions of IE throws unspecified error when touching
  9626. // document.activeElement in some cases (during loading, in iframe)
  9627. if (ie && ie_version < 11) activeElt = function() {
  9628. try { return document.activeElement; }
  9629. catch(e) { return document.body; }
  9630. };
  9631. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  9632. var rmClass = CodeMirror.rmClass = function(node, cls) {
  9633. var current = node.className;
  9634. var match = classTest(cls).exec(current);
  9635. if (match) {
  9636. var after = current.slice(match.index + match[0].length);
  9637. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  9638. }
  9639. };
  9640. var addClass = CodeMirror.addClass = function(node, cls) {
  9641. var current = node.className;
  9642. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  9643. };
  9644. function joinClasses(a, b) {
  9645. var as = a.split(" ");
  9646. for (var i = 0; i < as.length; i++)
  9647. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  9648. return b;
  9649. }
  9650. // WINDOW-WIDE EVENTS
  9651. // These must be handled carefully, because naively registering a
  9652. // handler for each editor will cause the editors to never be
  9653. // garbage collected.
  9654. function forEachCodeMirror(f) {
  9655. if (!document.body.getElementsByClassName) return;
  9656. var byClass = document.body.getElementsByClassName("CodeMirror");
  9657. for (var i = 0; i < byClass.length; i++) {
  9658. var cm = byClass[i].CodeMirror;
  9659. if (cm) f(cm);
  9660. }
  9661. }
  9662. var globalsRegistered = false;
  9663. function ensureGlobalHandlers() {
  9664. if (globalsRegistered) return;
  9665. registerGlobalHandlers();
  9666. globalsRegistered = true;
  9667. }
  9668. function registerGlobalHandlers() {
  9669. // When the window resizes, we need to refresh active editors.
  9670. var resizeTimer;
  9671. on(window, "resize", function() {
  9672. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  9673. resizeTimer = null;
  9674. forEachCodeMirror(onResize);
  9675. }, 100);
  9676. });
  9677. // When the window loses focus, we want to show the editor as blurred
  9678. on(window, "blur", function() {
  9679. forEachCodeMirror(onBlur);
  9680. });
  9681. }
  9682. // FEATURE DETECTION
  9683. // Detect drag-and-drop
  9684. var dragAndDrop = function() {
  9685. // There is *some* kind of drag-and-drop support in IE6-8, but I
  9686. // couldn't get it to work yet.
  9687. if (ie && ie_version < 9) return false;
  9688. var div = elt('div');
  9689. return "draggable" in div || "dragDrop" in div;
  9690. }();
  9691. var zwspSupported;
  9692. function zeroWidthElement(measure) {
  9693. if (zwspSupported == null) {
  9694. var test = elt("span", "\u200b");
  9695. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  9696. if (measure.firstChild.offsetHeight != 0)
  9697. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  9698. }
  9699. var node = zwspSupported ? elt("span", "\u200b") :
  9700. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  9701. node.setAttribute("cm-text", "");
  9702. return node;
  9703. }
  9704. // Feature-detect IE's crummy client rect reporting for bidi text
  9705. var badBidiRects;
  9706. function hasBadBidiRects(measure) {
  9707. if (badBidiRects != null) return badBidiRects;
  9708. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  9709. var r0 = range(txt, 0, 1).getBoundingClientRect();
  9710. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  9711. var r1 = range(txt, 1, 2).getBoundingClientRect();
  9712. return badBidiRects = (r1.right - r0.right < 3);
  9713. }
  9714. // See if "".split is the broken IE version, if so, provide an
  9715. // alternative way to split lines.
  9716. var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  9717. var pos = 0, result = [], l = string.length;
  9718. while (pos <= l) {
  9719. var nl = string.indexOf("\n", pos);
  9720. if (nl == -1) nl = string.length;
  9721. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  9722. var rt = line.indexOf("\r");
  9723. if (rt != -1) {
  9724. result.push(line.slice(0, rt));
  9725. pos += rt + 1;
  9726. } else {
  9727. result.push(line);
  9728. pos = nl + 1;
  9729. }
  9730. }
  9731. return result;
  9732. } : function(string){return string.split(/\r\n?|\n/);};
  9733. var hasSelection = window.getSelection ? function(te) {
  9734. try { return te.selectionStart != te.selectionEnd; }
  9735. catch(e) { return false; }
  9736. } : function(te) {
  9737. try {var range = te.ownerDocument.selection.createRange();}
  9738. catch(e) {}
  9739. if (!range || range.parentElement() != te) return false;
  9740. return range.compareEndPoints("StartToEnd", range) != 0;
  9741. };
  9742. var hasCopyEvent = (function() {
  9743. var e = elt("div");
  9744. if ("oncopy" in e) return true;
  9745. e.setAttribute("oncopy", "return;");
  9746. return typeof e.oncopy == "function";
  9747. })();
  9748. var badZoomedRects = null;
  9749. function hasBadZoomedRects(measure) {
  9750. if (badZoomedRects != null) return badZoomedRects;
  9751. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  9752. var normal = node.getBoundingClientRect();
  9753. var fromRange = range(node, 0, 1).getBoundingClientRect();
  9754. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  9755. }
  9756. // KEY NAMES
  9757. var keyNames = CodeMirror.keyNames = {
  9758. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  9759. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  9760. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  9761. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  9762. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  9763. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  9764. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  9765. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  9766. };
  9767. (function() {
  9768. // Number keys
  9769. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  9770. // Alphabetic keys
  9771. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  9772. // Function keys
  9773. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  9774. })();
  9775. // BIDI HELPERS
  9776. function iterateBidiSections(order, from, to, f) {
  9777. if (!order) return f(from, to, "ltr");
  9778. var found = false;
  9779. for (var i = 0; i < order.length; ++i) {
  9780. var part = order[i];
  9781. if (part.from < to && part.to > from || from == to && part.to == from) {
  9782. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  9783. found = true;
  9784. }
  9785. }
  9786. if (!found) f(from, to, "ltr");
  9787. }
  9788. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  9789. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  9790. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  9791. function lineRight(line) {
  9792. var order = getOrder(line);
  9793. if (!order) return line.text.length;
  9794. return bidiRight(lst(order));
  9795. }
  9796. function lineStart(cm, lineN) {
  9797. var line = getLine(cm.doc, lineN);
  9798. var visual = visualLine(line);
  9799. if (visual != line) lineN = lineNo(visual);
  9800. var order = getOrder(visual);
  9801. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  9802. return Pos(lineN, ch);
  9803. }
  9804. function lineEnd(cm, lineN) {
  9805. var merged, line = getLine(cm.doc, lineN);
  9806. while (merged = collapsedSpanAtEnd(line)) {
  9807. line = merged.find(1, true).line;
  9808. lineN = null;
  9809. }
  9810. var order = getOrder(line);
  9811. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  9812. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  9813. }
  9814. function lineStartSmart(cm, pos) {
  9815. var start = lineStart(cm, pos.line);
  9816. var line = getLine(cm.doc, start.line);
  9817. var order = getOrder(line);
  9818. if (!order || order[0].level == 0) {
  9819. var firstNonWS = Math.max(0, line.text.search(/\S/));
  9820. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  9821. return Pos(start.line, inWS ? 0 : firstNonWS);
  9822. }
  9823. return start;
  9824. }
  9825. function compareBidiLevel(order, a, b) {
  9826. var linedir = order[0].level;
  9827. if (a == linedir) return true;
  9828. if (b == linedir) return false;
  9829. return a < b;
  9830. }
  9831. var bidiOther;
  9832. function getBidiPartAt(order, pos) {
  9833. bidiOther = null;
  9834. for (var i = 0, found; i < order.length; ++i) {
  9835. var cur = order[i];
  9836. if (cur.from < pos && cur.to > pos) return i;
  9837. if ((cur.from == pos || cur.to == pos)) {
  9838. if (found == null) {
  9839. found = i;
  9840. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  9841. if (cur.from != cur.to) bidiOther = found;
  9842. return i;
  9843. } else {
  9844. if (cur.from != cur.to) bidiOther = i;
  9845. return found;
  9846. }
  9847. }
  9848. }
  9849. return found;
  9850. }
  9851. function moveInLine(line, pos, dir, byUnit) {
  9852. if (!byUnit) return pos + dir;
  9853. do pos += dir;
  9854. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  9855. return pos;
  9856. }
  9857. // This is needed in order to move 'visually' through bi-directional
  9858. // text -- i.e., pressing left should make the cursor go left, even
  9859. // when in RTL text. The tricky part is the 'jumps', where RTL and
  9860. // LTR text touch each other. This often requires the cursor offset
  9861. // to move more than one unit, in order to visually move one unit.
  9862. function moveVisually(line, start, dir, byUnit) {
  9863. var bidi = getOrder(line);
  9864. if (!bidi) return moveLogically(line, start, dir, byUnit);
  9865. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  9866. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  9867. for (;;) {
  9868. if (target > part.from && target < part.to) return target;
  9869. if (target == part.from || target == part.to) {
  9870. if (getBidiPartAt(bidi, target) == pos) return target;
  9871. part = bidi[pos += dir];
  9872. return (dir > 0) == part.level % 2 ? part.to : part.from;
  9873. } else {
  9874. part = bidi[pos += dir];
  9875. if (!part) return null;
  9876. if ((dir > 0) == part.level % 2)
  9877. target = moveInLine(line, part.to, -1, byUnit);
  9878. else
  9879. target = moveInLine(line, part.from, 1, byUnit);
  9880. }
  9881. }
  9882. }
  9883. function moveLogically(line, start, dir, byUnit) {
  9884. var target = start + dir;
  9885. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  9886. return target < 0 || target > line.text.length ? null : target;
  9887. }
  9888. // Bidirectional ordering algorithm
  9889. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  9890. // that this (partially) implements.
  9891. // One-char codes used for character types:
  9892. // L (L): Left-to-Right
  9893. // R (R): Right-to-Left
  9894. // r (AL): Right-to-Left Arabic
  9895. // 1 (EN): European Number
  9896. // + (ES): European Number Separator
  9897. // % (ET): European Number Terminator
  9898. // n (AN): Arabic Number
  9899. // , (CS): Common Number Separator
  9900. // m (NSM): Non-Spacing Mark
  9901. // b (BN): Boundary Neutral
  9902. // s (B): Paragraph Separator
  9903. // t (S): Segment Separator
  9904. // w (WS): Whitespace
  9905. // N (ON): Other Neutrals
  9906. // Returns null if characters are ordered as they appear
  9907. // (left-to-right), or an array of sections ({from, to, level}
  9908. // objects) in the order in which they occur visually.
  9909. var bidiOrdering = (function() {
  9910. // Character types for codepoints 0 to 0xff
  9911. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  9912. // Character types for codepoints 0x600 to 0x6ff
  9913. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  9914. function charType(code) {
  9915. if (code <= 0xf7) return lowTypes.charAt(code);
  9916. else if (0x590 <= code && code <= 0x5f4) return "R";
  9917. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  9918. else if (0x6ee <= code && code <= 0x8ac) return "r";
  9919. else if (0x2000 <= code && code <= 0x200b) return "w";
  9920. else if (code == 0x200c) return "b";
  9921. else return "L";
  9922. }
  9923. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  9924. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  9925. // Browsers seem to always treat the boundaries of block elements as being L.
  9926. var outerType = "L";
  9927. function BidiSpan(level, from, to) {
  9928. this.level = level;
  9929. this.from = from; this.to = to;
  9930. }
  9931. return function(str) {
  9932. if (!bidiRE.test(str)) return false;
  9933. var len = str.length, types = [];
  9934. for (var i = 0, type; i < len; ++i)
  9935. types.push(type = charType(str.charCodeAt(i)));
  9936. // W1. Examine each non-spacing mark (NSM) in the level run, and
  9937. // change the type of the NSM to the type of the previous
  9938. // character. If the NSM is at the start of the level run, it will
  9939. // get the type of sor.
  9940. for (var i = 0, prev = outerType; i < len; ++i) {
  9941. var type = types[i];
  9942. if (type == "m") types[i] = prev;
  9943. else prev = type;
  9944. }
  9945. // W2. Search backwards from each instance of a European number
  9946. // until the first strong type (R, L, AL, or sor) is found. If an
  9947. // AL is found, change the type of the European number to Arabic
  9948. // number.
  9949. // W3. Change all ALs to R.
  9950. for (var i = 0, cur = outerType; i < len; ++i) {
  9951. var type = types[i];
  9952. if (type == "1" && cur == "r") types[i] = "n";
  9953. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  9954. }
  9955. // W4. A single European separator between two European numbers
  9956. // changes to a European number. A single common separator between
  9957. // two numbers of the same type changes to that type.
  9958. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  9959. var type = types[i];
  9960. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  9961. else if (type == "," && prev == types[i+1] &&
  9962. (prev == "1" || prev == "n")) types[i] = prev;
  9963. prev = type;
  9964. }
  9965. // W5. A sequence of European terminators adjacent to European
  9966. // numbers changes to all European numbers.
  9967. // W6. Otherwise, separators and terminators change to Other
  9968. // Neutral.
  9969. for (var i = 0; i < len; ++i) {
  9970. var type = types[i];
  9971. if (type == ",") types[i] = "N";
  9972. else if (type == "%") {
  9973. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  9974. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  9975. for (var j = i; j < end; ++j) types[j] = replace;
  9976. i = end - 1;
  9977. }
  9978. }
  9979. // W7. Search backwards from each instance of a European number
  9980. // until the first strong type (R, L, or sor) is found. If an L is
  9981. // found, then change the type of the European number to L.
  9982. for (var i = 0, cur = outerType; i < len; ++i) {
  9983. var type = types[i];
  9984. if (cur == "L" && type == "1") types[i] = "L";
  9985. else if (isStrong.test(type)) cur = type;
  9986. }
  9987. // N1. A sequence of neutrals takes the direction of the
  9988. // surrounding strong text if the text on both sides has the same
  9989. // direction. European and Arabic numbers act as if they were R in
  9990. // terms of their influence on neutrals. Start-of-level-run (sor)
  9991. // and end-of-level-run (eor) are used at level run boundaries.
  9992. // N2. Any remaining neutrals take the embedding direction.
  9993. for (var i = 0; i < len; ++i) {
  9994. if (isNeutral.test(types[i])) {
  9995. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  9996. var before = (i ? types[i-1] : outerType) == "L";
  9997. var after = (end < len ? types[end] : outerType) == "L";
  9998. var replace = before || after ? "L" : "R";
  9999. for (var j = i; j < end; ++j) types[j] = replace;
  10000. i = end - 1;
  10001. }
  10002. }
  10003. // Here we depart from the documented algorithm, in order to avoid
  10004. // building up an actual levels array. Since there are only three
  10005. // levels (0, 1, 2) in an implementation that doesn't take
  10006. // explicit embedding into account, we can build up the order on
  10007. // the fly, without following the level-based algorithm.
  10008. var order = [], m;
  10009. for (var i = 0; i < len;) {
  10010. if (countsAsLeft.test(types[i])) {
  10011. var start = i;
  10012. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  10013. order.push(new BidiSpan(0, start, i));
  10014. } else {
  10015. var pos = i, at = order.length;
  10016. for (++i; i < len && types[i] != "L"; ++i) {}
  10017. for (var j = pos; j < i;) {
  10018. if (countsAsNum.test(types[j])) {
  10019. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  10020. var nstart = j;
  10021. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  10022. order.splice(at, 0, new BidiSpan(2, nstart, j));
  10023. pos = j;
  10024. } else ++j;
  10025. }
  10026. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  10027. }
  10028. }
  10029. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  10030. order[0].from = m[0].length;
  10031. order.unshift(new BidiSpan(0, 0, m[0].length));
  10032. }
  10033. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  10034. lst(order).to -= m[0].length;
  10035. order.push(new BidiSpan(0, len - m[0].length, len));
  10036. }
  10037. if (order[0].level == 2)
  10038. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  10039. if (order[0].level != lst(order).level)
  10040. order.push(new BidiSpan(order[0].level, len, len));
  10041. return order;
  10042. };
  10043. })();
  10044. // THE END
  10045. CodeMirror.version = "5.15.2";
  10046. return CodeMirror;
  10047. });
  10048. },{}],11:[function(require,module,exports){
  10049. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10050. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10051. (function(mod) {
  10052. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10053. mod(require("../../lib/codemirror"), require("../markdown/markdown"), require("../../addon/mode/overlay"));
  10054. else if (typeof define == "function" && define.amd) // AMD
  10055. define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod);
  10056. else // Plain browser env
  10057. mod(CodeMirror);
  10058. })(function(CodeMirror) {
  10059. "use strict";
  10060. 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
  10061. CodeMirror.defineMode("gfm", function(config, modeConfig) {
  10062. var codeDepth = 0;
  10063. function blankLine(state) {
  10064. state.code = false;
  10065. return null;
  10066. }
  10067. var gfmOverlay = {
  10068. startState: function() {
  10069. return {
  10070. code: false,
  10071. codeBlock: false,
  10072. ateSpace: false
  10073. };
  10074. },
  10075. copyState: function(s) {
  10076. return {
  10077. code: s.code,
  10078. codeBlock: s.codeBlock,
  10079. ateSpace: s.ateSpace
  10080. };
  10081. },
  10082. token: function(stream, state) {
  10083. state.combineTokens = null;
  10084. // Hack to prevent formatting override inside code blocks (block and inline)
  10085. if (state.codeBlock) {
  10086. if (stream.match(/^```+/)) {
  10087. state.codeBlock = false;
  10088. return null;
  10089. }
  10090. stream.skipToEnd();
  10091. return null;
  10092. }
  10093. if (stream.sol()) {
  10094. state.code = false;
  10095. }
  10096. if (stream.sol() && stream.match(/^```+/)) {
  10097. stream.skipToEnd();
  10098. state.codeBlock = true;
  10099. return null;
  10100. }
  10101. // If this block is changed, it may need to be updated in Markdown mode
  10102. if (stream.peek() === '`') {
  10103. stream.next();
  10104. var before = stream.pos;
  10105. stream.eatWhile('`');
  10106. var difference = 1 + stream.pos - before;
  10107. if (!state.code) {
  10108. codeDepth = difference;
  10109. state.code = true;
  10110. } else {
  10111. if (difference === codeDepth) { // Must be exact
  10112. state.code = false;
  10113. }
  10114. }
  10115. return null;
  10116. } else if (state.code) {
  10117. stream.next();
  10118. return null;
  10119. }
  10120. // Check if space. If so, links can be formatted later on
  10121. if (stream.eatSpace()) {
  10122. state.ateSpace = true;
  10123. return null;
  10124. }
  10125. if (stream.sol() || state.ateSpace) {
  10126. state.ateSpace = false;
  10127. if (modeConfig.gitHubSpice !== false) {
  10128. if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) {
  10129. // User/Project@SHA
  10130. // User@SHA
  10131. // SHA
  10132. state.combineTokens = true;
  10133. return "link";
  10134. } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
  10135. // User/Project#Num
  10136. // User#Num
  10137. // #Num
  10138. state.combineTokens = true;
  10139. return "link";
  10140. }
  10141. }
  10142. }
  10143. if (stream.match(urlRE) &&
  10144. stream.string.slice(stream.start - 2, stream.start) != "](" &&
  10145. (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
  10146. // URLs
  10147. // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
  10148. // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
  10149. // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
  10150. state.combineTokens = true;
  10151. return "link";
  10152. }
  10153. stream.next();
  10154. return null;
  10155. },
  10156. blankLine: blankLine
  10157. };
  10158. var markdownConfig = {
  10159. underscoresBreakWords: false,
  10160. taskLists: true,
  10161. fencedCodeBlocks: '```',
  10162. strikethrough: true
  10163. };
  10164. for (var attr in modeConfig) {
  10165. markdownConfig[attr] = modeConfig[attr];
  10166. }
  10167. markdownConfig.name = "markdown";
  10168. return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
  10169. }, "markdown");
  10170. CodeMirror.defineMIME("text/x-gfm", "gfm");
  10171. });
  10172. },{"../../addon/mode/overlay":8,"../../lib/codemirror":10,"../markdown/markdown":12}],12:[function(require,module,exports){
  10173. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10174. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10175. (function(mod) {
  10176. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10177. mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta"));
  10178. else if (typeof define == "function" && define.amd) // AMD
  10179. define(["../../lib/codemirror", "../xml/xml", "../meta"], mod);
  10180. else // Plain browser env
  10181. mod(CodeMirror);
  10182. })(function(CodeMirror) {
  10183. "use strict";
  10184. CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
  10185. var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
  10186. var htmlModeMissing = htmlMode.name == "null"
  10187. function getMode(name) {
  10188. if (CodeMirror.findModeByName) {
  10189. var found = CodeMirror.findModeByName(name);
  10190. if (found) name = found.mime || found.mimes[0];
  10191. }
  10192. var mode = CodeMirror.getMode(cmCfg, name);
  10193. return mode.name == "null" ? null : mode;
  10194. }
  10195. // Should characters that affect highlighting be highlighted separate?
  10196. // Does not include characters that will be output (such as `1.` and `-` for lists)
  10197. if (modeCfg.highlightFormatting === undefined)
  10198. modeCfg.highlightFormatting = false;
  10199. // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
  10200. // Excess `>` will emit `error` token.
  10201. if (modeCfg.maxBlockquoteDepth === undefined)
  10202. modeCfg.maxBlockquoteDepth = 0;
  10203. // Should underscores in words open/close em/strong?
  10204. if (modeCfg.underscoresBreakWords === undefined)
  10205. modeCfg.underscoresBreakWords = true;
  10206. // Use `fencedCodeBlocks` to configure fenced code blocks. false to
  10207. // disable, string to specify a precise regexp that the fence should
  10208. // match, and true to allow three or more backticks or tildes (as
  10209. // per CommonMark).
  10210. // Turn on task lists? ("- [ ] " and "- [x] ")
  10211. if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
  10212. // Turn on strikethrough syntax
  10213. if (modeCfg.strikethrough === undefined)
  10214. modeCfg.strikethrough = false;
  10215. // Allow token types to be overridden by user-provided token types.
  10216. if (modeCfg.tokenTypeOverrides === undefined)
  10217. modeCfg.tokenTypeOverrides = {};
  10218. var tokenTypes = {
  10219. header: "header",
  10220. code: "comment",
  10221. quote: "quote",
  10222. list1: "variable-2",
  10223. list2: "variable-3",
  10224. list3: "keyword",
  10225. hr: "hr",
  10226. image: "tag",
  10227. formatting: "formatting",
  10228. linkInline: "link",
  10229. linkEmail: "link",
  10230. linkText: "link",
  10231. linkHref: "string",
  10232. em: "em",
  10233. strong: "strong",
  10234. strikethrough: "strikethrough"
  10235. };
  10236. for (var tokenType in tokenTypes) {
  10237. if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
  10238. tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
  10239. }
  10240. }
  10241. var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
  10242. , ulRE = /^[*\-+]\s+/
  10243. , olRE = /^[0-9]+([.)])\s+/
  10244. , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE
  10245. , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
  10246. , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/
  10247. , textRE = /^[^#!\[\]*_\\<>` "'(~]+/
  10248. , fencedCodeRE = new RegExp("^(" + (modeCfg.fencedCodeBlocks === true ? "~~~+|```+" : modeCfg.fencedCodeBlocks) +
  10249. ")[ \\t]*([\\w+#\-]*)");
  10250. function switchInline(stream, state, f) {
  10251. state.f = state.inline = f;
  10252. return f(stream, state);
  10253. }
  10254. function switchBlock(stream, state, f) {
  10255. state.f = state.block = f;
  10256. return f(stream, state);
  10257. }
  10258. function lineIsEmpty(line) {
  10259. return !line || !/\S/.test(line.string)
  10260. }
  10261. // Blocks
  10262. function blankLine(state) {
  10263. // Reset linkTitle state
  10264. state.linkTitle = false;
  10265. // Reset EM state
  10266. state.em = false;
  10267. // Reset STRONG state
  10268. state.strong = false;
  10269. // Reset strikethrough state
  10270. state.strikethrough = false;
  10271. // Reset state.quote
  10272. state.quote = 0;
  10273. // Reset state.indentedCode
  10274. state.indentedCode = false;
  10275. if (htmlModeMissing && state.f == htmlBlock) {
  10276. state.f = inlineNormal;
  10277. state.block = blockNormal;
  10278. }
  10279. // Reset state.trailingSpace
  10280. state.trailingSpace = 0;
  10281. state.trailingSpaceNewLine = false;
  10282. // Mark this line as blank
  10283. state.prevLine = state.thisLine
  10284. state.thisLine = null
  10285. return null;
  10286. }
  10287. function blockNormal(stream, state) {
  10288. var sol = stream.sol();
  10289. var prevLineIsList = state.list !== false,
  10290. prevLineIsIndentedCode = state.indentedCode;
  10291. state.indentedCode = false;
  10292. if (prevLineIsList) {
  10293. if (state.indentationDiff >= 0) { // Continued list
  10294. if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block
  10295. state.indentation -= state.indentationDiff;
  10296. }
  10297. state.list = null;
  10298. } else if (state.indentation > 0) {
  10299. state.list = null;
  10300. } else { // No longer a list
  10301. state.list = false;
  10302. }
  10303. }
  10304. var match = null;
  10305. if (state.indentationDiff >= 4) {
  10306. stream.skipToEnd();
  10307. if (prevLineIsIndentedCode || lineIsEmpty(state.prevLine)) {
  10308. state.indentation -= 4;
  10309. state.indentedCode = true;
  10310. return tokenTypes.code;
  10311. } else {
  10312. return null;
  10313. }
  10314. } else if (stream.eatSpace()) {
  10315. return null;
  10316. } else if ((match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
  10317. state.header = match[1].length;
  10318. if (modeCfg.highlightFormatting) state.formatting = "header";
  10319. state.f = state.inline;
  10320. return getType(state);
  10321. } else if (!lineIsEmpty(state.prevLine) && !state.quote && !prevLineIsList &&
  10322. !prevLineIsIndentedCode && (match = stream.match(setextHeaderRE))) {
  10323. state.header = match[0].charAt(0) == '=' ? 1 : 2;
  10324. if (modeCfg.highlightFormatting) state.formatting = "header";
  10325. state.f = state.inline;
  10326. return getType(state);
  10327. } else if (stream.eat('>')) {
  10328. state.quote = sol ? 1 : state.quote + 1;
  10329. if (modeCfg.highlightFormatting) state.formatting = "quote";
  10330. stream.eatSpace();
  10331. return getType(state);
  10332. } else if (stream.peek() === '[') {
  10333. return switchInline(stream, state, footnoteLink);
  10334. } else if (stream.match(hrRE, true)) {
  10335. state.hr = true;
  10336. return tokenTypes.hr;
  10337. } else if ((lineIsEmpty(state.prevLine) || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) {
  10338. var listType = null;
  10339. if (stream.match(ulRE, true)) {
  10340. listType = 'ul';
  10341. } else {
  10342. stream.match(olRE, true);
  10343. listType = 'ol';
  10344. }
  10345. state.indentation = stream.column() + stream.current().length;
  10346. state.list = true;
  10347. // While this list item's marker's indentation
  10348. // is less than the deepest list item's content's indentation,
  10349. // pop the deepest list item indentation off the stack.
  10350. while (state.listStack && stream.column() < state.listStack[state.listStack.length - 1]) {
  10351. state.listStack.pop();
  10352. }
  10353. // Add this list item's content's indentation to the stack
  10354. state.listStack.push(state.indentation);
  10355. if (modeCfg.taskLists && stream.match(taskListRE, false)) {
  10356. state.taskList = true;
  10357. }
  10358. state.f = state.inline;
  10359. if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
  10360. return getType(state);
  10361. } else if (modeCfg.fencedCodeBlocks && (match = stream.match(fencedCodeRE, true))) {
  10362. state.fencedChars = match[1]
  10363. // try switching mode
  10364. state.localMode = getMode(match[2]);
  10365. if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
  10366. state.f = state.block = local;
  10367. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  10368. state.code = -1
  10369. return getType(state);
  10370. }
  10371. return switchInline(stream, state, state.inline);
  10372. }
  10373. function htmlBlock(stream, state) {
  10374. var style = htmlMode.token(stream, state.htmlState);
  10375. if (!htmlModeMissing) {
  10376. var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
  10377. if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
  10378. (!inner.state.context && inner.state.tokenize.isInText)) ||
  10379. (state.md_inside && stream.current().indexOf(">") > -1)) {
  10380. state.f = inlineNormal;
  10381. state.block = blockNormal;
  10382. state.htmlState = null;
  10383. }
  10384. }
  10385. return style;
  10386. }
  10387. function local(stream, state) {
  10388. if (state.fencedChars && stream.match(state.fencedChars, false)) {
  10389. state.localMode = state.localState = null;
  10390. state.f = state.block = leavingLocal;
  10391. return null;
  10392. } else if (state.localMode) {
  10393. return state.localMode.token(stream, state.localState);
  10394. } else {
  10395. stream.skipToEnd();
  10396. return tokenTypes.code;
  10397. }
  10398. }
  10399. function leavingLocal(stream, state) {
  10400. stream.match(state.fencedChars);
  10401. state.block = blockNormal;
  10402. state.f = inlineNormal;
  10403. state.fencedChars = null;
  10404. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  10405. state.code = 1
  10406. var returnType = getType(state);
  10407. state.code = 0
  10408. return returnType;
  10409. }
  10410. // Inline
  10411. function getType(state) {
  10412. var styles = [];
  10413. if (state.formatting) {
  10414. styles.push(tokenTypes.formatting);
  10415. if (typeof state.formatting === "string") state.formatting = [state.formatting];
  10416. for (var i = 0; i < state.formatting.length; i++) {
  10417. styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
  10418. if (state.formatting[i] === "header") {
  10419. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
  10420. }
  10421. // Add `formatting-quote` and `formatting-quote-#` for blockquotes
  10422. // Add `error` instead if the maximum blockquote nesting depth is passed
  10423. if (state.formatting[i] === "quote") {
  10424. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  10425. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
  10426. } else {
  10427. styles.push("error");
  10428. }
  10429. }
  10430. }
  10431. }
  10432. if (state.taskOpen) {
  10433. styles.push("meta");
  10434. return styles.length ? styles.join(' ') : null;
  10435. }
  10436. if (state.taskClosed) {
  10437. styles.push("property");
  10438. return styles.length ? styles.join(' ') : null;
  10439. }
  10440. if (state.linkHref) {
  10441. styles.push(tokenTypes.linkHref, "url");
  10442. } else { // Only apply inline styles to non-url text
  10443. if (state.strong) { styles.push(tokenTypes.strong); }
  10444. if (state.em) { styles.push(tokenTypes.em); }
  10445. if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
  10446. if (state.linkText) { styles.push(tokenTypes.linkText); }
  10447. if (state.code) { styles.push(tokenTypes.code); }
  10448. }
  10449. if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
  10450. if (state.quote) {
  10451. styles.push(tokenTypes.quote);
  10452. // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
  10453. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  10454. styles.push(tokenTypes.quote + "-" + state.quote);
  10455. } else {
  10456. styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
  10457. }
  10458. }
  10459. if (state.list !== false) {
  10460. var listMod = (state.listStack.length - 1) % 3;
  10461. if (!listMod) {
  10462. styles.push(tokenTypes.list1);
  10463. } else if (listMod === 1) {
  10464. styles.push(tokenTypes.list2);
  10465. } else {
  10466. styles.push(tokenTypes.list3);
  10467. }
  10468. }
  10469. if (state.trailingSpaceNewLine) {
  10470. styles.push("trailing-space-new-line");
  10471. } else if (state.trailingSpace) {
  10472. styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
  10473. }
  10474. return styles.length ? styles.join(' ') : null;
  10475. }
  10476. function handleText(stream, state) {
  10477. if (stream.match(textRE, true)) {
  10478. return getType(state);
  10479. }
  10480. return undefined;
  10481. }
  10482. function inlineNormal(stream, state) {
  10483. var style = state.text(stream, state);
  10484. if (typeof style !== 'undefined')
  10485. return style;
  10486. if (state.list) { // List marker (*, +, -, 1., etc)
  10487. state.list = null;
  10488. return getType(state);
  10489. }
  10490. if (state.taskList) {
  10491. var taskOpen = stream.match(taskListRE, true)[1] !== "x";
  10492. if (taskOpen) state.taskOpen = true;
  10493. else state.taskClosed = true;
  10494. if (modeCfg.highlightFormatting) state.formatting = "task";
  10495. state.taskList = false;
  10496. return getType(state);
  10497. }
  10498. state.taskOpen = false;
  10499. state.taskClosed = false;
  10500. if (state.header && stream.match(/^#+$/, true)) {
  10501. if (modeCfg.highlightFormatting) state.formatting = "header";
  10502. return getType(state);
  10503. }
  10504. // Get sol() value now, before character is consumed
  10505. var sol = stream.sol();
  10506. var ch = stream.next();
  10507. // Matches link titles present on next line
  10508. if (state.linkTitle) {
  10509. state.linkTitle = false;
  10510. var matchCh = ch;
  10511. if (ch === '(') {
  10512. matchCh = ')';
  10513. }
  10514. matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
  10515. var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
  10516. if (stream.match(new RegExp(regex), true)) {
  10517. return tokenTypes.linkHref;
  10518. }
  10519. }
  10520. // If this block is changed, it may need to be updated in GFM mode
  10521. if (ch === '`') {
  10522. var previousFormatting = state.formatting;
  10523. if (modeCfg.highlightFormatting) state.formatting = "code";
  10524. stream.eatWhile('`');
  10525. var count = stream.current().length
  10526. if (state.code == 0) {
  10527. state.code = count
  10528. return getType(state)
  10529. } else if (count == state.code) { // Must be exact
  10530. var t = getType(state)
  10531. state.code = 0
  10532. return t
  10533. } else {
  10534. state.formatting = previousFormatting
  10535. return getType(state)
  10536. }
  10537. } else if (state.code) {
  10538. return getType(state);
  10539. }
  10540. if (ch === '\\') {
  10541. stream.next();
  10542. if (modeCfg.highlightFormatting) {
  10543. var type = getType(state);
  10544. var formattingEscape = tokenTypes.formatting + "-escape";
  10545. return type ? type + " " + formattingEscape : formattingEscape;
  10546. }
  10547. }
  10548. if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
  10549. stream.match(/\[[^\]]*\]/);
  10550. state.inline = state.f = linkHref;
  10551. return tokenTypes.image;
  10552. }
  10553. if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false)) {
  10554. state.linkText = true;
  10555. if (modeCfg.highlightFormatting) state.formatting = "link";
  10556. return getType(state);
  10557. }
  10558. if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) {
  10559. if (modeCfg.highlightFormatting) state.formatting = "link";
  10560. var type = getType(state);
  10561. state.linkText = false;
  10562. state.inline = state.f = linkHref;
  10563. return type;
  10564. }
  10565. if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
  10566. state.f = state.inline = linkInline;
  10567. if (modeCfg.highlightFormatting) state.formatting = "link";
  10568. var type = getType(state);
  10569. if (type){
  10570. type += " ";
  10571. } else {
  10572. type = "";
  10573. }
  10574. return type + tokenTypes.linkInline;
  10575. }
  10576. if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
  10577. state.f = state.inline = linkInline;
  10578. if (modeCfg.highlightFormatting) state.formatting = "link";
  10579. var type = getType(state);
  10580. if (type){
  10581. type += " ";
  10582. } else {
  10583. type = "";
  10584. }
  10585. return type + tokenTypes.linkEmail;
  10586. }
  10587. if (ch === '<' && stream.match(/^(!--|\w)/, false)) {
  10588. var end = stream.string.indexOf(">", stream.pos);
  10589. if (end != -1) {
  10590. var atts = stream.string.substring(stream.start, end);
  10591. if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
  10592. }
  10593. stream.backUp(1);
  10594. state.htmlState = CodeMirror.startState(htmlMode);
  10595. return switchBlock(stream, state, htmlBlock);
  10596. }
  10597. if (ch === '<' && stream.match(/^\/\w*?>/)) {
  10598. state.md_inside = false;
  10599. return "tag";
  10600. }
  10601. var ignoreUnderscore = false;
  10602. if (!modeCfg.underscoresBreakWords) {
  10603. if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) {
  10604. var prevPos = stream.pos - 2;
  10605. if (prevPos >= 0) {
  10606. var prevCh = stream.string.charAt(prevPos);
  10607. if (prevCh !== '_' && prevCh.match(/(\w)/, false)) {
  10608. ignoreUnderscore = true;
  10609. }
  10610. }
  10611. }
  10612. }
  10613. if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
  10614. if (sol && stream.peek() === ' ') {
  10615. // Do nothing, surrounded by newline and space
  10616. } else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
  10617. if (modeCfg.highlightFormatting) state.formatting = "strong";
  10618. var t = getType(state);
  10619. state.strong = false;
  10620. return t;
  10621. } else if (!state.strong && stream.eat(ch)) { // Add STRONG
  10622. state.strong = ch;
  10623. if (modeCfg.highlightFormatting) state.formatting = "strong";
  10624. return getType(state);
  10625. } else if (state.em === ch) { // Remove EM
  10626. if (modeCfg.highlightFormatting) state.formatting = "em";
  10627. var t = getType(state);
  10628. state.em = false;
  10629. return t;
  10630. } else if (!state.em) { // Add EM
  10631. state.em = ch;
  10632. if (modeCfg.highlightFormatting) state.formatting = "em";
  10633. return getType(state);
  10634. }
  10635. } else if (ch === ' ') {
  10636. if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
  10637. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  10638. return getType(state);
  10639. } else { // Not surrounded by spaces, back up pointer
  10640. stream.backUp(1);
  10641. }
  10642. }
  10643. }
  10644. if (modeCfg.strikethrough) {
  10645. if (ch === '~' && stream.eatWhile(ch)) {
  10646. if (state.strikethrough) {// Remove strikethrough
  10647. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  10648. var t = getType(state);
  10649. state.strikethrough = false;
  10650. return t;
  10651. } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
  10652. state.strikethrough = true;
  10653. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  10654. return getType(state);
  10655. }
  10656. } else if (ch === ' ') {
  10657. if (stream.match(/^~~/, true)) { // Probably surrounded by space
  10658. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  10659. return getType(state);
  10660. } else { // Not surrounded by spaces, back up pointer
  10661. stream.backUp(2);
  10662. }
  10663. }
  10664. }
  10665. }
  10666. if (ch === ' ') {
  10667. if (stream.match(/ +$/, false)) {
  10668. state.trailingSpace++;
  10669. } else if (state.trailingSpace) {
  10670. state.trailingSpaceNewLine = true;
  10671. }
  10672. }
  10673. return getType(state);
  10674. }
  10675. function linkInline(stream, state) {
  10676. var ch = stream.next();
  10677. if (ch === ">") {
  10678. state.f = state.inline = inlineNormal;
  10679. if (modeCfg.highlightFormatting) state.formatting = "link";
  10680. var type = getType(state);
  10681. if (type){
  10682. type += " ";
  10683. } else {
  10684. type = "";
  10685. }
  10686. return type + tokenTypes.linkInline;
  10687. }
  10688. stream.match(/^[^>]+/, true);
  10689. return tokenTypes.linkInline;
  10690. }
  10691. function linkHref(stream, state) {
  10692. // Check if space, and return NULL if so (to avoid marking the space)
  10693. if(stream.eatSpace()){
  10694. return null;
  10695. }
  10696. var ch = stream.next();
  10697. if (ch === '(' || ch === '[') {
  10698. state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]", 0);
  10699. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  10700. state.linkHref = true;
  10701. return getType(state);
  10702. }
  10703. return 'error';
  10704. }
  10705. var linkRE = {
  10706. ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
  10707. "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/
  10708. }
  10709. function getLinkHrefInside(endChar) {
  10710. return function(stream, state) {
  10711. var ch = stream.next();
  10712. if (ch === endChar) {
  10713. state.f = state.inline = inlineNormal;
  10714. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  10715. var returnState = getType(state);
  10716. state.linkHref = false;
  10717. return returnState;
  10718. }
  10719. stream.match(linkRE[endChar])
  10720. state.linkHref = true;
  10721. return getType(state);
  10722. };
  10723. }
  10724. function footnoteLink(stream, state) {
  10725. if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
  10726. state.f = footnoteLinkInside;
  10727. stream.next(); // Consume [
  10728. if (modeCfg.highlightFormatting) state.formatting = "link";
  10729. state.linkText = true;
  10730. return getType(state);
  10731. }
  10732. return switchInline(stream, state, inlineNormal);
  10733. }
  10734. function footnoteLinkInside(stream, state) {
  10735. if (stream.match(/^\]:/, true)) {
  10736. state.f = state.inline = footnoteUrl;
  10737. if (modeCfg.highlightFormatting) state.formatting = "link";
  10738. var returnType = getType(state);
  10739. state.linkText = false;
  10740. return returnType;
  10741. }
  10742. stream.match(/^([^\]\\]|\\.)+/, true);
  10743. return tokenTypes.linkText;
  10744. }
  10745. function footnoteUrl(stream, state) {
  10746. // Check if space, and return NULL if so (to avoid marking the space)
  10747. if(stream.eatSpace()){
  10748. return null;
  10749. }
  10750. // Match URL
  10751. stream.match(/^[^\s]+/, true);
  10752. // Check for link title
  10753. if (stream.peek() === undefined) { // End of line, set flag to check next line
  10754. state.linkTitle = true;
  10755. } else { // More content on line, check if link title
  10756. stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
  10757. }
  10758. state.f = state.inline = inlineNormal;
  10759. return tokenTypes.linkHref + " url";
  10760. }
  10761. var mode = {
  10762. startState: function() {
  10763. return {
  10764. f: blockNormal,
  10765. prevLine: null,
  10766. thisLine: null,
  10767. block: blockNormal,
  10768. htmlState: null,
  10769. indentation: 0,
  10770. inline: inlineNormal,
  10771. text: handleText,
  10772. formatting: false,
  10773. linkText: false,
  10774. linkHref: false,
  10775. linkTitle: false,
  10776. code: 0,
  10777. em: false,
  10778. strong: false,
  10779. header: 0,
  10780. hr: false,
  10781. taskList: false,
  10782. list: false,
  10783. listStack: [],
  10784. quote: 0,
  10785. trailingSpace: 0,
  10786. trailingSpaceNewLine: false,
  10787. strikethrough: false,
  10788. fencedChars: null
  10789. };
  10790. },
  10791. copyState: function(s) {
  10792. return {
  10793. f: s.f,
  10794. prevLine: s.prevLine,
  10795. thisLine: s.thisLine,
  10796. block: s.block,
  10797. htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
  10798. indentation: s.indentation,
  10799. localMode: s.localMode,
  10800. localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
  10801. inline: s.inline,
  10802. text: s.text,
  10803. formatting: false,
  10804. linkTitle: s.linkTitle,
  10805. code: s.code,
  10806. em: s.em,
  10807. strong: s.strong,
  10808. strikethrough: s.strikethrough,
  10809. header: s.header,
  10810. hr: s.hr,
  10811. taskList: s.taskList,
  10812. list: s.list,
  10813. listStack: s.listStack.slice(0),
  10814. quote: s.quote,
  10815. indentedCode: s.indentedCode,
  10816. trailingSpace: s.trailingSpace,
  10817. trailingSpaceNewLine: s.trailingSpaceNewLine,
  10818. md_inside: s.md_inside,
  10819. fencedChars: s.fencedChars
  10820. };
  10821. },
  10822. token: function(stream, state) {
  10823. // Reset state.formatting
  10824. state.formatting = false;
  10825. if (stream != state.thisLine) {
  10826. var forceBlankLine = state.header || state.hr;
  10827. // Reset state.header and state.hr
  10828. state.header = 0;
  10829. state.hr = false;
  10830. if (stream.match(/^\s*$/, true) || forceBlankLine) {
  10831. blankLine(state);
  10832. if (!forceBlankLine) return null
  10833. state.prevLine = null
  10834. }
  10835. state.prevLine = state.thisLine
  10836. state.thisLine = stream
  10837. // Reset state.taskList
  10838. state.taskList = false;
  10839. // Reset state.trailingSpace
  10840. state.trailingSpace = 0;
  10841. state.trailingSpaceNewLine = false;
  10842. state.f = state.block;
  10843. var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length;
  10844. state.indentationDiff = Math.min(indentation - state.indentation, 4);
  10845. state.indentation = state.indentation + state.indentationDiff;
  10846. if (indentation > 0) return null;
  10847. }
  10848. return state.f(stream, state);
  10849. },
  10850. innerMode: function(state) {
  10851. if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
  10852. if (state.localState) return {state: state.localState, mode: state.localMode};
  10853. return {state: state, mode: mode};
  10854. },
  10855. blankLine: blankLine,
  10856. getType: getType,
  10857. fold: "markdown"
  10858. };
  10859. return mode;
  10860. }, "xml");
  10861. CodeMirror.defineMIME("text/x-markdown", "markdown");
  10862. });
  10863. },{"../../lib/codemirror":10,"../meta":13,"../xml/xml":14}],13:[function(require,module,exports){
  10864. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10865. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10866. (function(mod) {
  10867. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10868. mod(require("../lib/codemirror"));
  10869. else if (typeof define == "function" && define.amd) // AMD
  10870. define(["../lib/codemirror"], mod);
  10871. else // Plain browser env
  10872. mod(CodeMirror);
  10873. })(function(CodeMirror) {
  10874. "use strict";
  10875. CodeMirror.modeInfo = [
  10876. {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
  10877. {name: "PGP", mimes: ["application/pgp", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["pgp"]},
  10878. {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
  10879. {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
  10880. {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
  10881. {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h"]},
  10882. {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
  10883. {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
  10884. {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
  10885. {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
  10886. {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
  10887. {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
  10888. {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
  10889. {name: "CoffeeScript", mime: "text/x-coffeescript", mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
  10890. {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
  10891. {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
  10892. {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
  10893. {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
  10894. {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
  10895. {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
  10896. {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
  10897. {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
  10898. {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
  10899. {name: "Django", mime: "text/x-django", mode: "django"},
  10900. {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
  10901. {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
  10902. {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
  10903. {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
  10904. {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
  10905. {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
  10906. {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
  10907. {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
  10908. {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
  10909. {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
  10910. {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
  10911. {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
  10912. {name: "FCL", mime: "text/x-fcl", mode: "fcl"},
  10913. {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
  10914. {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
  10915. {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
  10916. {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
  10917. {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
  10918. {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
  10919. {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
  10920. {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"]},
  10921. {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
  10922. {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
  10923. {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
  10924. {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
  10925. {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
  10926. {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
  10927. {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm"], alias: ["xhtml"]},
  10928. {name: "HTTP", mime: "message/http", mode: "http"},
  10929. {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
  10930. {name: "Jade", mime: "text/x-jade", mode: "jade", ext: ["jade"]},
  10931. {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
  10932. {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
  10933. {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
  10934. mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
  10935. {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
  10936. {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
  10937. {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
  10938. {name: "Jinja2", mime: "null", mode: "jinja2"},
  10939. {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
  10940. {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
  10941. {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
  10942. {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
  10943. {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
  10944. {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
  10945. {name: "mIRC", mime: "text/mirc", mode: "mirc"},
  10946. {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
  10947. {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
  10948. {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
  10949. {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
  10950. {name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
  10951. {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
  10952. {name: "MySQL", mime: "text/x-mysql", mode: "sql"},
  10953. {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
  10954. {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
  10955. {name: "NTriples", mime: "text/n-triples", mode: "ntriples", ext: ["nt"]},
  10956. {name: "Objective C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
  10957. {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
  10958. {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
  10959. {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
  10960. {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
  10961. {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
  10962. {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
  10963. {name: "PHP", mime: "application/x-httpd-php", mode: "php", ext: ["php", "php3", "php4", "php5", "phtml"]},
  10964. {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
  10965. {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
  10966. {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
  10967. {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
  10968. {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
  10969. {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
  10970. {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
  10971. {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
  10972. {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
  10973. {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r"], alias: ["rscript"]},
  10974. {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
  10975. {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
  10976. {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
  10977. {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
  10978. {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
  10979. {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
  10980. {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
  10981. {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
  10982. {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
  10983. {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
  10984. {name: "Shell", mime: "text/x-sh", mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
  10985. {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
  10986. {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
  10987. {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
  10988. {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
  10989. {name: "Solr", mime: "text/x-solr", mode: "solr"},
  10990. {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
  10991. {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
  10992. {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
  10993. {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
  10994. {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
  10995. {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
  10996. {name: "sTeX", mime: "text/x-stex", mode: "stex"},
  10997. {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx"], alias: ["tex"]},
  10998. {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v"]},
  10999. {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
  11000. {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
  11001. {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
  11002. {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
  11003. {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
  11004. {name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
  11005. {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
  11006. {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
  11007. {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
  11008. {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
  11009. {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
  11010. {name: "Twig", mime: "text/x-twig", mode: "twig"},
  11011. {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
  11012. {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
  11013. {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
  11014. {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
  11015. {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
  11016. {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
  11017. {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd"], alias: ["rss", "wsdl", "xsd"]},
  11018. {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
  11019. {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
  11020. {name: "YAML", mime: "text/x-yaml", mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
  11021. {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
  11022. {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
  11023. {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
  11024. {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
  11025. ];
  11026. // Ensure all modes have a mime property for backwards compatibility
  11027. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11028. var info = CodeMirror.modeInfo[i];
  11029. if (info.mimes) info.mime = info.mimes[0];
  11030. }
  11031. CodeMirror.findModeByMIME = function(mime) {
  11032. mime = mime.toLowerCase();
  11033. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11034. var info = CodeMirror.modeInfo[i];
  11035. if (info.mime == mime) return info;
  11036. if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
  11037. if (info.mimes[j] == mime) return info;
  11038. }
  11039. };
  11040. CodeMirror.findModeByExtension = function(ext) {
  11041. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11042. var info = CodeMirror.modeInfo[i];
  11043. if (info.ext) for (var j = 0; j < info.ext.length; j++)
  11044. if (info.ext[j] == ext) return info;
  11045. }
  11046. };
  11047. CodeMirror.findModeByFileName = function(filename) {
  11048. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11049. var info = CodeMirror.modeInfo[i];
  11050. if (info.file && info.file.test(filename)) return info;
  11051. }
  11052. var dot = filename.lastIndexOf(".");
  11053. var ext = dot > -1 && filename.substring(dot + 1, filename.length);
  11054. if (ext) return CodeMirror.findModeByExtension(ext);
  11055. };
  11056. CodeMirror.findModeByName = function(name) {
  11057. name = name.toLowerCase();
  11058. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11059. var info = CodeMirror.modeInfo[i];
  11060. if (info.name.toLowerCase() == name) return info;
  11061. if (info.alias) for (var j = 0; j < info.alias.length; j++)
  11062. if (info.alias[j].toLowerCase() == name) return info;
  11063. }
  11064. };
  11065. });
  11066. },{"../lib/codemirror":10}],14:[function(require,module,exports){
  11067. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11068. // Distributed under an MIT license: http://codemirror.net/LICENSE
  11069. (function(mod) {
  11070. if (typeof exports == "object" && typeof module == "object") // CommonJS
  11071. mod(require("../../lib/codemirror"));
  11072. else if (typeof define == "function" && define.amd) // AMD
  11073. define(["../../lib/codemirror"], mod);
  11074. else // Plain browser env
  11075. mod(CodeMirror);
  11076. })(function(CodeMirror) {
  11077. "use strict";
  11078. var htmlConfig = {
  11079. autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
  11080. 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
  11081. 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
  11082. 'track': true, 'wbr': true, 'menuitem': true},
  11083. implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
  11084. 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
  11085. 'th': true, 'tr': true},
  11086. contextGrabbers: {
  11087. 'dd': {'dd': true, 'dt': true},
  11088. 'dt': {'dd': true, 'dt': true},
  11089. 'li': {'li': true},
  11090. 'option': {'option': true, 'optgroup': true},
  11091. 'optgroup': {'optgroup': true},
  11092. 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
  11093. 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
  11094. 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
  11095. 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
  11096. 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
  11097. 'rp': {'rp': true, 'rt': true},
  11098. 'rt': {'rp': true, 'rt': true},
  11099. 'tbody': {'tbody': true, 'tfoot': true},
  11100. 'td': {'td': true, 'th': true},
  11101. 'tfoot': {'tbody': true},
  11102. 'th': {'td': true, 'th': true},
  11103. 'thead': {'tbody': true, 'tfoot': true},
  11104. 'tr': {'tr': true}
  11105. },
  11106. doNotIndent: {"pre": true},
  11107. allowUnquoted: true,
  11108. allowMissing: true,
  11109. caseFold: true
  11110. }
  11111. var xmlConfig = {
  11112. autoSelfClosers: {},
  11113. implicitlyClosed: {},
  11114. contextGrabbers: {},
  11115. doNotIndent: {},
  11116. allowUnquoted: false,
  11117. allowMissing: false,
  11118. caseFold: false
  11119. }
  11120. CodeMirror.defineMode("xml", function(editorConf, config_) {
  11121. var indentUnit = editorConf.indentUnit
  11122. var config = {}
  11123. var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  11124. for (var prop in defaults) config[prop] = defaults[prop]
  11125. for (var prop in config_) config[prop] = config_[prop]
  11126. // Return variables for tokenizers
  11127. var type, setStyle;
  11128. function inText(stream, state) {
  11129. function chain(parser) {
  11130. state.tokenize = parser;
  11131. return parser(stream, state);
  11132. }
  11133. var ch = stream.next();
  11134. if (ch == "<") {
  11135. if (stream.eat("!")) {
  11136. if (stream.eat("[")) {
  11137. if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
  11138. else return null;
  11139. } else if (stream.match("--")) {
  11140. return chain(inBlock("comment", "-->"));
  11141. } else if (stream.match("DOCTYPE", true, true)) {
  11142. stream.eatWhile(/[\w\._\-]/);
  11143. return chain(doctype(1));
  11144. } else {
  11145. return null;
  11146. }
  11147. } else if (stream.eat("?")) {
  11148. stream.eatWhile(/[\w\._\-]/);
  11149. state.tokenize = inBlock("meta", "?>");
  11150. return "meta";
  11151. } else {
  11152. type = stream.eat("/") ? "closeTag" : "openTag";
  11153. state.tokenize = inTag;
  11154. return "tag bracket";
  11155. }
  11156. } else if (ch == "&") {
  11157. var ok;
  11158. if (stream.eat("#")) {
  11159. if (stream.eat("x")) {
  11160. ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
  11161. } else {
  11162. ok = stream.eatWhile(/[\d]/) && stream.eat(";");
  11163. }
  11164. } else {
  11165. ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
  11166. }
  11167. return ok ? "atom" : "error";
  11168. } else {
  11169. stream.eatWhile(/[^&<]/);
  11170. return null;
  11171. }
  11172. }
  11173. inText.isInText = true;
  11174. function inTag(stream, state) {
  11175. var ch = stream.next();
  11176. if (ch == ">" || (ch == "/" && stream.eat(">"))) {
  11177. state.tokenize = inText;
  11178. type = ch == ">" ? "endTag" : "selfcloseTag";
  11179. return "tag bracket";
  11180. } else if (ch == "=") {
  11181. type = "equals";
  11182. return null;
  11183. } else if (ch == "<") {
  11184. state.tokenize = inText;
  11185. state.state = baseState;
  11186. state.tagName = state.tagStart = null;
  11187. var next = state.tokenize(stream, state);
  11188. return next ? next + " tag error" : "tag error";
  11189. } else if (/[\'\"]/.test(ch)) {
  11190. state.tokenize = inAttribute(ch);
  11191. state.stringStartCol = stream.column();
  11192. return state.tokenize(stream, state);
  11193. } else {
  11194. stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
  11195. return "word";
  11196. }
  11197. }
  11198. function inAttribute(quote) {
  11199. var closure = function(stream, state) {
  11200. while (!stream.eol()) {
  11201. if (stream.next() == quote) {
  11202. state.tokenize = inTag;
  11203. break;
  11204. }
  11205. }
  11206. return "string";
  11207. };
  11208. closure.isInAttribute = true;
  11209. return closure;
  11210. }
  11211. function inBlock(style, terminator) {
  11212. return function(stream, state) {
  11213. while (!stream.eol()) {
  11214. if (stream.match(terminator)) {
  11215. state.tokenize = inText;
  11216. break;
  11217. }
  11218. stream.next();
  11219. }
  11220. return style;
  11221. };
  11222. }
  11223. function doctype(depth) {
  11224. return function(stream, state) {
  11225. var ch;
  11226. while ((ch = stream.next()) != null) {
  11227. if (ch == "<") {
  11228. state.tokenize = doctype(depth + 1);
  11229. return state.tokenize(stream, state);
  11230. } else if (ch == ">") {
  11231. if (depth == 1) {
  11232. state.tokenize = inText;
  11233. break;
  11234. } else {
  11235. state.tokenize = doctype(depth - 1);
  11236. return state.tokenize(stream, state);
  11237. }
  11238. }
  11239. }
  11240. return "meta";
  11241. };
  11242. }
  11243. function Context(state, tagName, startOfLine) {
  11244. this.prev = state.context;
  11245. this.tagName = tagName;
  11246. this.indent = state.indented;
  11247. this.startOfLine = startOfLine;
  11248. if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
  11249. this.noIndent = true;
  11250. }
  11251. function popContext(state) {
  11252. if (state.context) state.context = state.context.prev;
  11253. }
  11254. function maybePopContext(state, nextTagName) {
  11255. var parentTagName;
  11256. while (true) {
  11257. if (!state.context) {
  11258. return;
  11259. }
  11260. parentTagName = state.context.tagName;
  11261. if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
  11262. !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
  11263. return;
  11264. }
  11265. popContext(state);
  11266. }
  11267. }
  11268. function baseState(type, stream, state) {
  11269. if (type == "openTag") {
  11270. state.tagStart = stream.column();
  11271. return tagNameState;
  11272. } else if (type == "closeTag") {
  11273. return closeTagNameState;
  11274. } else {
  11275. return baseState;
  11276. }
  11277. }
  11278. function tagNameState(type, stream, state) {
  11279. if (type == "word") {
  11280. state.tagName = stream.current();
  11281. setStyle = "tag";
  11282. return attrState;
  11283. } else {
  11284. setStyle = "error";
  11285. return tagNameState;
  11286. }
  11287. }
  11288. function closeTagNameState(type, stream, state) {
  11289. if (type == "word") {
  11290. var tagName = stream.current();
  11291. if (state.context && state.context.tagName != tagName &&
  11292. config.implicitlyClosed.hasOwnProperty(state.context.tagName))
  11293. popContext(state);
  11294. if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
  11295. setStyle = "tag";
  11296. return closeState;
  11297. } else {
  11298. setStyle = "tag error";
  11299. return closeStateErr;
  11300. }
  11301. } else {
  11302. setStyle = "error";
  11303. return closeStateErr;
  11304. }
  11305. }
  11306. function closeState(type, _stream, state) {
  11307. if (type != "endTag") {
  11308. setStyle = "error";
  11309. return closeState;
  11310. }
  11311. popContext(state);
  11312. return baseState;
  11313. }
  11314. function closeStateErr(type, stream, state) {
  11315. setStyle = "error";
  11316. return closeState(type, stream, state);
  11317. }
  11318. function attrState(type, _stream, state) {
  11319. if (type == "word") {
  11320. setStyle = "attribute";
  11321. return attrEqState;
  11322. } else if (type == "endTag" || type == "selfcloseTag") {
  11323. var tagName = state.tagName, tagStart = state.tagStart;
  11324. state.tagName = state.tagStart = null;
  11325. if (type == "selfcloseTag" ||
  11326. config.autoSelfClosers.hasOwnProperty(tagName)) {
  11327. maybePopContext(state, tagName);
  11328. } else {
  11329. maybePopContext(state, tagName);
  11330. state.context = new Context(state, tagName, tagStart == state.indented);
  11331. }
  11332. return baseState;
  11333. }
  11334. setStyle = "error";
  11335. return attrState;
  11336. }
  11337. function attrEqState(type, stream, state) {
  11338. if (type == "equals") return attrValueState;
  11339. if (!config.allowMissing) setStyle = "error";
  11340. return attrState(type, stream, state);
  11341. }
  11342. function attrValueState(type, stream, state) {
  11343. if (type == "string") return attrContinuedState;
  11344. if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
  11345. setStyle = "error";
  11346. return attrState(type, stream, state);
  11347. }
  11348. function attrContinuedState(type, stream, state) {
  11349. if (type == "string") return attrContinuedState;
  11350. return attrState(type, stream, state);
  11351. }
  11352. return {
  11353. startState: function(baseIndent) {
  11354. var state = {tokenize: inText,
  11355. state: baseState,
  11356. indented: baseIndent || 0,
  11357. tagName: null, tagStart: null,
  11358. context: null}
  11359. if (baseIndent != null) state.baseIndent = baseIndent
  11360. return state
  11361. },
  11362. token: function(stream, state) {
  11363. if (!state.tagName && stream.sol())
  11364. state.indented = stream.indentation();
  11365. if (stream.eatSpace()) return null;
  11366. type = null;
  11367. var style = state.tokenize(stream, state);
  11368. if ((style || type) && style != "comment") {
  11369. setStyle = null;
  11370. state.state = state.state(type || style, stream, state);
  11371. if (setStyle)
  11372. style = setStyle == "error" ? style + " error" : setStyle;
  11373. }
  11374. return style;
  11375. },
  11376. indent: function(state, textAfter, fullLine) {
  11377. var context = state.context;
  11378. // Indent multi-line strings (e.g. css).
  11379. if (state.tokenize.isInAttribute) {
  11380. if (state.tagStart == state.indented)
  11381. return state.stringStartCol + 1;
  11382. else
  11383. return state.indented + indentUnit;
  11384. }
  11385. if (context && context.noIndent) return CodeMirror.Pass;
  11386. if (state.tokenize != inTag && state.tokenize != inText)
  11387. return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
  11388. // Indent the starts of attribute names.
  11389. if (state.tagName) {
  11390. if (config.multilineTagIndentPastTag !== false)
  11391. return state.tagStart + state.tagName.length + 2;
  11392. else
  11393. return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
  11394. }
  11395. if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
  11396. var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
  11397. if (tagAfter && tagAfter[1]) { // Closing tag spotted
  11398. while (context) {
  11399. if (context.tagName == tagAfter[2]) {
  11400. context = context.prev;
  11401. break;
  11402. } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
  11403. context = context.prev;
  11404. } else {
  11405. break;
  11406. }
  11407. }
  11408. } else if (tagAfter) { // Opening tag spotted
  11409. while (context) {
  11410. var grabbers = config.contextGrabbers[context.tagName];
  11411. if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
  11412. context = context.prev;
  11413. else
  11414. break;
  11415. }
  11416. }
  11417. while (context && context.prev && !context.startOfLine)
  11418. context = context.prev;
  11419. if (context) return context.indent + indentUnit;
  11420. else return state.baseIndent || 0;
  11421. },
  11422. electricInput: /<\/[\s\w:]+>$/,
  11423. blockCommentStart: "<!--",
  11424. blockCommentEnd: "-->",
  11425. configuration: config.htmlMode ? "html" : "xml",
  11426. helperType: config.htmlMode ? "html" : "xml",
  11427. skipAttribute: function(state) {
  11428. if (state.state == attrValueState)
  11429. state.state = attrState
  11430. }
  11431. };
  11432. });
  11433. CodeMirror.defineMIME("text/xml", "xml");
  11434. CodeMirror.defineMIME("application/xml", "xml");
  11435. if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  11436. CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
  11437. });
  11438. },{"../../lib/codemirror":10}],15:[function(require,module,exports){
  11439. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  11440. var e, m
  11441. var eLen = nBytes * 8 - mLen - 1
  11442. var eMax = (1 << eLen) - 1
  11443. var eBias = eMax >> 1
  11444. var nBits = -7
  11445. var i = isLE ? (nBytes - 1) : 0
  11446. var d = isLE ? -1 : 1
  11447. var s = buffer[offset + i]
  11448. i += d
  11449. e = s & ((1 << (-nBits)) - 1)
  11450. s >>= (-nBits)
  11451. nBits += eLen
  11452. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  11453. m = e & ((1 << (-nBits)) - 1)
  11454. e >>= (-nBits)
  11455. nBits += mLen
  11456. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  11457. if (e === 0) {
  11458. e = 1 - eBias
  11459. } else if (e === eMax) {
  11460. return m ? NaN : ((s ? -1 : 1) * Infinity)
  11461. } else {
  11462. m = m + Math.pow(2, mLen)
  11463. e = e - eBias
  11464. }
  11465. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  11466. }
  11467. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  11468. var e, m, c
  11469. var eLen = nBytes * 8 - mLen - 1
  11470. var eMax = (1 << eLen) - 1
  11471. var eBias = eMax >> 1
  11472. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  11473. var i = isLE ? 0 : (nBytes - 1)
  11474. var d = isLE ? 1 : -1
  11475. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  11476. value = Math.abs(value)
  11477. if (isNaN(value) || value === Infinity) {
  11478. m = isNaN(value) ? 1 : 0
  11479. e = eMax
  11480. } else {
  11481. e = Math.floor(Math.log(value) / Math.LN2)
  11482. if (value * (c = Math.pow(2, -e)) < 1) {
  11483. e--
  11484. c *= 2
  11485. }
  11486. if (e + eBias >= 1) {
  11487. value += rt / c
  11488. } else {
  11489. value += rt * Math.pow(2, 1 - eBias)
  11490. }
  11491. if (value * c >= 2) {
  11492. e++
  11493. c /= 2
  11494. }
  11495. if (e + eBias >= eMax) {
  11496. m = 0
  11497. e = eMax
  11498. } else if (e + eBias >= 1) {
  11499. m = (value * c - 1) * Math.pow(2, mLen)
  11500. e = e + eBias
  11501. } else {
  11502. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  11503. e = 0
  11504. }
  11505. }
  11506. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  11507. e = (e << mLen) | m
  11508. eLen += mLen
  11509. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  11510. buffer[offset + i - d] |= s * 128
  11511. }
  11512. },{}],16:[function(require,module,exports){
  11513. var toString = {}.toString;
  11514. module.exports = Array.isArray || function (arr) {
  11515. return toString.call(arr) == '[object Array]';
  11516. };
  11517. },{}],17:[function(require,module,exports){
  11518. (function (global){
  11519. /**
  11520. * marked - a markdown parser
  11521. * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
  11522. * https://github.com/chjj/marked
  11523. */
  11524. ;(function() {
  11525. /**
  11526. * Block-Level Grammar
  11527. */
  11528. var block = {
  11529. newline: /^\n+/,
  11530. code: /^( {4}[^\n]+\n*)+/,
  11531. fences: noop,
  11532. hr: /^( *[-*_]){3,} *(?:\n+|$)/,
  11533. heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
  11534. nptable: noop,
  11535. lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  11536. blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  11537. list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  11538. html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  11539. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
  11540. table: noop,
  11541. paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
  11542. text: /^[^\n]+/
  11543. };
  11544. block.bullet = /(?:[*+-]|\d+\.)/;
  11545. block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
  11546. block.item = replace(block.item, 'gm')
  11547. (/bull/g, block.bullet)
  11548. ();
  11549. block.list = replace(block.list)
  11550. (/bull/g, block.bullet)
  11551. ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  11552. ('def', '\\n+(?=' + block.def.source + ')')
  11553. ();
  11554. block.blockquote = replace(block.blockquote)
  11555. ('def', block.def)
  11556. ();
  11557. block._tag = '(?!(?:'
  11558. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  11559. + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  11560. + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
  11561. block.html = replace(block.html)
  11562. ('comment', /<!--[\s\S]*?-->/)
  11563. ('closed', /<(tag)[\s\S]+?<\/\1>/)
  11564. ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  11565. (/tag/g, block._tag)
  11566. ();
  11567. block.paragraph = replace(block.paragraph)
  11568. ('hr', block.hr)
  11569. ('heading', block.heading)
  11570. ('lheading', block.lheading)
  11571. ('blockquote', block.blockquote)
  11572. ('tag', '<' + block._tag)
  11573. ('def', block.def)
  11574. ();
  11575. /**
  11576. * Normal Block Grammar
  11577. */
  11578. block.normal = merge({}, block);
  11579. /**
  11580. * GFM Block Grammar
  11581. */
  11582. block.gfm = merge({}, block.normal, {
  11583. fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
  11584. paragraph: /^/,
  11585. heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
  11586. });
  11587. block.gfm.paragraph = replace(block.paragraph)
  11588. ('(?!', '(?!'
  11589. + block.gfm.fences.source.replace('\\1', '\\2') + '|'
  11590. + block.list.source.replace('\\1', '\\3') + '|')
  11591. ();
  11592. /**
  11593. * GFM + Tables Block Grammar
  11594. */
  11595. block.tables = merge({}, block.gfm, {
  11596. nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  11597. table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
  11598. });
  11599. /**
  11600. * Block Lexer
  11601. */
  11602. function Lexer(options) {
  11603. this.tokens = [];
  11604. this.tokens.links = {};
  11605. this.options = options || marked.defaults;
  11606. this.rules = block.normal;
  11607. if (this.options.gfm) {
  11608. if (this.options.tables) {
  11609. this.rules = block.tables;
  11610. } else {
  11611. this.rules = block.gfm;
  11612. }
  11613. }
  11614. }
  11615. /**
  11616. * Expose Block Rules
  11617. */
  11618. Lexer.rules = block;
  11619. /**
  11620. * Static Lex Method
  11621. */
  11622. Lexer.lex = function(src, options) {
  11623. var lexer = new Lexer(options);
  11624. return lexer.lex(src);
  11625. };
  11626. /**
  11627. * Preprocessing
  11628. */
  11629. Lexer.prototype.lex = function(src) {
  11630. src = src
  11631. .replace(/\r\n|\r/g, '\n')
  11632. .replace(/\t/g, ' ')
  11633. .replace(/\u00a0/g, ' ')
  11634. .replace(/\u2424/g, '\n');
  11635. return this.token(src, true);
  11636. };
  11637. /**
  11638. * Lexing
  11639. */
  11640. Lexer.prototype.token = function(src, top, bq) {
  11641. var src = src.replace(/^ +$/gm, '')
  11642. , next
  11643. , loose
  11644. , cap
  11645. , bull
  11646. , b
  11647. , item
  11648. , space
  11649. , i
  11650. , l;
  11651. while (src) {
  11652. // newline
  11653. if (cap = this.rules.newline.exec(src)) {
  11654. src = src.substring(cap[0].length);
  11655. if (cap[0].length > 1) {
  11656. this.tokens.push({
  11657. type: 'space'
  11658. });
  11659. }
  11660. }
  11661. // code
  11662. if (cap = this.rules.code.exec(src)) {
  11663. src = src.substring(cap[0].length);
  11664. cap = cap[0].replace(/^ {4}/gm, '');
  11665. this.tokens.push({
  11666. type: 'code',
  11667. text: !this.options.pedantic
  11668. ? cap.replace(/\n+$/, '')
  11669. : cap
  11670. });
  11671. continue;
  11672. }
  11673. // fences (gfm)
  11674. if (cap = this.rules.fences.exec(src)) {
  11675. src = src.substring(cap[0].length);
  11676. this.tokens.push({
  11677. type: 'code',
  11678. lang: cap[2],
  11679. text: cap[3] || ''
  11680. });
  11681. continue;
  11682. }
  11683. // heading
  11684. if (cap = this.rules.heading.exec(src)) {
  11685. src = src.substring(cap[0].length);
  11686. this.tokens.push({
  11687. type: 'heading',
  11688. depth: cap[1].length,
  11689. text: cap[2]
  11690. });
  11691. continue;
  11692. }
  11693. // table no leading pipe (gfm)
  11694. if (top && (cap = this.rules.nptable.exec(src))) {
  11695. src = src.substring(cap[0].length);
  11696. item = {
  11697. type: 'table',
  11698. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  11699. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  11700. cells: cap[3].replace(/\n$/, '').split('\n')
  11701. };
  11702. for (i = 0; i < item.align.length; i++) {
  11703. if (/^ *-+: *$/.test(item.align[i])) {
  11704. item.align[i] = 'right';
  11705. } else if (/^ *:-+: *$/.test(item.align[i])) {
  11706. item.align[i] = 'center';
  11707. } else if (/^ *:-+ *$/.test(item.align[i])) {
  11708. item.align[i] = 'left';
  11709. } else {
  11710. item.align[i] = null;
  11711. }
  11712. }
  11713. for (i = 0; i < item.cells.length; i++) {
  11714. item.cells[i] = item.cells[i].split(/ *\| */);
  11715. }
  11716. this.tokens.push(item);
  11717. continue;
  11718. }
  11719. // lheading
  11720. if (cap = this.rules.lheading.exec(src)) {
  11721. src = src.substring(cap[0].length);
  11722. this.tokens.push({
  11723. type: 'heading',
  11724. depth: cap[2] === '=' ? 1 : 2,
  11725. text: cap[1]
  11726. });
  11727. continue;
  11728. }
  11729. // hr
  11730. if (cap = this.rules.hr.exec(src)) {
  11731. src = src.substring(cap[0].length);
  11732. this.tokens.push({
  11733. type: 'hr'
  11734. });
  11735. continue;
  11736. }
  11737. // blockquote
  11738. if (cap = this.rules.blockquote.exec(src)) {
  11739. src = src.substring(cap[0].length);
  11740. this.tokens.push({
  11741. type: 'blockquote_start'
  11742. });
  11743. cap = cap[0].replace(/^ *> ?/gm, '');
  11744. // Pass `top` to keep the current
  11745. // "toplevel" state. This is exactly
  11746. // how markdown.pl works.
  11747. this.token(cap, top, true);
  11748. this.tokens.push({
  11749. type: 'blockquote_end'
  11750. });
  11751. continue;
  11752. }
  11753. // list
  11754. if (cap = this.rules.list.exec(src)) {
  11755. src = src.substring(cap[0].length);
  11756. bull = cap[2];
  11757. this.tokens.push({
  11758. type: 'list_start',
  11759. ordered: bull.length > 1
  11760. });
  11761. // Get each top-level item.
  11762. cap = cap[0].match(this.rules.item);
  11763. next = false;
  11764. l = cap.length;
  11765. i = 0;
  11766. for (; i < l; i++) {
  11767. item = cap[i];
  11768. // Remove the list item's bullet
  11769. // so it is seen as the next token.
  11770. space = item.length;
  11771. item = item.replace(/^ *([*+-]|\d+\.) +/, '');
  11772. // Outdent whatever the
  11773. // list item contains. Hacky.
  11774. if (~item.indexOf('\n ')) {
  11775. space -= item.length;
  11776. item = !this.options.pedantic
  11777. ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
  11778. : item.replace(/^ {1,4}/gm, '');
  11779. }
  11780. // Determine whether the next list item belongs here.
  11781. // Backpedal if it does not belong in this list.
  11782. if (this.options.smartLists && i !== l - 1) {
  11783. b = block.bullet.exec(cap[i + 1])[0];
  11784. if (bull !== b && !(bull.length > 1 && b.length > 1)) {
  11785. src = cap.slice(i + 1).join('\n') + src;
  11786. i = l - 1;
  11787. }
  11788. }
  11789. // Determine whether item is loose or not.
  11790. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
  11791. // for discount behavior.
  11792. loose = next || /\n\n(?!\s*$)/.test(item);
  11793. if (i !== l - 1) {
  11794. next = item.charAt(item.length - 1) === '\n';
  11795. if (!loose) loose = next;
  11796. }
  11797. this.tokens.push({
  11798. type: loose
  11799. ? 'loose_item_start'
  11800. : 'list_item_start'
  11801. });
  11802. // Recurse.
  11803. this.token(item, false, bq);
  11804. this.tokens.push({
  11805. type: 'list_item_end'
  11806. });
  11807. }
  11808. this.tokens.push({
  11809. type: 'list_end'
  11810. });
  11811. continue;
  11812. }
  11813. // html
  11814. if (cap = this.rules.html.exec(src)) {
  11815. src = src.substring(cap[0].length);
  11816. this.tokens.push({
  11817. type: this.options.sanitize
  11818. ? 'paragraph'
  11819. : 'html',
  11820. pre: !this.options.sanitizer
  11821. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  11822. text: cap[0]
  11823. });
  11824. continue;
  11825. }
  11826. // def
  11827. if ((!bq && top) && (cap = this.rules.def.exec(src))) {
  11828. src = src.substring(cap[0].length);
  11829. this.tokens.links[cap[1].toLowerCase()] = {
  11830. href: cap[2],
  11831. title: cap[3]
  11832. };
  11833. continue;
  11834. }
  11835. // table (gfm)
  11836. if (top && (cap = this.rules.table.exec(src))) {
  11837. src = src.substring(cap[0].length);
  11838. item = {
  11839. type: 'table',
  11840. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  11841. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  11842. cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
  11843. };
  11844. for (i = 0; i < item.align.length; i++) {
  11845. if (/^ *-+: *$/.test(item.align[i])) {
  11846. item.align[i] = 'right';
  11847. } else if (/^ *:-+: *$/.test(item.align[i])) {
  11848. item.align[i] = 'center';
  11849. } else if (/^ *:-+ *$/.test(item.align[i])) {
  11850. item.align[i] = 'left';
  11851. } else {
  11852. item.align[i] = null;
  11853. }
  11854. }
  11855. for (i = 0; i < item.cells.length; i++) {
  11856. item.cells[i] = item.cells[i]
  11857. .replace(/^ *\| *| *\| *$/g, '')
  11858. .split(/ *\| */);
  11859. }
  11860. this.tokens.push(item);
  11861. continue;
  11862. }
  11863. // top-level paragraph
  11864. if (top && (cap = this.rules.paragraph.exec(src))) {
  11865. src = src.substring(cap[0].length);
  11866. this.tokens.push({
  11867. type: 'paragraph',
  11868. text: cap[1].charAt(cap[1].length - 1) === '\n'
  11869. ? cap[1].slice(0, -1)
  11870. : cap[1]
  11871. });
  11872. continue;
  11873. }
  11874. // text
  11875. if (cap = this.rules.text.exec(src)) {
  11876. // Top-level should never reach here.
  11877. src = src.substring(cap[0].length);
  11878. this.tokens.push({
  11879. type: 'text',
  11880. text: cap[0]
  11881. });
  11882. continue;
  11883. }
  11884. if (src) {
  11885. throw new
  11886. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  11887. }
  11888. }
  11889. return this.tokens;
  11890. };
  11891. /**
  11892. * Inline-Level Grammar
  11893. */
  11894. var inline = {
  11895. escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
  11896. autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  11897. url: noop,
  11898. tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
  11899. link: /^!?\[(inside)\]\(href\)/,
  11900. reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
  11901. nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
  11902. strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
  11903. em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  11904. code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
  11905. br: /^ {2,}\n(?!\s*$)/,
  11906. del: noop,
  11907. text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
  11908. };
  11909. inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
  11910. inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
  11911. inline.link = replace(inline.link)
  11912. ('inside', inline._inside)
  11913. ('href', inline._href)
  11914. ();
  11915. inline.reflink = replace(inline.reflink)
  11916. ('inside', inline._inside)
  11917. ();
  11918. /**
  11919. * Normal Inline Grammar
  11920. */
  11921. inline.normal = merge({}, inline);
  11922. /**
  11923. * Pedantic Inline Grammar
  11924. */
  11925. inline.pedantic = merge({}, inline.normal, {
  11926. strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  11927. em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
  11928. });
  11929. /**
  11930. * GFM Inline Grammar
  11931. */
  11932. inline.gfm = merge({}, inline.normal, {
  11933. escape: replace(inline.escape)('])', '~|])')(),
  11934. url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
  11935. del: /^~~(?=\S)([\s\S]*?\S)~~/,
  11936. text: replace(inline.text)
  11937. (']|', '~]|')
  11938. ('|', '|https?://|')
  11939. ()
  11940. });
  11941. /**
  11942. * GFM + Line Breaks Inline Grammar
  11943. */
  11944. inline.breaks = merge({}, inline.gfm, {
  11945. br: replace(inline.br)('{2,}', '*')(),
  11946. text: replace(inline.gfm.text)('{2,}', '*')()
  11947. });
  11948. /**
  11949. * Inline Lexer & Compiler
  11950. */
  11951. function InlineLexer(links, options) {
  11952. this.options = options || marked.defaults;
  11953. this.links = links;
  11954. this.rules = inline.normal;
  11955. this.renderer = this.options.renderer || new Renderer;
  11956. this.renderer.options = this.options;
  11957. if (!this.links) {
  11958. throw new
  11959. Error('Tokens array requires a `links` property.');
  11960. }
  11961. if (this.options.gfm) {
  11962. if (this.options.breaks) {
  11963. this.rules = inline.breaks;
  11964. } else {
  11965. this.rules = inline.gfm;
  11966. }
  11967. } else if (this.options.pedantic) {
  11968. this.rules = inline.pedantic;
  11969. }
  11970. }
  11971. /**
  11972. * Expose Inline Rules
  11973. */
  11974. InlineLexer.rules = inline;
  11975. /**
  11976. * Static Lexing/Compiling Method
  11977. */
  11978. InlineLexer.output = function(src, links, options) {
  11979. var inline = new InlineLexer(links, options);
  11980. return inline.output(src);
  11981. };
  11982. /**
  11983. * Lexing/Compiling
  11984. */
  11985. InlineLexer.prototype.output = function(src) {
  11986. var out = ''
  11987. , link
  11988. , text
  11989. , href
  11990. , cap;
  11991. while (src) {
  11992. // escape
  11993. if (cap = this.rules.escape.exec(src)) {
  11994. src = src.substring(cap[0].length);
  11995. out += cap[1];
  11996. continue;
  11997. }
  11998. // autolink
  11999. if (cap = this.rules.autolink.exec(src)) {
  12000. src = src.substring(cap[0].length);
  12001. if (cap[2] === '@') {
  12002. text = cap[1].charAt(6) === ':'
  12003. ? this.mangle(cap[1].substring(7))
  12004. : this.mangle(cap[1]);
  12005. href = this.mangle('mailto:') + text;
  12006. } else {
  12007. text = escape(cap[1]);
  12008. href = text;
  12009. }
  12010. out += this.renderer.link(href, null, text);
  12011. continue;
  12012. }
  12013. // url (gfm)
  12014. if (!this.inLink && (cap = this.rules.url.exec(src))) {
  12015. src = src.substring(cap[0].length);
  12016. text = escape(cap[1]);
  12017. href = text;
  12018. out += this.renderer.link(href, null, text);
  12019. continue;
  12020. }
  12021. // tag
  12022. if (cap = this.rules.tag.exec(src)) {
  12023. if (!this.inLink && /^<a /i.test(cap[0])) {
  12024. this.inLink = true;
  12025. } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
  12026. this.inLink = false;
  12027. }
  12028. src = src.substring(cap[0].length);
  12029. out += this.options.sanitize
  12030. ? this.options.sanitizer
  12031. ? this.options.sanitizer(cap[0])
  12032. : escape(cap[0])
  12033. : cap[0]
  12034. continue;
  12035. }
  12036. // link
  12037. if (cap = this.rules.link.exec(src)) {
  12038. src = src.substring(cap[0].length);
  12039. this.inLink = true;
  12040. out += this.outputLink(cap, {
  12041. href: cap[2],
  12042. title: cap[3]
  12043. });
  12044. this.inLink = false;
  12045. continue;
  12046. }
  12047. // reflink, nolink
  12048. if ((cap = this.rules.reflink.exec(src))
  12049. || (cap = this.rules.nolink.exec(src))) {
  12050. src = src.substring(cap[0].length);
  12051. link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  12052. link = this.links[link.toLowerCase()];
  12053. if (!link || !link.href) {
  12054. out += cap[0].charAt(0);
  12055. src = cap[0].substring(1) + src;
  12056. continue;
  12057. }
  12058. this.inLink = true;
  12059. out += this.outputLink(cap, link);
  12060. this.inLink = false;
  12061. continue;
  12062. }
  12063. // strong
  12064. if (cap = this.rules.strong.exec(src)) {
  12065. src = src.substring(cap[0].length);
  12066. out += this.renderer.strong(this.output(cap[2] || cap[1]));
  12067. continue;
  12068. }
  12069. // em
  12070. if (cap = this.rules.em.exec(src)) {
  12071. src = src.substring(cap[0].length);
  12072. out += this.renderer.em(this.output(cap[2] || cap[1]));
  12073. continue;
  12074. }
  12075. // code
  12076. if (cap = this.rules.code.exec(src)) {
  12077. src = src.substring(cap[0].length);
  12078. out += this.renderer.codespan(escape(cap[2], true));
  12079. continue;
  12080. }
  12081. // br
  12082. if (cap = this.rules.br.exec(src)) {
  12083. src = src.substring(cap[0].length);
  12084. out += this.renderer.br();
  12085. continue;
  12086. }
  12087. // del (gfm)
  12088. if (cap = this.rules.del.exec(src)) {
  12089. src = src.substring(cap[0].length);
  12090. out += this.renderer.del(this.output(cap[1]));
  12091. continue;
  12092. }
  12093. // text
  12094. if (cap = this.rules.text.exec(src)) {
  12095. src = src.substring(cap[0].length);
  12096. out += this.renderer.text(escape(this.smartypants(cap[0])));
  12097. continue;
  12098. }
  12099. if (src) {
  12100. throw new
  12101. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  12102. }
  12103. }
  12104. return out;
  12105. };
  12106. /**
  12107. * Compile Link
  12108. */
  12109. InlineLexer.prototype.outputLink = function(cap, link) {
  12110. var href = escape(link.href)
  12111. , title = link.title ? escape(link.title) : null;
  12112. return cap[0].charAt(0) !== '!'
  12113. ? this.renderer.link(href, title, this.output(cap[1]))
  12114. : this.renderer.image(href, title, escape(cap[1]));
  12115. };
  12116. /**
  12117. * Smartypants Transformations
  12118. */
  12119. InlineLexer.prototype.smartypants = function(text) {
  12120. if (!this.options.smartypants) return text;
  12121. return text
  12122. // em-dashes
  12123. .replace(/---/g, '\u2014')
  12124. // en-dashes
  12125. .replace(/--/g, '\u2013')
  12126. // opening singles
  12127. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  12128. // closing singles & apostrophes
  12129. .replace(/'/g, '\u2019')
  12130. // opening doubles
  12131. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  12132. // closing doubles
  12133. .replace(/"/g, '\u201d')
  12134. // ellipses
  12135. .replace(/\.{3}/g, '\u2026');
  12136. };
  12137. /**
  12138. * Mangle Links
  12139. */
  12140. InlineLexer.prototype.mangle = function(text) {
  12141. if (!this.options.mangle) return text;
  12142. var out = ''
  12143. , l = text.length
  12144. , i = 0
  12145. , ch;
  12146. for (; i < l; i++) {
  12147. ch = text.charCodeAt(i);
  12148. if (Math.random() > 0.5) {
  12149. ch = 'x' + ch.toString(16);
  12150. }
  12151. out += '&#' + ch + ';';
  12152. }
  12153. return out;
  12154. };
  12155. /**
  12156. * Renderer
  12157. */
  12158. function Renderer(options) {
  12159. this.options = options || {};
  12160. }
  12161. Renderer.prototype.code = function(code, lang, escaped) {
  12162. if (this.options.highlight) {
  12163. var out = this.options.highlight(code, lang);
  12164. if (out != null && out !== code) {
  12165. escaped = true;
  12166. code = out;
  12167. }
  12168. }
  12169. if (!lang) {
  12170. return '<pre><code>'
  12171. + (escaped ? code : escape(code, true))
  12172. + '\n</code></pre>';
  12173. }
  12174. return '<pre><code class="'
  12175. + this.options.langPrefix
  12176. + escape(lang, true)
  12177. + '">'
  12178. + (escaped ? code : escape(code, true))
  12179. + '\n</code></pre>\n';
  12180. };
  12181. Renderer.prototype.blockquote = function(quote) {
  12182. return '<blockquote>\n' + quote + '</blockquote>\n';
  12183. };
  12184. Renderer.prototype.html = function(html) {
  12185. return html;
  12186. };
  12187. Renderer.prototype.heading = function(text, level, raw) {
  12188. return '<h'
  12189. + level
  12190. + ' id="'
  12191. + this.options.headerPrefix
  12192. + raw.toLowerCase().replace(/[^\w]+/g, '-')
  12193. + '">'
  12194. + text
  12195. + '</h'
  12196. + level
  12197. + '>\n';
  12198. };
  12199. Renderer.prototype.hr = function() {
  12200. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  12201. };
  12202. Renderer.prototype.list = function(body, ordered) {
  12203. var type = ordered ? 'ol' : 'ul';
  12204. return '<' + type + '>\n' + body + '</' + type + '>\n';
  12205. };
  12206. Renderer.prototype.listitem = function(text) {
  12207. return '<li>' + text + '</li>\n';
  12208. };
  12209. Renderer.prototype.paragraph = function(text) {
  12210. return '<p>' + text + '</p>\n';
  12211. };
  12212. Renderer.prototype.table = function(header, body) {
  12213. return '<table>\n'
  12214. + '<thead>\n'
  12215. + header
  12216. + '</thead>\n'
  12217. + '<tbody>\n'
  12218. + body
  12219. + '</tbody>\n'
  12220. + '</table>\n';
  12221. };
  12222. Renderer.prototype.tablerow = function(content) {
  12223. return '<tr>\n' + content + '</tr>\n';
  12224. };
  12225. Renderer.prototype.tablecell = function(content, flags) {
  12226. var type = flags.header ? 'th' : 'td';
  12227. var tag = flags.align
  12228. ? '<' + type + ' style="text-align:' + flags.align + '">'
  12229. : '<' + type + '>';
  12230. return tag + content + '</' + type + '>\n';
  12231. };
  12232. // span level renderer
  12233. Renderer.prototype.strong = function(text) {
  12234. return '<strong>' + text + '</strong>';
  12235. };
  12236. Renderer.prototype.em = function(text) {
  12237. return '<em>' + text + '</em>';
  12238. };
  12239. Renderer.prototype.codespan = function(text) {
  12240. return '<code>' + text + '</code>';
  12241. };
  12242. Renderer.prototype.br = function() {
  12243. return this.options.xhtml ? '<br/>' : '<br>';
  12244. };
  12245. Renderer.prototype.del = function(text) {
  12246. return '<del>' + text + '</del>';
  12247. };
  12248. Renderer.prototype.link = function(href, title, text) {
  12249. if (this.options.sanitize) {
  12250. try {
  12251. var prot = decodeURIComponent(unescape(href))
  12252. .replace(/[^\w:]/g, '')
  12253. .toLowerCase();
  12254. } catch (e) {
  12255. return '';
  12256. }
  12257. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
  12258. return '';
  12259. }
  12260. }
  12261. var out = '<a href="' + href + '"';
  12262. if (title) {
  12263. out += ' title="' + title + '"';
  12264. }
  12265. out += '>' + text + '</a>';
  12266. return out;
  12267. };
  12268. Renderer.prototype.image = function(href, title, text) {
  12269. var out = '<img src="' + href + '" alt="' + text + '"';
  12270. if (title) {
  12271. out += ' title="' + title + '"';
  12272. }
  12273. out += this.options.xhtml ? '/>' : '>';
  12274. return out;
  12275. };
  12276. Renderer.prototype.text = function(text) {
  12277. return text;
  12278. };
  12279. /**
  12280. * Parsing & Compiling
  12281. */
  12282. function Parser(options) {
  12283. this.tokens = [];
  12284. this.token = null;
  12285. this.options = options || marked.defaults;
  12286. this.options.renderer = this.options.renderer || new Renderer;
  12287. this.renderer = this.options.renderer;
  12288. this.renderer.options = this.options;
  12289. }
  12290. /**
  12291. * Static Parse Method
  12292. */
  12293. Parser.parse = function(src, options, renderer) {
  12294. var parser = new Parser(options, renderer);
  12295. return parser.parse(src);
  12296. };
  12297. /**
  12298. * Parse Loop
  12299. */
  12300. Parser.prototype.parse = function(src) {
  12301. this.inline = new InlineLexer(src.links, this.options, this.renderer);
  12302. this.tokens = src.reverse();
  12303. var out = '';
  12304. while (this.next()) {
  12305. out += this.tok();
  12306. }
  12307. return out;
  12308. };
  12309. /**
  12310. * Next Token
  12311. */
  12312. Parser.prototype.next = function() {
  12313. return this.token = this.tokens.pop();
  12314. };
  12315. /**
  12316. * Preview Next Token
  12317. */
  12318. Parser.prototype.peek = function() {
  12319. return this.tokens[this.tokens.length - 1] || 0;
  12320. };
  12321. /**
  12322. * Parse Text Tokens
  12323. */
  12324. Parser.prototype.parseText = function() {
  12325. var body = this.token.text;
  12326. while (this.peek().type === 'text') {
  12327. body += '\n' + this.next().text;
  12328. }
  12329. return this.inline.output(body);
  12330. };
  12331. /**
  12332. * Parse Current Token
  12333. */
  12334. Parser.prototype.tok = function() {
  12335. switch (this.token.type) {
  12336. case 'space': {
  12337. return '';
  12338. }
  12339. case 'hr': {
  12340. return this.renderer.hr();
  12341. }
  12342. case 'heading': {
  12343. return this.renderer.heading(
  12344. this.inline.output(this.token.text),
  12345. this.token.depth,
  12346. this.token.text);
  12347. }
  12348. case 'code': {
  12349. return this.renderer.code(this.token.text,
  12350. this.token.lang,
  12351. this.token.escaped);
  12352. }
  12353. case 'table': {
  12354. var header = ''
  12355. , body = ''
  12356. , i
  12357. , row
  12358. , cell
  12359. , flags
  12360. , j;
  12361. // header
  12362. cell = '';
  12363. for (i = 0; i < this.token.header.length; i++) {
  12364. flags = { header: true, align: this.token.align[i] };
  12365. cell += this.renderer.tablecell(
  12366. this.inline.output(this.token.header[i]),
  12367. { header: true, align: this.token.align[i] }
  12368. );
  12369. }
  12370. header += this.renderer.tablerow(cell);
  12371. for (i = 0; i < this.token.cells.length; i++) {
  12372. row = this.token.cells[i];
  12373. cell = '';
  12374. for (j = 0; j < row.length; j++) {
  12375. cell += this.renderer.tablecell(
  12376. this.inline.output(row[j]),
  12377. { header: false, align: this.token.align[j] }
  12378. );
  12379. }
  12380. body += this.renderer.tablerow(cell);
  12381. }
  12382. return this.renderer.table(header, body);
  12383. }
  12384. case 'blockquote_start': {
  12385. var body = '';
  12386. while (this.next().type !== 'blockquote_end') {
  12387. body += this.tok();
  12388. }
  12389. return this.renderer.blockquote(body);
  12390. }
  12391. case 'list_start': {
  12392. var body = ''
  12393. , ordered = this.token.ordered;
  12394. while (this.next().type !== 'list_end') {
  12395. body += this.tok();
  12396. }
  12397. return this.renderer.list(body, ordered);
  12398. }
  12399. case 'list_item_start': {
  12400. var body = '';
  12401. while (this.next().type !== 'list_item_end') {
  12402. body += this.token.type === 'text'
  12403. ? this.parseText()
  12404. : this.tok();
  12405. }
  12406. return this.renderer.listitem(body);
  12407. }
  12408. case 'loose_item_start': {
  12409. var body = '';
  12410. while (this.next().type !== 'list_item_end') {
  12411. body += this.tok();
  12412. }
  12413. return this.renderer.listitem(body);
  12414. }
  12415. case 'html': {
  12416. var html = !this.token.pre && !this.options.pedantic
  12417. ? this.inline.output(this.token.text)
  12418. : this.token.text;
  12419. return this.renderer.html(html);
  12420. }
  12421. case 'paragraph': {
  12422. return this.renderer.paragraph(this.inline.output(this.token.text));
  12423. }
  12424. case 'text': {
  12425. return this.renderer.paragraph(this.parseText());
  12426. }
  12427. }
  12428. };
  12429. /**
  12430. * Helpers
  12431. */
  12432. function escape(html, encode) {
  12433. return html
  12434. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
  12435. .replace(/</g, '&lt;')
  12436. .replace(/>/g, '&gt;')
  12437. .replace(/"/g, '&quot;')
  12438. .replace(/'/g, '&#39;');
  12439. }
  12440. function unescape(html) {
  12441. return html.replace(/&([#\w]+);/g, function(_, n) {
  12442. n = n.toLowerCase();
  12443. if (n === 'colon') return ':';
  12444. if (n.charAt(0) === '#') {
  12445. return n.charAt(1) === 'x'
  12446. ? String.fromCharCode(parseInt(n.substring(2), 16))
  12447. : String.fromCharCode(+n.substring(1));
  12448. }
  12449. return '';
  12450. });
  12451. }
  12452. function replace(regex, opt) {
  12453. regex = regex.source;
  12454. opt = opt || '';
  12455. return function self(name, val) {
  12456. if (!name) return new RegExp(regex, opt);
  12457. val = val.source || val;
  12458. val = val.replace(/(^|[^\[])\^/g, '$1');
  12459. regex = regex.replace(name, val);
  12460. return self;
  12461. };
  12462. }
  12463. function noop() {}
  12464. noop.exec = noop;
  12465. function merge(obj) {
  12466. var i = 1
  12467. , target
  12468. , key;
  12469. for (; i < arguments.length; i++) {
  12470. target = arguments[i];
  12471. for (key in target) {
  12472. if (Object.prototype.hasOwnProperty.call(target, key)) {
  12473. obj[key] = target[key];
  12474. }
  12475. }
  12476. }
  12477. return obj;
  12478. }
  12479. /**
  12480. * Marked
  12481. */
  12482. function marked(src, opt, callback) {
  12483. if (callback || typeof opt === 'function') {
  12484. if (!callback) {
  12485. callback = opt;
  12486. opt = null;
  12487. }
  12488. opt = merge({}, marked.defaults, opt || {});
  12489. var highlight = opt.highlight
  12490. , tokens
  12491. , pending
  12492. , i = 0;
  12493. try {
  12494. tokens = Lexer.lex(src, opt)
  12495. } catch (e) {
  12496. return callback(e);
  12497. }
  12498. pending = tokens.length;
  12499. var done = function(err) {
  12500. if (err) {
  12501. opt.highlight = highlight;
  12502. return callback(err);
  12503. }
  12504. var out;
  12505. try {
  12506. out = Parser.parse(tokens, opt);
  12507. } catch (e) {
  12508. err = e;
  12509. }
  12510. opt.highlight = highlight;
  12511. return err
  12512. ? callback(err)
  12513. : callback(null, out);
  12514. };
  12515. if (!highlight || highlight.length < 3) {
  12516. return done();
  12517. }
  12518. delete opt.highlight;
  12519. if (!pending) return done();
  12520. for (; i < tokens.length; i++) {
  12521. (function(token) {
  12522. if (token.type !== 'code') {
  12523. return --pending || done();
  12524. }
  12525. return highlight(token.text, token.lang, function(err, code) {
  12526. if (err) return done(err);
  12527. if (code == null || code === token.text) {
  12528. return --pending || done();
  12529. }
  12530. token.text = code;
  12531. token.escaped = true;
  12532. --pending || done();
  12533. });
  12534. })(tokens[i]);
  12535. }
  12536. return;
  12537. }
  12538. try {
  12539. if (opt) opt = merge({}, marked.defaults, opt);
  12540. return Parser.parse(Lexer.lex(src, opt), opt);
  12541. } catch (e) {
  12542. e.message += '\nPlease report this to https://github.com/chjj/marked.';
  12543. if ((opt || marked.defaults).silent) {
  12544. return '<p>An error occured:</p><pre>'
  12545. + escape(e.message + '', true)
  12546. + '</pre>';
  12547. }
  12548. throw e;
  12549. }
  12550. }
  12551. /**
  12552. * Options
  12553. */
  12554. marked.options =
  12555. marked.setOptions = function(opt) {
  12556. merge(marked.defaults, opt);
  12557. return marked;
  12558. };
  12559. marked.defaults = {
  12560. gfm: true,
  12561. tables: true,
  12562. breaks: false,
  12563. pedantic: false,
  12564. sanitize: false,
  12565. sanitizer: null,
  12566. mangle: true,
  12567. smartLists: false,
  12568. silent: false,
  12569. highlight: null,
  12570. langPrefix: 'lang-',
  12571. smartypants: false,
  12572. headerPrefix: '',
  12573. renderer: new Renderer,
  12574. xhtml: false
  12575. };
  12576. /**
  12577. * Expose
  12578. */
  12579. marked.Parser = Parser;
  12580. marked.parser = Parser.parse;
  12581. marked.Renderer = Renderer;
  12582. marked.Lexer = Lexer;
  12583. marked.lexer = Lexer.lex;
  12584. marked.InlineLexer = InlineLexer;
  12585. marked.inlineLexer = InlineLexer.output;
  12586. marked.parse = marked;
  12587. if (typeof module !== 'undefined' && typeof exports === 'object') {
  12588. module.exports = marked;
  12589. } else if (typeof define === 'function' && define.amd) {
  12590. define(function() { return marked; });
  12591. } else {
  12592. this.marked = marked;
  12593. }
  12594. }).call(function() {
  12595. return this || (typeof window !== 'undefined' ? window : global);
  12596. }());
  12597. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12598. },{}],18:[function(require,module,exports){
  12599. (function (Buffer,__dirname){
  12600. 'use strict';
  12601. /**
  12602. * Typo is a JavaScript implementation of a spellchecker using hunspell-style
  12603. * dictionaries.
  12604. */
  12605. /**
  12606. * Typo constructor.
  12607. *
  12608. * @param {String} [dictionary] The locale code of the dictionary being used. e.g.,
  12609. * "en_US". This is only used to auto-load dictionaries.
  12610. * @param {String} [affData] The data from the dictionary's .aff file. If omitted
  12611. * and Typo.js is being used in a Chrome extension, the .aff
  12612. * file will be loaded automatically from
  12613. * lib/typo/dictionaries/[dictionary]/[dictionary].aff
  12614. * In other environments, it will be loaded from
  12615. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].aff
  12616. * @param {String} [wordsData] The data from the dictionary's .dic file. If omitted
  12617. * and Typo.js is being used in a Chrome extension, the .dic
  12618. * file will be loaded automatically from
  12619. * lib/typo/dictionaries/[dictionary]/[dictionary].dic
  12620. * In other environments, it will be loaded from
  12621. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].dic
  12622. * @param {Object} [settings] Constructor settings. Available properties are:
  12623. * {String} [dictionaryPath]: path to load dictionary from in non-chrome
  12624. * environment.
  12625. * {Object} [flags]: flag information.
  12626. *
  12627. *
  12628. * @returns {Typo} A Typo object.
  12629. */
  12630. var Typo = function (dictionary, affData, wordsData, settings) {
  12631. settings = settings || {};
  12632. this.dictionary = null;
  12633. this.rules = {};
  12634. this.dictionaryTable = {};
  12635. this.compoundRules = [];
  12636. this.compoundRuleCodes = {};
  12637. this.replacementTable = [];
  12638. this.flags = settings.flags || {};
  12639. if (dictionary) {
  12640. this.dictionary = dictionary;
  12641. if (typeof window !== 'undefined' && 'chrome' in window && 'extension' in window.chrome && 'getURL' in window.chrome.extension) {
  12642. if (!affData) affData = this._readFile(chrome.extension.getURL("lib/typo/dictionaries/" + dictionary + "/" + dictionary + ".aff"));
  12643. if (!wordsData) wordsData = this._readFile(chrome.extension.getURL("lib/typo/dictionaries/" + dictionary + "/" + dictionary + ".dic"));
  12644. } else {
  12645. if (settings.dictionaryPath) {
  12646. var path = settings.dictionaryPath;
  12647. }
  12648. else if (typeof __dirname !== 'undefined') {
  12649. var path = __dirname + '/dictionaries';
  12650. }
  12651. else {
  12652. var path = './dictionaries';
  12653. }
  12654. if (!affData) affData = this._readFile(path + "/" + dictionary + "/" + dictionary + ".aff");
  12655. if (!wordsData) wordsData = this._readFile(path + "/" + dictionary + "/" + dictionary + ".dic");
  12656. }
  12657. this.rules = this._parseAFF(affData);
  12658. // Save the rule codes that are used in compound rules.
  12659. this.compoundRuleCodes = {};
  12660. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  12661. var rule = this.compoundRules[i];
  12662. for (var j = 0, _jlen = rule.length; j < _jlen; j++) {
  12663. this.compoundRuleCodes[rule[j]] = [];
  12664. }
  12665. }
  12666. // If we add this ONLYINCOMPOUND flag to this.compoundRuleCodes, then _parseDIC
  12667. // will do the work of saving the list of words that are compound-only.
  12668. if ("ONLYINCOMPOUND" in this.flags) {
  12669. this.compoundRuleCodes[this.flags.ONLYINCOMPOUND] = [];
  12670. }
  12671. this.dictionaryTable = this._parseDIC(wordsData);
  12672. // Get rid of any codes from the compound rule codes that are never used
  12673. // (or that were special regex characters). Not especially necessary...
  12674. for (var i in this.compoundRuleCodes) {
  12675. if (this.compoundRuleCodes[i].length == 0) {
  12676. delete this.compoundRuleCodes[i];
  12677. }
  12678. }
  12679. // Build the full regular expressions for each compound rule.
  12680. // I have a feeling (but no confirmation yet) that this method of
  12681. // testing for compound words is probably slow.
  12682. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  12683. var ruleText = this.compoundRules[i];
  12684. var expressionText = "";
  12685. for (var j = 0, _jlen = ruleText.length; j < _jlen; j++) {
  12686. var character = ruleText[j];
  12687. if (character in this.compoundRuleCodes) {
  12688. expressionText += "(" + this.compoundRuleCodes[character].join("|") + ")";
  12689. }
  12690. else {
  12691. expressionText += character;
  12692. }
  12693. }
  12694. this.compoundRules[i] = new RegExp(expressionText, "i");
  12695. }
  12696. }
  12697. return this;
  12698. };
  12699. Typo.prototype = {
  12700. /**
  12701. * Loads a Typo instance from a hash of all of the Typo properties.
  12702. *
  12703. * @param object obj A hash of Typo properties, probably gotten from a JSON.parse(JSON.stringify(typo_instance)).
  12704. */
  12705. load : function (obj) {
  12706. for (var i in obj) {
  12707. this[i] = obj[i];
  12708. }
  12709. return this;
  12710. },
  12711. /**
  12712. * Read the contents of a file.
  12713. *
  12714. * @param {String} path The path (relative) to the file.
  12715. * @param {String} [charset="ISO8859-1"] The expected charset of the file
  12716. * @returns string The file data.
  12717. */
  12718. _readFile : function (path, charset) {
  12719. if (!charset) charset = "utf8";
  12720. if (typeof XMLHttpRequest !== 'undefined') {
  12721. var req = new XMLHttpRequest();
  12722. req.open("GET", path, false);
  12723. if (req.overrideMimeType)
  12724. req.overrideMimeType("text/plain; charset=" + charset);
  12725. req.send(null);
  12726. return req.responseText;
  12727. }
  12728. else if (typeof require !== 'undefined') {
  12729. // Node.js
  12730. var fs = require("fs");
  12731. try {
  12732. if (fs.existsSync(path)) {
  12733. var stats = fs.statSync(path);
  12734. var fileDescriptor = fs.openSync(path, 'r');
  12735. var buffer = new Buffer(stats.size);
  12736. fs.readSync(fileDescriptor, buffer, 0, buffer.length, null);
  12737. return buffer.toString(charset, 0, buffer.length);
  12738. }
  12739. else {
  12740. console.log("Path " + path + " does not exist.");
  12741. }
  12742. } catch (e) {
  12743. console.log(e);
  12744. return '';
  12745. }
  12746. }
  12747. },
  12748. /**
  12749. * Parse the rules out from a .aff file.
  12750. *
  12751. * @param {String} data The contents of the affix file.
  12752. * @returns object The rules from the file.
  12753. */
  12754. _parseAFF : function (data) {
  12755. var rules = {};
  12756. // Remove comment lines
  12757. data = this._removeAffixComments(data);
  12758. var lines = data.split("\n");
  12759. for (var i = 0, _len = lines.length; i < _len; i++) {
  12760. var line = lines[i];
  12761. var definitionParts = line.split(/\s+/);
  12762. var ruleType = definitionParts[0];
  12763. if (ruleType == "PFX" || ruleType == "SFX") {
  12764. var ruleCode = definitionParts[1];
  12765. var combineable = definitionParts[2];
  12766. var numEntries = parseInt(definitionParts[3], 10);
  12767. var entries = [];
  12768. for (var j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12769. var line = lines[j];
  12770. var lineParts = line.split(/\s+/);
  12771. var charactersToRemove = lineParts[2];
  12772. var additionParts = lineParts[3].split("/");
  12773. var charactersToAdd = additionParts[0];
  12774. if (charactersToAdd === "0") charactersToAdd = "";
  12775. var continuationClasses = this.parseRuleCodes(additionParts[1]);
  12776. var regexToMatch = lineParts[4];
  12777. var entry = {};
  12778. entry.add = charactersToAdd;
  12779. if (continuationClasses.length > 0) entry.continuationClasses = continuationClasses;
  12780. if (regexToMatch !== ".") {
  12781. if (ruleType === "SFX") {
  12782. entry.match = new RegExp(regexToMatch + "$");
  12783. }
  12784. else {
  12785. entry.match = new RegExp("^" + regexToMatch);
  12786. }
  12787. }
  12788. if (charactersToRemove != "0") {
  12789. if (ruleType === "SFX") {
  12790. entry.remove = new RegExp(charactersToRemove + "$");
  12791. }
  12792. else {
  12793. entry.remove = charactersToRemove;
  12794. }
  12795. }
  12796. entries.push(entry);
  12797. }
  12798. rules[ruleCode] = { "type" : ruleType, "combineable" : (combineable == "Y"), "entries" : entries };
  12799. i += numEntries;
  12800. }
  12801. else if (ruleType === "COMPOUNDRULE") {
  12802. var numEntries = parseInt(definitionParts[1], 10);
  12803. for (var j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12804. var line = lines[j];
  12805. var lineParts = line.split(/\s+/);
  12806. this.compoundRules.push(lineParts[1]);
  12807. }
  12808. i += numEntries;
  12809. }
  12810. else if (ruleType === "REP") {
  12811. var lineParts = line.split(/\s+/);
  12812. if (lineParts.length === 3) {
  12813. this.replacementTable.push([ lineParts[1], lineParts[2] ]);
  12814. }
  12815. }
  12816. else {
  12817. // ONLYINCOMPOUND
  12818. // COMPOUNDMIN
  12819. // FLAG
  12820. // KEEPCASE
  12821. // NEEDAFFIX
  12822. this.flags[ruleType] = definitionParts[1];
  12823. }
  12824. }
  12825. return rules;
  12826. },
  12827. /**
  12828. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  12829. *
  12830. * @param {String} data The data from an affix file.
  12831. * @return {String} The cleaned-up data.
  12832. */
  12833. _removeAffixComments : function (data) {
  12834. // Remove comments
  12835. data = data.replace(/#.*$/mg, "");
  12836. // Trim each line
  12837. data = data.replace(/^\s\s*/m, '').replace(/\s\s*$/m, '');
  12838. // Remove blank lines.
  12839. data = data.replace(/\n{2,}/g, "\n");
  12840. // Trim the entire string
  12841. data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  12842. return data;
  12843. },
  12844. /**
  12845. * Parses the words out from the .dic file.
  12846. *
  12847. * @param {String} data The data from the dictionary file.
  12848. * @returns object The lookup table containing all of the words and
  12849. * word forms from the dictionary.
  12850. */
  12851. _parseDIC : function (data) {
  12852. data = this._removeDicComments(data);
  12853. var lines = data.split("\n");
  12854. var dictionaryTable = {};
  12855. function addWord(word, rules) {
  12856. // Some dictionaries will list the same word multiple times with different rule sets.
  12857. if (!(word in dictionaryTable) || typeof dictionaryTable[word] != 'object') {
  12858. dictionaryTable[word] = [];
  12859. }
  12860. dictionaryTable[word].push(rules);
  12861. }
  12862. // The first line is the number of words in the dictionary.
  12863. for (var i = 1, _len = lines.length; i < _len; i++) {
  12864. var line = lines[i];
  12865. var parts = line.split("/", 2);
  12866. var word = parts[0];
  12867. // Now for each affix rule, generate that form of the word.
  12868. if (parts.length > 1) {
  12869. var ruleCodesArray = this.parseRuleCodes(parts[1]);
  12870. // Save the ruleCodes for compound word situations.
  12871. if (!("NEEDAFFIX" in this.flags) || ruleCodesArray.indexOf(this.flags.NEEDAFFIX) == -1) {
  12872. addWord(word, ruleCodesArray);
  12873. }
  12874. for (var j = 0, _jlen = ruleCodesArray.length; j < _jlen; j++) {
  12875. var code = ruleCodesArray[j];
  12876. var rule = this.rules[code];
  12877. if (rule) {
  12878. var newWords = this._applyRule(word, rule);
  12879. for (var ii = 0, _iilen = newWords.length; ii < _iilen; ii++) {
  12880. var newWord = newWords[ii];
  12881. addWord(newWord, []);
  12882. if (rule.combineable) {
  12883. for (var k = j + 1; k < _jlen; k++) {
  12884. var combineCode = ruleCodesArray[k];
  12885. var combineRule = this.rules[combineCode];
  12886. if (combineRule) {
  12887. if (combineRule.combineable && (rule.type != combineRule.type)) {
  12888. var otherNewWords = this._applyRule(newWord, combineRule);
  12889. for (var iii = 0, _iiilen = otherNewWords.length; iii < _iiilen; iii++) {
  12890. var otherNewWord = otherNewWords[iii];
  12891. addWord(otherNewWord, []);
  12892. }
  12893. }
  12894. }
  12895. }
  12896. }
  12897. }
  12898. }
  12899. if (code in this.compoundRuleCodes) {
  12900. this.compoundRuleCodes[code].push(word);
  12901. }
  12902. }
  12903. }
  12904. else {
  12905. addWord(word.trim(), []);
  12906. }
  12907. }
  12908. return dictionaryTable;
  12909. },
  12910. /**
  12911. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  12912. *
  12913. * @param {String} data The data from a .dic file.
  12914. * @return {String} The cleaned-up data.
  12915. */
  12916. _removeDicComments : function (data) {
  12917. // I can't find any official documentation on it, but at least the de_DE
  12918. // dictionary uses tab-indented lines as comments.
  12919. // Remove comments
  12920. data = data.replace(/^\t.*$/mg, "");
  12921. return data;
  12922. },
  12923. parseRuleCodes : function (textCodes) {
  12924. if (!textCodes) {
  12925. return [];
  12926. }
  12927. else if (!("FLAG" in this.flags)) {
  12928. return textCodes.split("");
  12929. }
  12930. else if (this.flags.FLAG === "long") {
  12931. var flags = [];
  12932. for (var i = 0, _len = textCodes.length; i < _len; i += 2) {
  12933. flags.push(textCodes.substr(i, 2));
  12934. }
  12935. return flags;
  12936. }
  12937. else if (this.flags.FLAG === "num") {
  12938. return textCode.split(",");
  12939. }
  12940. },
  12941. /**
  12942. * Applies an affix rule to a word.
  12943. *
  12944. * @param {String} word The base word.
  12945. * @param {Object} rule The affix rule.
  12946. * @returns {String[]} The new words generated by the rule.
  12947. */
  12948. _applyRule : function (word, rule) {
  12949. var entries = rule.entries;
  12950. var newWords = [];
  12951. for (var i = 0, _len = entries.length; i < _len; i++) {
  12952. var entry = entries[i];
  12953. if (!entry.match || word.match(entry.match)) {
  12954. var newWord = word;
  12955. if (entry.remove) {
  12956. newWord = newWord.replace(entry.remove, "");
  12957. }
  12958. if (rule.type === "SFX") {
  12959. newWord = newWord + entry.add;
  12960. }
  12961. else {
  12962. newWord = entry.add + newWord;
  12963. }
  12964. newWords.push(newWord);
  12965. if ("continuationClasses" in entry) {
  12966. for (var j = 0, _jlen = entry.continuationClasses.length; j < _jlen; j++) {
  12967. var continuationRule = this.rules[entry.continuationClasses[j]];
  12968. if (continuationRule) {
  12969. newWords = newWords.concat(this._applyRule(newWord, continuationRule));
  12970. }
  12971. /*
  12972. else {
  12973. // This shouldn't happen, but it does, at least in the de_DE dictionary.
  12974. // I think the author mistakenly supplied lower-case rule codes instead
  12975. // of upper-case.
  12976. }
  12977. */
  12978. }
  12979. }
  12980. }
  12981. }
  12982. return newWords;
  12983. },
  12984. /**
  12985. * Checks whether a word or a capitalization variant exists in the current dictionary.
  12986. * The word is trimmed and several variations of capitalizations are checked.
  12987. * If you want to check a word without any changes made to it, call checkExact()
  12988. *
  12989. * @see http://blog.stevenlevithan.com/archives/faster-trim-javascript re:trimming function
  12990. *
  12991. * @param {String} aWord The word to check.
  12992. * @returns {Boolean}
  12993. */
  12994. check : function (aWord) {
  12995. // Remove leading and trailing whitespace
  12996. var trimmedWord = aWord.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  12997. if (this.checkExact(trimmedWord)) {
  12998. return true;
  12999. }
  13000. // The exact word is not in the dictionary.
  13001. if (trimmedWord.toUpperCase() === trimmedWord) {
  13002. // The word was supplied in all uppercase.
  13003. // Check for a capitalized form of the word.
  13004. var capitalizedWord = trimmedWord[0] + trimmedWord.substring(1).toLowerCase();
  13005. if (this.hasFlag(capitalizedWord, "KEEPCASE")) {
  13006. // Capitalization variants are not allowed for this word.
  13007. return false;
  13008. }
  13009. if (this.checkExact(capitalizedWord)) {
  13010. return true;
  13011. }
  13012. }
  13013. var lowercaseWord = trimmedWord.toLowerCase();
  13014. if (lowercaseWord !== trimmedWord) {
  13015. if (this.hasFlag(lowercaseWord, "KEEPCASE")) {
  13016. // Capitalization variants are not allowed for this word.
  13017. return false;
  13018. }
  13019. // Check for a lowercase form
  13020. if (this.checkExact(lowercaseWord)) {
  13021. return true;
  13022. }
  13023. }
  13024. return false;
  13025. },
  13026. /**
  13027. * Checks whether a word exists in the current dictionary.
  13028. *
  13029. * @param {String} word The word to check.
  13030. * @returns {Boolean}
  13031. */
  13032. checkExact : function (word) {
  13033. var ruleCodes = this.dictionaryTable[word];
  13034. if (typeof ruleCodes === 'undefined') {
  13035. // Check if this might be a compound word.
  13036. if ("COMPOUNDMIN" in this.flags && word.length >= this.flags.COMPOUNDMIN) {
  13037. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  13038. if (word.match(this.compoundRules[i])) {
  13039. return true;
  13040. }
  13041. }
  13042. }
  13043. return false;
  13044. }
  13045. else if (typeof ruleCodes === 'object') { // this.dictionary['hasOwnProperty'] will be a function.
  13046. for (var i = 0, _len = ruleCodes.length; i < _len; i++) {
  13047. if (!this.hasFlag(word, "ONLYINCOMPOUND", ruleCodes[i])) {
  13048. return true;
  13049. }
  13050. }
  13051. return false;
  13052. }
  13053. },
  13054. /**
  13055. * Looks up whether a given word is flagged with a given flag.
  13056. *
  13057. * @param {String} word The word in question.
  13058. * @param {String} flag The flag in question.
  13059. * @return {Boolean}
  13060. */
  13061. hasFlag : function (word, flag, wordFlags) {
  13062. if (flag in this.flags) {
  13063. if (typeof wordFlags === 'undefined') {
  13064. var wordFlags = Array.prototype.concat.apply([], this.dictionaryTable[word]);
  13065. }
  13066. if (wordFlags && wordFlags.indexOf(this.flags[flag]) !== -1) {
  13067. return true;
  13068. }
  13069. }
  13070. return false;
  13071. },
  13072. /**
  13073. * Returns a list of suggestions for a misspelled word.
  13074. *
  13075. * @see http://www.norvig.com/spell-correct.html for the basis of this suggestor.
  13076. * This suggestor is primitive, but it works.
  13077. *
  13078. * @param {String} word The misspelling.
  13079. * @param {Number} [limit=5] The maximum number of suggestions to return.
  13080. * @returns {String[]} The array of suggestions.
  13081. */
  13082. alphabet : "",
  13083. suggest : function (word, limit) {
  13084. if (!limit) limit = 5;
  13085. if (this.check(word)) return [];
  13086. // Check the replacement table.
  13087. for (var i = 0, _len = this.replacementTable.length; i < _len; i++) {
  13088. var replacementEntry = this.replacementTable[i];
  13089. if (word.indexOf(replacementEntry[0]) !== -1) {
  13090. var correctedWord = word.replace(replacementEntry[0], replacementEntry[1]);
  13091. if (this.check(correctedWord)) {
  13092. return [ correctedWord ];
  13093. }
  13094. }
  13095. }
  13096. var self = this;
  13097. self.alphabet = "abcdefghijklmnopqrstuvwxyz";
  13098. /*
  13099. if (!self.alphabet) {
  13100. // Use the alphabet as implicitly defined by the words in the dictionary.
  13101. var alphaHash = {};
  13102. for (var i in self.dictionaryTable) {
  13103. for (var j = 0, _len = i.length; j < _len; j++) {
  13104. alphaHash[i[j]] = true;
  13105. }
  13106. }
  13107. for (var i in alphaHash) {
  13108. self.alphabet += i;
  13109. }
  13110. var alphaArray = self.alphabet.split("");
  13111. alphaArray.sort();
  13112. self.alphabet = alphaArray.join("");
  13113. }
  13114. */
  13115. function edits1(words) {
  13116. var rv = [];
  13117. for (var ii = 0, _iilen = words.length; ii < _iilen; ii++) {
  13118. var word = words[ii];
  13119. var splits = [];
  13120. for (var i = 0, _len = word.length + 1; i < _len; i++) {
  13121. splits.push([ word.substring(0, i), word.substring(i, word.length) ]);
  13122. }
  13123. var deletes = [];
  13124. for (var i = 0, _len = splits.length; i < _len; i++) {
  13125. var s = splits[i];
  13126. if (s[1]) {
  13127. deletes.push(s[0] + s[1].substring(1));
  13128. }
  13129. }
  13130. var transposes = [];
  13131. for (var i = 0, _len = splits.length; i < _len; i++) {
  13132. var s = splits[i];
  13133. if (s[1].length > 1) {
  13134. transposes.push(s[0] + s[1][1] + s[1][0] + s[1].substring(2));
  13135. }
  13136. }
  13137. var replaces = [];
  13138. for (var i = 0, _len = splits.length; i < _len; i++) {
  13139. var s = splits[i];
  13140. if (s[1]) {
  13141. for (var j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13142. replaces.push(s[0] + self.alphabet[j] + s[1].substring(1));
  13143. }
  13144. }
  13145. }
  13146. var inserts = [];
  13147. for (var i = 0, _len = splits.length; i < _len; i++) {
  13148. var s = splits[i];
  13149. if (s[1]) {
  13150. for (var j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13151. replaces.push(s[0] + self.alphabet[j] + s[1]);
  13152. }
  13153. }
  13154. }
  13155. rv = rv.concat(deletes);
  13156. rv = rv.concat(transposes);
  13157. rv = rv.concat(replaces);
  13158. rv = rv.concat(inserts);
  13159. }
  13160. return rv;
  13161. }
  13162. function known(words) {
  13163. var rv = [];
  13164. for (var i = 0; i < words.length; i++) {
  13165. if (self.check(words[i])) {
  13166. rv.push(words[i]);
  13167. }
  13168. }
  13169. return rv;
  13170. }
  13171. function correct(word) {
  13172. // Get the edit-distance-1 and edit-distance-2 forms of this word.
  13173. var ed1 = edits1([word]);
  13174. var ed2 = edits1(ed1);
  13175. var corrections = known(ed1).concat(known(ed2));
  13176. // Sort the edits based on how many different ways they were created.
  13177. var weighted_corrections = {};
  13178. for (var i = 0, _len = corrections.length; i < _len; i++) {
  13179. if (!(corrections[i] in weighted_corrections)) {
  13180. weighted_corrections[corrections[i]] = 1;
  13181. }
  13182. else {
  13183. weighted_corrections[corrections[i]] += 1;
  13184. }
  13185. }
  13186. var sorted_corrections = [];
  13187. for (var i in weighted_corrections) {
  13188. sorted_corrections.push([ i, weighted_corrections[i] ]);
  13189. }
  13190. function sorter(a, b) {
  13191. if (a[1] < b[1]) {
  13192. return -1;
  13193. }
  13194. return 1;
  13195. }
  13196. sorted_corrections.sort(sorter).reverse();
  13197. var rv = [];
  13198. for (var i = 0, _len = Math.min(limit, sorted_corrections.length); i < _len; i++) {
  13199. if (!self.hasFlag(sorted_corrections[i][0], "NOSUGGEST")) {
  13200. rv.push(sorted_corrections[i][0]);
  13201. }
  13202. }
  13203. return rv;
  13204. }
  13205. return correct(word);
  13206. }
  13207. };
  13208. // Support for use as a node.js module.
  13209. if (typeof module !== 'undefined') {
  13210. module.exports = Typo;
  13211. }
  13212. }).call(this,require("buffer").Buffer,"/node_modules/typo-js")
  13213. },{"buffer":3,"fs":2}],19:[function(require,module,exports){
  13214. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  13215. // Distributed under an MIT license: http://codemirror.net/LICENSE
  13216. var CodeMirror = require("codemirror");
  13217. CodeMirror.commands.tabAndIndentMarkdownList = function (cm) {
  13218. var ranges = cm.listSelections();
  13219. var pos = ranges[0].head;
  13220. var eolState = cm.getStateAfter(pos.line);
  13221. var inList = eolState.list !== false;
  13222. if (inList) {
  13223. cm.execCommand("indentMore");
  13224. return;
  13225. }
  13226. if (cm.options.indentWithTabs) {
  13227. cm.execCommand("insertTab");
  13228. }
  13229. else {
  13230. var spaces = Array(cm.options.tabSize + 1).join(" ");
  13231. cm.replaceSelection(spaces);
  13232. }
  13233. };
  13234. CodeMirror.commands.shiftTabAndUnindentMarkdownList = function (cm) {
  13235. var ranges = cm.listSelections();
  13236. var pos = ranges[0].head;
  13237. var eolState = cm.getStateAfter(pos.line);
  13238. var inList = eolState.list !== false;
  13239. if (inList) {
  13240. cm.execCommand("indentLess");
  13241. return;
  13242. }
  13243. if (cm.options.indentWithTabs) {
  13244. cm.execCommand("insertTab");
  13245. }
  13246. else {
  13247. var spaces = Array(cm.options.tabSize + 1).join(" ");
  13248. cm.replaceSelection(spaces);
  13249. }
  13250. };
  13251. },{"codemirror":10}],20:[function(require,module,exports){
  13252. /*global require,module*/
  13253. "use strict";
  13254. var CodeMirror = require("codemirror");
  13255. require("codemirror/addon/edit/continuelist.js");
  13256. require("./codemirror/tablist");
  13257. require("codemirror/addon/display/fullscreen.js");
  13258. require("codemirror/mode/markdown/markdown.js");
  13259. require("codemirror/addon/mode/overlay.js");
  13260. require("codemirror/addon/display/placeholder.js");
  13261. require("codemirror/addon/selection/mark-selection.js");
  13262. require("codemirror/mode/gfm/gfm.js");
  13263. require("codemirror/mode/xml/xml.js");
  13264. var CodeMirrorSpellChecker = require("codemirror-spell-checker");
  13265. var marked = require("marked");
  13266. // Some variables
  13267. var isMac = /Mac/.test(navigator.platform);
  13268. // Mapping of actions that can be bound to keyboard shortcuts or toolbar buttons
  13269. var bindings = {
  13270. "toggleBold": toggleBold,
  13271. "toggleItalic": toggleItalic,
  13272. "drawLink": drawLink,
  13273. "toggleHeadingSmaller": toggleHeadingSmaller,
  13274. "toggleHeadingBigger": toggleHeadingBigger,
  13275. "drawImage": drawImage,
  13276. "toggleBlockquote": toggleBlockquote,
  13277. "toggleOrderedList": toggleOrderedList,
  13278. "toggleUnorderedList": toggleUnorderedList,
  13279. "toggleCodeBlock": toggleCodeBlock,
  13280. "togglePreview": togglePreview,
  13281. "toggleStrikethrough": toggleStrikethrough,
  13282. "toggleHeading1": toggleHeading1,
  13283. "toggleHeading2": toggleHeading2,
  13284. "toggleHeading3": toggleHeading3,
  13285. "cleanBlock": cleanBlock,
  13286. "drawTable": drawTable,
  13287. "drawHorizontalRule": drawHorizontalRule,
  13288. "undo": undo,
  13289. "redo": redo,
  13290. "toggleSideBySide": toggleSideBySide,
  13291. "toggleFullScreen": toggleFullScreen
  13292. };
  13293. var shortcuts = {
  13294. "toggleBold": "Cmd-B",
  13295. "toggleItalic": "Cmd-I",
  13296. "drawLink": "Cmd-K",
  13297. "toggleHeadingSmaller": "Cmd-H",
  13298. "toggleHeadingBigger": "Shift-Cmd-H",
  13299. "cleanBlock": "Cmd-E",
  13300. "drawImage": "Cmd-Alt-I",
  13301. "toggleBlockquote": "Cmd-'",
  13302. "toggleOrderedList": "Cmd-Alt-L",
  13303. "toggleUnorderedList": "Cmd-L",
  13304. "toggleCodeBlock": "Cmd-Alt-C",
  13305. "togglePreview": "Cmd-P",
  13306. "toggleSideBySide": "F9",
  13307. "toggleFullScreen": "F11"
  13308. };
  13309. var getBindingName = function(f) {
  13310. for(var key in bindings) {
  13311. if(bindings[key] === f) {
  13312. return key;
  13313. }
  13314. }
  13315. return null;
  13316. };
  13317. var isMobile = function() {
  13318. var check = false;
  13319. (function(a) {
  13320. 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;
  13321. })(navigator.userAgent || navigator.vendor || window.opera);
  13322. return check;
  13323. };
  13324. /**
  13325. * Fix shortcut. Mac use Command, others use Ctrl.
  13326. */
  13327. function fixShortcut(name) {
  13328. if(isMac) {
  13329. name = name.replace("Ctrl", "Cmd");
  13330. } else {
  13331. name = name.replace("Cmd", "Ctrl");
  13332. }
  13333. return name;
  13334. }
  13335. /**
  13336. * Create icon element for toolbar.
  13337. */
  13338. function createIcon(options, enableTooltips, shortcuts) {
  13339. options = options || {};
  13340. var el = document.createElement("a");
  13341. enableTooltips = (enableTooltips == undefined) ? true : enableTooltips;
  13342. if(options.title && enableTooltips) {
  13343. el.title = createTootlip(options.title, options.action, shortcuts);
  13344. if(isMac) {
  13345. el.title = el.title.replace("Ctrl", "⌘");
  13346. el.title = el.title.replace("Alt", "⌥");
  13347. }
  13348. }
  13349. el.tabIndex = -1;
  13350. el.className = options.className;
  13351. return el;
  13352. }
  13353. function createSep() {
  13354. var el = document.createElement("i");
  13355. el.className = "separator";
  13356. el.innerHTML = "|";
  13357. return el;
  13358. }
  13359. function createTootlip(title, action, shortcuts) {
  13360. var actionName;
  13361. var tooltip = title;
  13362. if(action) {
  13363. actionName = getBindingName(action);
  13364. if(shortcuts[actionName]) {
  13365. tooltip += " (" + fixShortcut(shortcuts[actionName]) + ")";
  13366. }
  13367. }
  13368. return tooltip;
  13369. }
  13370. /**
  13371. * The state of CodeMirror at the given position.
  13372. */
  13373. function getState(cm, pos) {
  13374. pos = pos || cm.getCursor("start");
  13375. var stat = cm.getTokenAt(pos);
  13376. if(!stat.type) return {};
  13377. var types = stat.type.split(" ");
  13378. var ret = {},
  13379. data, text;
  13380. for(var i = 0; i < types.length; i++) {
  13381. data = types[i];
  13382. if(data === "strong") {
  13383. ret.bold = true;
  13384. } else if(data === "variable-2") {
  13385. text = cm.getLine(pos.line);
  13386. if(/^\s*\d+\.\s/.test(text)) {
  13387. ret["ordered-list"] = true;
  13388. } else {
  13389. ret["unordered-list"] = true;
  13390. }
  13391. } else if(data === "atom") {
  13392. ret.quote = true;
  13393. } else if(data === "em") {
  13394. ret.italic = true;
  13395. } else if(data === "quote") {
  13396. ret.quote = true;
  13397. } else if(data === "strikethrough") {
  13398. ret.strikethrough = true;
  13399. } else if(data === "comment") {
  13400. ret.code = true;
  13401. } else if(data === "link") {
  13402. ret.link = true;
  13403. } else if(data === "tag") {
  13404. ret.image = true;
  13405. } else if(data.match(/^header(\-[1-6])?$/)) {
  13406. ret[data.replace("header", "heading")] = true;
  13407. }
  13408. }
  13409. return ret;
  13410. }
  13411. // Saved overflow setting
  13412. var saved_overflow = "";
  13413. /**
  13414. * Toggle full screen of the editor.
  13415. */
  13416. function toggleFullScreen(editor) {
  13417. // Set fullscreen
  13418. var cm = editor.codemirror;
  13419. cm.setOption("fullScreen", !cm.getOption("fullScreen"));
  13420. // Prevent scrolling on body during fullscreen active
  13421. if(cm.getOption("fullScreen")) {
  13422. saved_overflow = document.body.style.overflow;
  13423. document.body.style.overflow = "hidden";
  13424. } else {
  13425. document.body.style.overflow = saved_overflow;
  13426. }
  13427. // Update toolbar class
  13428. var wrap = cm.getWrapperElement();
  13429. if(!/fullscreen/.test(wrap.previousSibling.className)) {
  13430. wrap.previousSibling.className += " fullscreen";
  13431. } else {
  13432. wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, "");
  13433. }
  13434. // Update toolbar button
  13435. var toolbarButton = editor.toolbarElements.fullscreen;
  13436. if(!/active/.test(toolbarButton.className)) {
  13437. toolbarButton.className += " active";
  13438. } else {
  13439. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  13440. }
  13441. // Hide side by side if needed
  13442. var sidebyside = cm.getWrapperElement().nextSibling;
  13443. if(/editor-preview-active-side/.test(sidebyside.className))
  13444. toggleSideBySide(editor);
  13445. }
  13446. /**
  13447. * Action for toggling bold.
  13448. */
  13449. function toggleBold(editor) {
  13450. _toggleBlock(editor, "bold", editor.options.blockStyles.bold);
  13451. }
  13452. /**
  13453. * Action for toggling italic.
  13454. */
  13455. function toggleItalic(editor) {
  13456. _toggleBlock(editor, "italic", editor.options.blockStyles.italic);
  13457. }
  13458. /**
  13459. * Action for toggling strikethrough.
  13460. */
  13461. function toggleStrikethrough(editor) {
  13462. _toggleBlock(editor, "strikethrough", "~~");
  13463. }
  13464. /**
  13465. * Action for toggling code block.
  13466. */
  13467. function toggleCodeBlock(editor) {
  13468. var fenceCharsToInsert = editor.options.blockStyles.code;
  13469. function fencing_line(line) {
  13470. /* return true, if this is a ``` or ~~~ line */
  13471. if(typeof line !== "object") {
  13472. throw "fencing_line() takes a 'line' object (not a line number, or line text). Got: " + typeof line + ": " + line;
  13473. }
  13474. return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
  13475. }
  13476. function token_state(token) {
  13477. // base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
  13478. return token.state.base.base || token.state.base;
  13479. }
  13480. function code_type(cm, line_num, line, firstTok, lastTok) {
  13481. /*
  13482. * Return "single", "indented", "fenced" or false
  13483. *
  13484. * cm and line_num are required. Others are optional for efficiency
  13485. * To check in the middle of a line, pass in firstTok yourself.
  13486. */
  13487. line = line || cm.getLineHandle(line_num);
  13488. firstTok = firstTok || cm.getTokenAt({
  13489. line: line_num,
  13490. ch: 1
  13491. });
  13492. lastTok = lastTok || (!!line.text && cm.getTokenAt({
  13493. line: line_num,
  13494. ch: line.text.length - 1
  13495. }));
  13496. var types = firstTok.type ? firstTok.type.split(" ") : [];
  13497. if(lastTok && token_state(lastTok).indentedCode) {
  13498. // have to check last char, since first chars of first line aren"t marked as indented
  13499. return "indented";
  13500. } else if(types.indexOf("comment") === -1) {
  13501. // has to be after "indented" check, since first chars of first indented line aren"t marked as such
  13502. return false;
  13503. } else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
  13504. return "fenced";
  13505. } else {
  13506. return "single";
  13507. }
  13508. }
  13509. function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
  13510. var start_line_sel = cur_start.line + 1,
  13511. end_line_sel = cur_end.line + 1,
  13512. sel_multi = cur_start.line !== cur_end.line,
  13513. repl_start = fenceCharsToInsert + "\n",
  13514. repl_end = "\n" + fenceCharsToInsert;
  13515. if(sel_multi) {
  13516. end_line_sel++;
  13517. }
  13518. // handle last char including \n or not
  13519. if(sel_multi && cur_end.ch === 0) {
  13520. repl_end = fenceCharsToInsert + "\n";
  13521. end_line_sel--;
  13522. }
  13523. _replaceSelection(cm, false, [repl_start, repl_end]);
  13524. cm.setSelection({
  13525. line: start_line_sel,
  13526. ch: 0
  13527. }, {
  13528. line: end_line_sel,
  13529. ch: 0
  13530. });
  13531. }
  13532. var cm = editor.codemirror,
  13533. cur_start = cm.getCursor("start"),
  13534. cur_end = cm.getCursor("end"),
  13535. tok = cm.getTokenAt({
  13536. line: cur_start.line,
  13537. ch: cur_start.ch || 1
  13538. }), // avoid ch 0 which is a cursor pos but not token
  13539. line = cm.getLineHandle(cur_start.line),
  13540. is_code = code_type(cm, cur_start.line, line, tok);
  13541. var block_start, block_end, lineCount;
  13542. if(is_code === "single") {
  13543. // similar to some SimpleMDE _toggleBlock logic
  13544. var start = line.text.slice(0, cur_start.ch).replace("`", ""),
  13545. end = line.text.slice(cur_start.ch).replace("`", "");
  13546. cm.replaceRange(start + end, {
  13547. line: cur_start.line,
  13548. ch: 0
  13549. }, {
  13550. line: cur_start.line,
  13551. ch: 99999999999999
  13552. });
  13553. cur_start.ch--;
  13554. if(cur_start !== cur_end) {
  13555. cur_end.ch--;
  13556. }
  13557. cm.setSelection(cur_start, cur_end);
  13558. cm.focus();
  13559. } else if(is_code === "fenced") {
  13560. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  13561. // use selection
  13562. // find the fenced line so we know what type it is (tilde, backticks, number of them)
  13563. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  13564. line = cm.getLineHandle(block_start);
  13565. if(fencing_line(line)) {
  13566. break;
  13567. }
  13568. }
  13569. var fencedTok = cm.getTokenAt({
  13570. line: block_start,
  13571. ch: 1
  13572. });
  13573. var fence_chars = token_state(fencedTok).fencedChars;
  13574. var start_text, start_line;
  13575. var end_text, end_line;
  13576. // check for selection going up against fenced lines, in which case we don't want to add more fencing
  13577. if(fencing_line(cm.getLineHandle(cur_start.line))) {
  13578. start_text = "";
  13579. start_line = cur_start.line;
  13580. } else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
  13581. start_text = "";
  13582. start_line = cur_start.line - 1;
  13583. } else {
  13584. start_text = fence_chars + "\n";
  13585. start_line = cur_start.line;
  13586. }
  13587. if(fencing_line(cm.getLineHandle(cur_end.line))) {
  13588. end_text = "";
  13589. end_line = cur_end.line;
  13590. if(cur_end.ch === 0) {
  13591. end_line += 1;
  13592. }
  13593. } else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
  13594. end_text = "";
  13595. end_line = cur_end.line + 1;
  13596. } else {
  13597. end_text = fence_chars + "\n";
  13598. end_line = cur_end.line + 1;
  13599. }
  13600. if(cur_end.ch === 0) {
  13601. // full last line selected, putting cursor at beginning of next
  13602. end_line -= 1;
  13603. }
  13604. cm.operation(function() {
  13605. // end line first, so that line numbers don't change
  13606. cm.replaceRange(end_text, {
  13607. line: end_line,
  13608. ch: 0
  13609. }, {
  13610. line: end_line + (end_text ? 0 : 1),
  13611. ch: 0
  13612. });
  13613. cm.replaceRange(start_text, {
  13614. line: start_line,
  13615. ch: 0
  13616. }, {
  13617. line: start_line + (start_text ? 0 : 1),
  13618. ch: 0
  13619. });
  13620. });
  13621. cm.setSelection({
  13622. line: start_line + (start_text ? 1 : 0),
  13623. ch: 0
  13624. }, {
  13625. line: end_line + (start_text ? 1 : -1),
  13626. ch: 0
  13627. });
  13628. cm.focus();
  13629. } else {
  13630. // no selection, search for ends of this fenced block
  13631. var search_from = cur_start.line;
  13632. if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
  13633. if(code_type(cm, cur_start.line + 1) === "fenced") {
  13634. block_start = cur_start.line;
  13635. search_from = cur_start.line + 1; // for searching for "end"
  13636. } else {
  13637. block_end = cur_start.line;
  13638. search_from = cur_start.line - 1; // for searching for "start"
  13639. }
  13640. }
  13641. if(block_start === undefined) {
  13642. for(block_start = search_from; block_start >= 0; block_start--) {
  13643. line = cm.getLineHandle(block_start);
  13644. if(fencing_line(line)) {
  13645. break;
  13646. }
  13647. }
  13648. }
  13649. if(block_end === undefined) {
  13650. lineCount = cm.lineCount();
  13651. for(block_end = search_from; block_end < lineCount; block_end++) {
  13652. line = cm.getLineHandle(block_end);
  13653. if(fencing_line(line)) {
  13654. break;
  13655. }
  13656. }
  13657. }
  13658. cm.operation(function() {
  13659. cm.replaceRange("", {
  13660. line: block_start,
  13661. ch: 0
  13662. }, {
  13663. line: block_start + 1,
  13664. ch: 0
  13665. });
  13666. cm.replaceRange("", {
  13667. line: block_end - 1,
  13668. ch: 0
  13669. }, {
  13670. line: block_end,
  13671. ch: 0
  13672. });
  13673. });
  13674. cm.focus();
  13675. }
  13676. } else if(is_code === "indented") {
  13677. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  13678. // use selection
  13679. block_start = cur_start.line;
  13680. block_end = cur_end.line;
  13681. if(cur_end.ch === 0) {
  13682. block_end--;
  13683. }
  13684. } else {
  13685. // no selection, search for ends of this indented block
  13686. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  13687. line = cm.getLineHandle(block_start);
  13688. if(line.text.match(/^\s*$/)) {
  13689. // empty or all whitespace - keep going
  13690. continue;
  13691. } else {
  13692. if(code_type(cm, block_start, line) !== "indented") {
  13693. block_start += 1;
  13694. break;
  13695. }
  13696. }
  13697. }
  13698. lineCount = cm.lineCount();
  13699. for(block_end = cur_start.line; block_end < lineCount; block_end++) {
  13700. line = cm.getLineHandle(block_end);
  13701. if(line.text.match(/^\s*$/)) {
  13702. // empty or all whitespace - keep going
  13703. continue;
  13704. } else {
  13705. if(code_type(cm, block_end, line) !== "indented") {
  13706. block_end -= 1;
  13707. break;
  13708. }
  13709. }
  13710. }
  13711. }
  13712. // if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
  13713. // insert a blank line so that the next line(s) continue to be indented code
  13714. var next_line = cm.getLineHandle(block_end + 1),
  13715. next_line_last_tok = next_line && cm.getTokenAt({
  13716. line: block_end + 1,
  13717. ch: next_line.text.length - 1
  13718. }),
  13719. next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
  13720. if(next_line_indented) {
  13721. cm.replaceRange("\n", {
  13722. line: block_end + 1,
  13723. ch: 0
  13724. });
  13725. }
  13726. for(var i = block_start; i <= block_end; i++) {
  13727. cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
  13728. }
  13729. cm.focus();
  13730. } else {
  13731. // insert code formatting
  13732. var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
  13733. var sel_multi = cur_start.line !== cur_end.line;
  13734. if(no_sel_and_starting_of_line || sel_multi) {
  13735. insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
  13736. } else {
  13737. _replaceSelection(cm, false, ["`", "`"]);
  13738. }
  13739. }
  13740. }
  13741. /**
  13742. * Action for toggling blockquote.
  13743. */
  13744. function toggleBlockquote(editor) {
  13745. var cm = editor.codemirror;
  13746. _toggleLine(cm, "quote");
  13747. }
  13748. /**
  13749. * Action for toggling heading size: normal -> h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> normal
  13750. */
  13751. function toggleHeadingSmaller(editor) {
  13752. var cm = editor.codemirror;
  13753. _toggleHeading(cm, "smaller");
  13754. }
  13755. /**
  13756. * Action for toggling heading size: normal -> h6 -> h5 -> h4 -> h3 -> h2 -> h1 -> normal
  13757. */
  13758. function toggleHeadingBigger(editor) {
  13759. var cm = editor.codemirror;
  13760. _toggleHeading(cm, "bigger");
  13761. }
  13762. /**
  13763. * Action for toggling heading size 1
  13764. */
  13765. function toggleHeading1(editor) {
  13766. var cm = editor.codemirror;
  13767. _toggleHeading(cm, undefined, 1);
  13768. }
  13769. /**
  13770. * Action for toggling heading size 2
  13771. */
  13772. function toggleHeading2(editor) {
  13773. var cm = editor.codemirror;
  13774. _toggleHeading(cm, undefined, 2);
  13775. }
  13776. /**
  13777. * Action for toggling heading size 3
  13778. */
  13779. function toggleHeading3(editor) {
  13780. var cm = editor.codemirror;
  13781. _toggleHeading(cm, undefined, 3);
  13782. }
  13783. /**
  13784. * Action for toggling ul.
  13785. */
  13786. function toggleUnorderedList(editor) {
  13787. var cm = editor.codemirror;
  13788. _toggleLine(cm, "unordered-list");
  13789. }
  13790. /**
  13791. * Action for toggling ol.
  13792. */
  13793. function toggleOrderedList(editor) {
  13794. var cm = editor.codemirror;
  13795. _toggleLine(cm, "ordered-list");
  13796. }
  13797. /**
  13798. * Action for clean block (remove headline, list, blockquote code, markers)
  13799. */
  13800. function cleanBlock(editor) {
  13801. var cm = editor.codemirror;
  13802. _cleanBlock(cm);
  13803. }
  13804. /**
  13805. * Action for drawing a link.
  13806. */
  13807. function drawLink(editor) {
  13808. var cm = editor.codemirror;
  13809. var stat = getState(cm);
  13810. var options = editor.options;
  13811. var url = "http://";
  13812. if(options.promptURLs) {
  13813. url = prompt(options.promptTexts.link);
  13814. if(!url) {
  13815. return false;
  13816. }
  13817. }
  13818. _replaceSelection(cm, stat.link, options.insertTexts.link, url);
  13819. }
  13820. /**
  13821. * Action for drawing an img.
  13822. */
  13823. function drawImage(editor) {
  13824. var cm = editor.codemirror;
  13825. var stat = getState(cm);
  13826. var options = editor.options;
  13827. var url = "http://";
  13828. if(options.promptURLs) {
  13829. url = prompt(options.promptTexts.image);
  13830. if(!url) {
  13831. return false;
  13832. }
  13833. }
  13834. _replaceSelection(cm, stat.image, options.insertTexts.image, url);
  13835. }
  13836. /**
  13837. * Action for drawing a table.
  13838. */
  13839. function drawTable(editor) {
  13840. var cm = editor.codemirror;
  13841. var stat = getState(cm);
  13842. var options = editor.options;
  13843. _replaceSelection(cm, stat.table, options.insertTexts.table);
  13844. }
  13845. /**
  13846. * Action for drawing a horizontal rule.
  13847. */
  13848. function drawHorizontalRule(editor) {
  13849. var cm = editor.codemirror;
  13850. var stat = getState(cm);
  13851. var options = editor.options;
  13852. _replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);
  13853. }
  13854. /**
  13855. * Undo action.
  13856. */
  13857. function undo(editor) {
  13858. var cm = editor.codemirror;
  13859. cm.undo();
  13860. cm.focus();
  13861. }
  13862. /**
  13863. * Redo action.
  13864. */
  13865. function redo(editor) {
  13866. var cm = editor.codemirror;
  13867. cm.redo();
  13868. cm.focus();
  13869. }
  13870. /**
  13871. * Toggle side by side preview
  13872. */
  13873. function toggleSideBySide(editor) {
  13874. var cm = editor.codemirror;
  13875. var wrapper = cm.getWrapperElement();
  13876. var preview = wrapper.nextSibling;
  13877. var toolbarButton = editor.toolbarElements["side-by-side"];
  13878. var useSideBySideListener = false;
  13879. if(/editor-preview-active-side/.test(preview.className)) {
  13880. preview.className = preview.className.replace(
  13881. /\s*editor-preview-active-side\s*/g, ""
  13882. );
  13883. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  13884. wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, " ");
  13885. } else {
  13886. // When the preview button is clicked for the first time,
  13887. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  13888. // instead of just appearing.
  13889. setTimeout(function() {
  13890. if(!cm.getOption("fullScreen"))
  13891. toggleFullScreen(editor);
  13892. preview.className += " editor-preview-active-side";
  13893. }, 1);
  13894. toolbarButton.className += " active";
  13895. wrapper.className += " CodeMirror-sided";
  13896. useSideBySideListener = true;
  13897. }
  13898. // Hide normal preview if active
  13899. var previewNormal = wrapper.lastChild;
  13900. if(/editor-preview-active/.test(previewNormal.className)) {
  13901. previewNormal.className = previewNormal.className.replace(
  13902. /\s*editor-preview-active\s*/g, ""
  13903. );
  13904. var toolbar = editor.toolbarElements.preview;
  13905. var toolbar_div = wrapper.previousSibling;
  13906. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  13907. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  13908. }
  13909. var sideBySideRenderingFunction = function() {
  13910. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13911. };
  13912. if(!cm.sideBySideRenderingFunction) {
  13913. cm.sideBySideRenderingFunction = sideBySideRenderingFunction;
  13914. }
  13915. if(useSideBySideListener) {
  13916. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13917. cm.on("update", cm.sideBySideRenderingFunction);
  13918. } else {
  13919. cm.off("update", cm.sideBySideRenderingFunction);
  13920. }
  13921. // Refresh to fix selection being off (#309)
  13922. cm.refresh();
  13923. }
  13924. /**
  13925. * Preview action.
  13926. */
  13927. function togglePreview(editor) {
  13928. var cm = editor.codemirror;
  13929. var wrapper = cm.getWrapperElement();
  13930. var toolbar_div = wrapper.previousSibling;
  13931. var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
  13932. var preview = wrapper.lastChild;
  13933. if(!preview || !/editor-preview/.test(preview.className)) {
  13934. preview = document.createElement("div");
  13935. preview.className = "editor-preview";
  13936. wrapper.appendChild(preview);
  13937. }
  13938. if(/editor-preview-active/.test(preview.className)) {
  13939. preview.className = preview.className.replace(
  13940. /\s*editor-preview-active\s*/g, ""
  13941. );
  13942. if(toolbar) {
  13943. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  13944. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  13945. }
  13946. } else {
  13947. // When the preview button is clicked for the first time,
  13948. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  13949. // instead of just appearing.
  13950. setTimeout(function() {
  13951. preview.className += " editor-preview-active";
  13952. }, 1);
  13953. if(toolbar) {
  13954. toolbar.className += " active";
  13955. toolbar_div.className += " disabled-for-preview";
  13956. }
  13957. }
  13958. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13959. // Turn off side by side if needed
  13960. var sidebyside = cm.getWrapperElement().nextSibling;
  13961. if(/editor-preview-active-side/.test(sidebyside.className))
  13962. toggleSideBySide(editor);
  13963. }
  13964. function _replaceSelection(cm, active, startEnd, url) {
  13965. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  13966. return;
  13967. var text;
  13968. var start = startEnd[0];
  13969. var end = startEnd[1];
  13970. var startPoint = cm.getCursor("start");
  13971. var endPoint = cm.getCursor("end");
  13972. if(url) {
  13973. end = end.replace("#url#", url);
  13974. }
  13975. if(active) {
  13976. text = cm.getLine(startPoint.line);
  13977. start = text.slice(0, startPoint.ch);
  13978. end = text.slice(startPoint.ch);
  13979. cm.replaceRange(start + end, {
  13980. line: startPoint.line,
  13981. ch: 0
  13982. });
  13983. } else {
  13984. text = cm.getSelection();
  13985. cm.replaceSelection(start + text + end);
  13986. startPoint.ch += start.length;
  13987. if(startPoint !== endPoint) {
  13988. endPoint.ch += start.length;
  13989. }
  13990. }
  13991. cm.setSelection(startPoint, endPoint);
  13992. cm.focus();
  13993. }
  13994. function _toggleHeading(cm, direction, size) {
  13995. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  13996. return;
  13997. var startPoint = cm.getCursor("start");
  13998. var endPoint = cm.getCursor("end");
  13999. for(var i = startPoint.line; i <= endPoint.line; i++) {
  14000. (function(i) {
  14001. var text = cm.getLine(i);
  14002. var currHeadingLevel = text.search(/[^#]/);
  14003. if(direction !== undefined) {
  14004. if(currHeadingLevel <= 0) {
  14005. if(direction == "bigger") {
  14006. text = "###### " + text;
  14007. } else {
  14008. text = "# " + text;
  14009. }
  14010. } else if(currHeadingLevel == 6 && direction == "smaller") {
  14011. text = text.substr(7);
  14012. } else if(currHeadingLevel == 1 && direction == "bigger") {
  14013. text = text.substr(2);
  14014. } else {
  14015. if(direction == "bigger") {
  14016. text = text.substr(1);
  14017. } else {
  14018. text = "#" + text;
  14019. }
  14020. }
  14021. } else {
  14022. if(size == 1) {
  14023. if(currHeadingLevel <= 0) {
  14024. text = "# " + text;
  14025. } else if(currHeadingLevel == size) {
  14026. text = text.substr(currHeadingLevel + 1);
  14027. } else {
  14028. text = "# " + text.substr(currHeadingLevel + 1);
  14029. }
  14030. } else if(size == 2) {
  14031. if(currHeadingLevel <= 0) {
  14032. text = "## " + text;
  14033. } else if(currHeadingLevel == size) {
  14034. text = text.substr(currHeadingLevel + 1);
  14035. } else {
  14036. text = "## " + text.substr(currHeadingLevel + 1);
  14037. }
  14038. } else {
  14039. if(currHeadingLevel <= 0) {
  14040. text = "### " + text;
  14041. } else if(currHeadingLevel == size) {
  14042. text = text.substr(currHeadingLevel + 1);
  14043. } else {
  14044. text = "### " + text.substr(currHeadingLevel + 1);
  14045. }
  14046. }
  14047. }
  14048. cm.replaceRange(text, {
  14049. line: i,
  14050. ch: 0
  14051. }, {
  14052. line: i,
  14053. ch: 99999999999999
  14054. });
  14055. })(i);
  14056. }
  14057. cm.focus();
  14058. }
  14059. function _toggleLine(cm, name) {
  14060. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14061. return;
  14062. var stat = getState(cm);
  14063. var startPoint = cm.getCursor("start");
  14064. var endPoint = cm.getCursor("end");
  14065. var repl = {
  14066. "quote": /^(\s*)\>\s+/,
  14067. "unordered-list": /^(\s*)(\*|\-|\+)\s+/,
  14068. "ordered-list": /^(\s*)\d+\.\s+/
  14069. };
  14070. var map = {
  14071. "quote": "> ",
  14072. "unordered-list": "* ",
  14073. "ordered-list": "1. "
  14074. };
  14075. for(var i = startPoint.line; i <= endPoint.line; i++) {
  14076. (function(i) {
  14077. var text = cm.getLine(i);
  14078. if(stat[name]) {
  14079. text = text.replace(repl[name], "$1");
  14080. } else {
  14081. text = map[name] + text;
  14082. }
  14083. cm.replaceRange(text, {
  14084. line: i,
  14085. ch: 0
  14086. }, {
  14087. line: i,
  14088. ch: 99999999999999
  14089. });
  14090. })(i);
  14091. }
  14092. cm.focus();
  14093. }
  14094. function _toggleBlock(editor, type, start_chars, end_chars) {
  14095. if(/editor-preview-active/.test(editor.codemirror.getWrapperElement().lastChild.className))
  14096. return;
  14097. end_chars = (typeof end_chars === "undefined") ? start_chars : end_chars;
  14098. var cm = editor.codemirror;
  14099. var stat = getState(cm);
  14100. var text;
  14101. var start = start_chars;
  14102. var end = end_chars;
  14103. var startPoint = cm.getCursor("start");
  14104. var endPoint = cm.getCursor("end");
  14105. if(stat[type]) {
  14106. text = cm.getLine(startPoint.line);
  14107. start = text.slice(0, startPoint.ch);
  14108. end = text.slice(startPoint.ch);
  14109. if(type == "bold") {
  14110. start = start.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/, "");
  14111. end = end.replace(/(\*\*|__)/, "");
  14112. } else if(type == "italic") {
  14113. start = start.replace(/(\*|_)(?![\s\S]*(\*|_))/, "");
  14114. end = end.replace(/(\*|_)/, "");
  14115. } else if(type == "strikethrough") {
  14116. start = start.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/, "");
  14117. end = end.replace(/(\*\*|~~)/, "");
  14118. }
  14119. cm.replaceRange(start + end, {
  14120. line: startPoint.line,
  14121. ch: 0
  14122. }, {
  14123. line: startPoint.line,
  14124. ch: 99999999999999
  14125. });
  14126. if(type == "bold" || type == "strikethrough") {
  14127. startPoint.ch -= 2;
  14128. if(startPoint !== endPoint) {
  14129. endPoint.ch -= 2;
  14130. }
  14131. } else if(type == "italic") {
  14132. startPoint.ch -= 1;
  14133. if(startPoint !== endPoint) {
  14134. endPoint.ch -= 1;
  14135. }
  14136. }
  14137. } else {
  14138. text = cm.getSelection();
  14139. if(type == "bold") {
  14140. text = text.split("**").join("");
  14141. text = text.split("__").join("");
  14142. } else if(type == "italic") {
  14143. text = text.split("*").join("");
  14144. text = text.split("_").join("");
  14145. } else if(type == "strikethrough") {
  14146. text = text.split("~~").join("");
  14147. }
  14148. cm.replaceSelection(start + text + end);
  14149. startPoint.ch += start_chars.length;
  14150. endPoint.ch = startPoint.ch + text.length;
  14151. }
  14152. cm.setSelection(startPoint, endPoint);
  14153. cm.focus();
  14154. }
  14155. function _cleanBlock(cm) {
  14156. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14157. return;
  14158. var startPoint = cm.getCursor("start");
  14159. var endPoint = cm.getCursor("end");
  14160. var text;
  14161. for(var line = startPoint.line; line <= endPoint.line; line++) {
  14162. text = cm.getLine(line);
  14163. text = text.replace(/^[ ]*([# ]+|\*|\-|[> ]+|[0-9]+(.|\)))[ ]*/, "");
  14164. cm.replaceRange(text, {
  14165. line: line,
  14166. ch: 0
  14167. }, {
  14168. line: line,
  14169. ch: 99999999999999
  14170. });
  14171. }
  14172. }
  14173. // Merge the properties of one object into another.
  14174. function _mergeProperties(target, source) {
  14175. for(var property in source) {
  14176. if(source.hasOwnProperty(property)) {
  14177. if(source[property] instanceof Array) {
  14178. target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);
  14179. } else if(
  14180. source[property] !== null &&
  14181. typeof source[property] === "object" &&
  14182. source[property].constructor === Object
  14183. ) {
  14184. target[property] = _mergeProperties(target[property] || {}, source[property]);
  14185. } else {
  14186. target[property] = source[property];
  14187. }
  14188. }
  14189. }
  14190. return target;
  14191. }
  14192. // Merge an arbitrary number of objects into one.
  14193. function extend(target) {
  14194. for(var i = 1; i < arguments.length; i++) {
  14195. target = _mergeProperties(target, arguments[i]);
  14196. }
  14197. return target;
  14198. }
  14199. /* The right word count in respect for CJK. */
  14200. function wordCount(data) {
  14201. var pattern = /[a-zA-Z0-9_\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
  14202. var m = data.match(pattern);
  14203. var count = 0;
  14204. if(m === null) return count;
  14205. for(var i = 0; i < m.length; i++) {
  14206. if(m[i].charCodeAt(0) >= 0x4E00) {
  14207. count += m[i].length;
  14208. } else {
  14209. count += 1;
  14210. }
  14211. }
  14212. return count;
  14213. }
  14214. var toolbarBuiltInButtons = {
  14215. "bold": {
  14216. name: "bold",
  14217. action: toggleBold,
  14218. className: "fa fa-bold",
  14219. title: "Bold",
  14220. default: true
  14221. },
  14222. "italic": {
  14223. name: "italic",
  14224. action: toggleItalic,
  14225. className: "fa fa-italic",
  14226. title: "Italic",
  14227. default: true
  14228. },
  14229. "strikethrough": {
  14230. name: "strikethrough",
  14231. action: toggleStrikethrough,
  14232. className: "fa fa-strikethrough",
  14233. title: "Strikethrough"
  14234. },
  14235. "heading": {
  14236. name: "heading",
  14237. action: toggleHeadingSmaller,
  14238. className: "fa fa-header",
  14239. title: "Heading",
  14240. default: true
  14241. },
  14242. "heading-smaller": {
  14243. name: "heading-smaller",
  14244. action: toggleHeadingSmaller,
  14245. className: "fa fa-header fa-header-x fa-header-smaller",
  14246. title: "Smaller Heading"
  14247. },
  14248. "heading-bigger": {
  14249. name: "heading-bigger",
  14250. action: toggleHeadingBigger,
  14251. className: "fa fa-header fa-header-x fa-header-bigger",
  14252. title: "Bigger Heading"
  14253. },
  14254. "heading-1": {
  14255. name: "heading-1",
  14256. action: toggleHeading1,
  14257. className: "fa fa-header fa-header-x fa-header-1",
  14258. title: "Big Heading"
  14259. },
  14260. "heading-2": {
  14261. name: "heading-2",
  14262. action: toggleHeading2,
  14263. className: "fa fa-header fa-header-x fa-header-2",
  14264. title: "Medium Heading"
  14265. },
  14266. "heading-3": {
  14267. name: "heading-3",
  14268. action: toggleHeading3,
  14269. className: "fa fa-header fa-header-x fa-header-3",
  14270. title: "Small Heading"
  14271. },
  14272. "separator-1": {
  14273. name: "separator-1"
  14274. },
  14275. "code": {
  14276. name: "code",
  14277. action: toggleCodeBlock,
  14278. className: "fa fa-code",
  14279. title: "Code"
  14280. },
  14281. "quote": {
  14282. name: "quote",
  14283. action: toggleBlockquote,
  14284. className: "fa fa-quote-left",
  14285. title: "Quote",
  14286. default: true
  14287. },
  14288. "unordered-list": {
  14289. name: "unordered-list",
  14290. action: toggleUnorderedList,
  14291. className: "fa fa-list-ul",
  14292. title: "Generic List",
  14293. default: true
  14294. },
  14295. "ordered-list": {
  14296. name: "ordered-list",
  14297. action: toggleOrderedList,
  14298. className: "fa fa-list-ol",
  14299. title: "Numbered List",
  14300. default: true
  14301. },
  14302. "clean-block": {
  14303. name: "clean-block",
  14304. action: cleanBlock,
  14305. className: "fa fa-eraser fa-clean-block",
  14306. title: "Clean block"
  14307. },
  14308. "separator-2": {
  14309. name: "separator-2"
  14310. },
  14311. "link": {
  14312. name: "link",
  14313. action: drawLink,
  14314. className: "fa fa-link",
  14315. title: "Create Link",
  14316. default: true
  14317. },
  14318. "image": {
  14319. name: "image",
  14320. action: drawImage,
  14321. className: "fa fa-picture-o",
  14322. title: "Insert Image",
  14323. default: true
  14324. },
  14325. "table": {
  14326. name: "table",
  14327. action: drawTable,
  14328. className: "fa fa-table",
  14329. title: "Insert Table"
  14330. },
  14331. "horizontal-rule": {
  14332. name: "horizontal-rule",
  14333. action: drawHorizontalRule,
  14334. className: "fa fa-minus",
  14335. title: "Insert Horizontal Line"
  14336. },
  14337. "separator-3": {
  14338. name: "separator-3"
  14339. },
  14340. "preview": {
  14341. name: "preview",
  14342. action: togglePreview,
  14343. className: "fa fa-eye no-disable",
  14344. title: "Toggle Preview",
  14345. default: true
  14346. },
  14347. "side-by-side": {
  14348. name: "side-by-side",
  14349. action: toggleSideBySide,
  14350. className: "fa fa-columns no-disable no-mobile",
  14351. title: "Toggle Side by Side",
  14352. default: true
  14353. },
  14354. "fullscreen": {
  14355. name: "fullscreen",
  14356. action: toggleFullScreen,
  14357. className: "fa fa-arrows-alt no-disable no-mobile",
  14358. title: "Toggle Fullscreen",
  14359. default: true
  14360. },
  14361. "separator-4": {
  14362. name: "separator-4"
  14363. },
  14364. "guide": {
  14365. name: "guide",
  14366. action: "https://simplemde.com/markdown-guide",
  14367. className: "fa fa-question-circle",
  14368. title: "Markdown Guide",
  14369. default: true
  14370. },
  14371. "separator-5": {
  14372. name: "separator-5"
  14373. },
  14374. "undo": {
  14375. name: "undo",
  14376. action: undo,
  14377. className: "fa fa-undo no-disable",
  14378. title: "Undo"
  14379. },
  14380. "redo": {
  14381. name: "redo",
  14382. action: redo,
  14383. className: "fa fa-repeat no-disable",
  14384. title: "Redo"
  14385. }
  14386. };
  14387. var insertTexts = {
  14388. link: ["[", "](#url#)"],
  14389. image: ["![](", "#url#)"],
  14390. table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"],
  14391. horizontalRule: ["", "\n\n-----\n\n"]
  14392. };
  14393. var promptTexts = {
  14394. link: "URL for the link:",
  14395. image: "URL of the image:"
  14396. };
  14397. var blockStyles = {
  14398. "bold": "**",
  14399. "code": "```",
  14400. "italic": "*"
  14401. };
  14402. /**
  14403. * Interface of SimpleMDE.
  14404. */
  14405. function SimpleMDE(options) {
  14406. // Handle options parameter
  14407. options = options || {};
  14408. // Used later to refer to it"s parent
  14409. options.parent = this;
  14410. // Check if Font Awesome needs to be auto downloaded
  14411. var autoDownloadFA = true;
  14412. if(options.autoDownloadFontAwesome === false) {
  14413. autoDownloadFA = false;
  14414. }
  14415. if(options.autoDownloadFontAwesome !== true) {
  14416. var styleSheets = document.styleSheets;
  14417. for(var i = 0; i < styleSheets.length; i++) {
  14418. if(!styleSheets[i].href)
  14419. continue;
  14420. if(styleSheets[i].href.indexOf("//maxcdn.bootstrapcdn.com/font-awesome/") > -1) {
  14421. autoDownloadFA = false;
  14422. }
  14423. }
  14424. }
  14425. if(autoDownloadFA) {
  14426. var link = document.createElement("link");
  14427. link.rel = "stylesheet";
  14428. link.href = "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css";
  14429. document.getElementsByTagName("head")[0].appendChild(link);
  14430. }
  14431. // Find the textarea to use
  14432. if(options.element) {
  14433. this.element = options.element;
  14434. } else if(options.element === null) {
  14435. // This means that the element option was specified, but no element was found
  14436. console.log("SimpleMDE: Error. No element was found.");
  14437. return;
  14438. }
  14439. // Handle toolbar
  14440. if(options.toolbar === undefined) {
  14441. // Initialize
  14442. options.toolbar = [];
  14443. // Loop over the built in buttons, to get the preferred order
  14444. for(var key in toolbarBuiltInButtons) {
  14445. if(toolbarBuiltInButtons.hasOwnProperty(key)) {
  14446. if(key.indexOf("separator-") != -1) {
  14447. options.toolbar.push("|");
  14448. }
  14449. if(toolbarBuiltInButtons[key].default === true || (options.showIcons && options.showIcons.constructor === Array && options.showIcons.indexOf(key) != -1)) {
  14450. options.toolbar.push(key);
  14451. }
  14452. }
  14453. }
  14454. }
  14455. // Handle status bar
  14456. if(!options.hasOwnProperty("status")) {
  14457. options.status = ["autosave", "lines", "words", "cursor"];
  14458. }
  14459. // Add default preview rendering function
  14460. if(!options.previewRender) {
  14461. options.previewRender = function(plainText) {
  14462. // Note: "this" refers to the options object
  14463. return this.parent.markdown(plainText);
  14464. };
  14465. }
  14466. // Set default options for parsing config
  14467. options.parsingConfig = extend({
  14468. highlightFormatting: true // needed for toggleCodeBlock to detect types of code
  14469. }, options.parsingConfig || {});
  14470. // Merging the insertTexts, with the given options
  14471. options.insertTexts = extend({}, insertTexts, options.insertTexts || {});
  14472. // Merging the promptTexts, with the given options
  14473. options.promptTexts = promptTexts;
  14474. // Merging the blockStyles, with the given options
  14475. options.blockStyles = extend({}, blockStyles, options.blockStyles || {});
  14476. // Merging the shortcuts, with the given options
  14477. options.shortcuts = extend({}, shortcuts, options.shortcuts || {});
  14478. // Change unique_id to uniqueId for backwards compatibility
  14479. if(options.autosave != undefined && options.autosave.unique_id != undefined && options.autosave.unique_id != "")
  14480. options.autosave.uniqueId = options.autosave.unique_id;
  14481. // Update this options
  14482. this.options = options;
  14483. // Auto render
  14484. this.render();
  14485. // The codemirror component is only available after rendering
  14486. // so, the setter for the initialValue can only run after
  14487. // the element has been rendered
  14488. if(options.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {
  14489. this.value(options.initialValue);
  14490. }
  14491. }
  14492. /**
  14493. * Default markdown render.
  14494. */
  14495. SimpleMDE.prototype.markdown = function(text) {
  14496. if(marked) {
  14497. // Initialize
  14498. var markedOptions = {};
  14499. // Update options
  14500. if(this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {
  14501. markedOptions.breaks = false;
  14502. } else {
  14503. markedOptions.breaks = true;
  14504. }
  14505. if(this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true && window.hljs) {
  14506. markedOptions.highlight = function(code) {
  14507. return window.hljs.highlightAuto(code).value;
  14508. };
  14509. }
  14510. // Set options
  14511. marked.setOptions(markedOptions);
  14512. // Return
  14513. return marked(text);
  14514. }
  14515. };
  14516. /**
  14517. * Render editor to the given element.
  14518. */
  14519. SimpleMDE.prototype.render = function(el) {
  14520. if(!el) {
  14521. el = this.element || document.getElementsByTagName("textarea")[0];
  14522. }
  14523. if(this._rendered && this._rendered === el) {
  14524. // Already rendered.
  14525. return;
  14526. }
  14527. this.element = el;
  14528. var options = this.options;
  14529. var self = this;
  14530. var keyMaps = {};
  14531. for(var key in options.shortcuts) {
  14532. // null stands for "do not bind this command"
  14533. if(options.shortcuts[key] !== null && bindings[key] !== null) {
  14534. (function(key) {
  14535. keyMaps[fixShortcut(options.shortcuts[key])] = function() {
  14536. bindings[key](self);
  14537. };
  14538. })(key);
  14539. }
  14540. }
  14541. keyMaps["Enter"] = "newlineAndIndentContinueMarkdownList";
  14542. keyMaps["Tab"] = "tabAndIndentMarkdownList";
  14543. keyMaps["Shift-Tab"] = "shiftTabAndUnindentMarkdownList";
  14544. keyMaps["Esc"] = function(cm) {
  14545. if(cm.getOption("fullScreen")) toggleFullScreen(self);
  14546. };
  14547. document.addEventListener("keydown", function(e) {
  14548. e = e || window.event;
  14549. if(e.keyCode == 27) {
  14550. if(self.codemirror.getOption("fullScreen")) toggleFullScreen(self);
  14551. }
  14552. }, false);
  14553. var mode, backdrop;
  14554. if(options.spellChecker !== false) {
  14555. mode = "spell-checker";
  14556. backdrop = options.parsingConfig;
  14557. backdrop.name = "gfm";
  14558. backdrop.gitHubSpice = false;
  14559. CodeMirrorSpellChecker({
  14560. codeMirrorInstance: CodeMirror
  14561. });
  14562. } else {
  14563. mode = options.parsingConfig;
  14564. mode.name = "gfm";
  14565. mode.gitHubSpice = false;
  14566. }
  14567. this.codemirror = CodeMirror.fromTextArea(el, {
  14568. mode: mode,
  14569. backdrop: backdrop,
  14570. theme: "paper",
  14571. tabSize: (options.tabSize != undefined) ? options.tabSize : 2,
  14572. indentUnit: (options.tabSize != undefined) ? options.tabSize : 2,
  14573. indentWithTabs: (options.indentWithTabs === false) ? false : true,
  14574. lineNumbers: false,
  14575. autofocus: (options.autofocus === true) ? true : false,
  14576. extraKeys: keyMaps,
  14577. lineWrapping: (options.lineWrapping === false) ? false : true,
  14578. allowDropFileTypes: ["text/plain"],
  14579. placeholder: options.placeholder || el.getAttribute("placeholder") || "",
  14580. styleSelectedText: (options.styleSelectedText != undefined) ? options.styleSelectedText : true
  14581. });
  14582. if(options.forceSync === true) {
  14583. var cm = this.codemirror;
  14584. cm.on("change", function() {
  14585. cm.save();
  14586. });
  14587. }
  14588. this.gui = {};
  14589. if(options.toolbar !== false) {
  14590. this.gui.toolbar = this.createToolbar();
  14591. }
  14592. if(options.status !== false) {
  14593. this.gui.statusbar = this.createStatusbar();
  14594. }
  14595. if(options.autosave != undefined && options.autosave.enabled === true) {
  14596. this.autosave();
  14597. }
  14598. this.gui.sideBySide = this.createSideBySide();
  14599. this._rendered = this.element;
  14600. // Fixes CodeMirror bug (#344)
  14601. var temp_cm = this.codemirror;
  14602. setTimeout(function() {
  14603. temp_cm.refresh();
  14604. }.bind(temp_cm), 0);
  14605. };
  14606. // 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.
  14607. function isLocalStorageAvailable() {
  14608. if(typeof localStorage === "object") {
  14609. try {
  14610. localStorage.setItem("smde_localStorage", 1);
  14611. localStorage.removeItem("smde_localStorage");
  14612. } catch(e) {
  14613. return false;
  14614. }
  14615. } else {
  14616. return false;
  14617. }
  14618. return true;
  14619. }
  14620. SimpleMDE.prototype.autosave = function() {
  14621. if(isLocalStorageAvailable()) {
  14622. var simplemde = this;
  14623. if(this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  14624. console.log("SimpleMDE: You must set a uniqueId to use the autosave feature");
  14625. return;
  14626. }
  14627. if(simplemde.element.form != null && simplemde.element.form != undefined) {
  14628. simplemde.element.form.addEventListener("submit", function() {
  14629. localStorage.removeItem("smde_" + simplemde.options.autosave.uniqueId);
  14630. });
  14631. }
  14632. if(this.options.autosave.loaded !== true) {
  14633. if(typeof localStorage.getItem("smde_" + this.options.autosave.uniqueId) == "string" && localStorage.getItem("smde_" + this.options.autosave.uniqueId) != "") {
  14634. this.codemirror.setValue(localStorage.getItem("smde_" + this.options.autosave.uniqueId));
  14635. this.options.autosave.foundSavedValue = true;
  14636. }
  14637. this.options.autosave.loaded = true;
  14638. }
  14639. localStorage.setItem("smde_" + this.options.autosave.uniqueId, simplemde.value());
  14640. var el = document.getElementById("autosaved");
  14641. if(el != null && el != undefined && el != "") {
  14642. var d = new Date();
  14643. var hh = d.getHours();
  14644. var m = d.getMinutes();
  14645. var dd = "am";
  14646. var h = hh;
  14647. if(h >= 12) {
  14648. h = hh - 12;
  14649. dd = "pm";
  14650. }
  14651. if(h == 0) {
  14652. h = 12;
  14653. }
  14654. m = m < 10 ? "0" + m : m;
  14655. el.innerHTML = "Autosaved: " + h + ":" + m + " " + dd;
  14656. }
  14657. this.autosaveTimeoutId = setTimeout(function() {
  14658. simplemde.autosave();
  14659. }, this.options.autosave.delay || 10000);
  14660. } else {
  14661. console.log("SimpleMDE: localStorage not available, cannot autosave");
  14662. }
  14663. };
  14664. SimpleMDE.prototype.clearAutosavedValue = function() {
  14665. if(isLocalStorageAvailable()) {
  14666. if(this.options.autosave == undefined || this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  14667. console.log("SimpleMDE: You must set a uniqueId to clear the autosave value");
  14668. return;
  14669. }
  14670. localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
  14671. } else {
  14672. console.log("SimpleMDE: localStorage not available, cannot autosave");
  14673. }
  14674. };
  14675. SimpleMDE.prototype.createSideBySide = function() {
  14676. var cm = this.codemirror;
  14677. var wrapper = cm.getWrapperElement();
  14678. var preview = wrapper.nextSibling;
  14679. if(!preview || !/editor-preview-side/.test(preview.className)) {
  14680. preview = document.createElement("div");
  14681. preview.className = "editor-preview-side";
  14682. wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);
  14683. }
  14684. // Syncs scroll editor -> preview
  14685. var cScroll = false;
  14686. var pScroll = false;
  14687. cm.on("scroll", function(v) {
  14688. if(cScroll) {
  14689. cScroll = false;
  14690. return;
  14691. }
  14692. pScroll = true;
  14693. var height = v.getScrollInfo().height - v.getScrollInfo().clientHeight;
  14694. var ratio = parseFloat(v.getScrollInfo().top) / height;
  14695. var move = (preview.scrollHeight - preview.clientHeight) * ratio;
  14696. preview.scrollTop = move;
  14697. });
  14698. // Syncs scroll preview -> editor
  14699. preview.onscroll = function() {
  14700. if(pScroll) {
  14701. pScroll = false;
  14702. return;
  14703. }
  14704. cScroll = true;
  14705. var height = preview.scrollHeight - preview.clientHeight;
  14706. var ratio = parseFloat(preview.scrollTop) / height;
  14707. var move = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;
  14708. cm.scrollTo(0, move);
  14709. };
  14710. return preview;
  14711. };
  14712. SimpleMDE.prototype.createToolbar = function(items) {
  14713. items = items || this.options.toolbar;
  14714. if(!items || items.length === 0) {
  14715. return;
  14716. }
  14717. var i;
  14718. for(i = 0; i < items.length; i++) {
  14719. if(toolbarBuiltInButtons[items[i]] != undefined) {
  14720. items[i] = toolbarBuiltInButtons[items[i]];
  14721. }
  14722. }
  14723. var bar = document.createElement("div");
  14724. bar.className = "editor-toolbar";
  14725. var self = this;
  14726. var toolbarData = {};
  14727. self.toolbar = items;
  14728. for(i = 0; i < items.length; i++) {
  14729. if(items[i].name == "guide" && self.options.toolbarGuideIcon === false)
  14730. continue;
  14731. if(self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)
  14732. continue;
  14733. // Fullscreen does not work well on mobile devices (even tablets)
  14734. // In the future, hopefully this can be resolved
  14735. if((items[i].name == "fullscreen" || items[i].name == "side-by-side") && isMobile())
  14736. continue;
  14737. // Don't include trailing separators
  14738. if(items[i] === "|") {
  14739. var nonSeparatorIconsFollow = false;
  14740. for(var x = (i + 1); x < items.length; x++) {
  14741. if(items[x] !== "|" && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x].name) == -1)) {
  14742. nonSeparatorIconsFollow = true;
  14743. }
  14744. }
  14745. if(!nonSeparatorIconsFollow)
  14746. continue;
  14747. }
  14748. // Create the icon and append to the toolbar
  14749. (function(item) {
  14750. var el;
  14751. if(item === "|") {
  14752. el = createSep();
  14753. } else {
  14754. el = createIcon(item, self.options.toolbarTips, self.options.shortcuts);
  14755. }
  14756. // bind events, special for info
  14757. if(item.action) {
  14758. if(typeof item.action === "function") {
  14759. el.onclick = function(e) {
  14760. e.preventDefault();
  14761. item.action(self);
  14762. };
  14763. } else if(typeof item.action === "string") {
  14764. el.href = item.action;
  14765. el.target = "_blank";
  14766. }
  14767. }
  14768. toolbarData[item.name || item] = el;
  14769. bar.appendChild(el);
  14770. })(items[i]);
  14771. }
  14772. self.toolbarElements = toolbarData;
  14773. var cm = this.codemirror;
  14774. cm.on("cursorActivity", function() {
  14775. var stat = getState(cm);
  14776. for(var key in toolbarData) {
  14777. (function(key) {
  14778. var el = toolbarData[key];
  14779. if(stat[key]) {
  14780. el.className += " active";
  14781. } else if(key != "fullscreen" && key != "side-by-side") {
  14782. el.className = el.className.replace(/\s*active\s*/g, "");
  14783. }
  14784. })(key);
  14785. }
  14786. });
  14787. var cmWrapper = cm.getWrapperElement();
  14788. cmWrapper.parentNode.insertBefore(bar, cmWrapper);
  14789. return bar;
  14790. };
  14791. SimpleMDE.prototype.createStatusbar = function(status) {
  14792. // Initialize
  14793. status = status || this.options.status;
  14794. var options = this.options;
  14795. var cm = this.codemirror;
  14796. // Make sure the status variable is valid
  14797. if(!status || status.length === 0)
  14798. return;
  14799. // Set up the built-in items
  14800. var items = [];
  14801. var i, onUpdate, defaultValue;
  14802. for(i = 0; i < status.length; i++) {
  14803. // Reset some values
  14804. onUpdate = undefined;
  14805. defaultValue = undefined;
  14806. // Handle if custom or not
  14807. if(typeof status[i] === "object") {
  14808. items.push({
  14809. className: status[i].className,
  14810. defaultValue: status[i].defaultValue,
  14811. onUpdate: status[i].onUpdate
  14812. });
  14813. } else {
  14814. var name = status[i];
  14815. if(name === "words") {
  14816. defaultValue = function(el) {
  14817. el.innerHTML = wordCount(cm.getValue());
  14818. };
  14819. onUpdate = function(el) {
  14820. el.innerHTML = wordCount(cm.getValue());
  14821. };
  14822. } else if(name === "lines") {
  14823. defaultValue = function(el) {
  14824. el.innerHTML = cm.lineCount();
  14825. };
  14826. onUpdate = function(el) {
  14827. el.innerHTML = cm.lineCount();
  14828. };
  14829. } else if(name === "cursor") {
  14830. defaultValue = function(el) {
  14831. el.innerHTML = "0:0";
  14832. };
  14833. onUpdate = function(el) {
  14834. var pos = cm.getCursor();
  14835. el.innerHTML = pos.line + ":" + pos.ch;
  14836. };
  14837. } else if(name === "autosave") {
  14838. defaultValue = function(el) {
  14839. if(options.autosave != undefined && options.autosave.enabled === true) {
  14840. el.setAttribute("id", "autosaved");
  14841. }
  14842. };
  14843. }
  14844. items.push({
  14845. className: name,
  14846. defaultValue: defaultValue,
  14847. onUpdate: onUpdate
  14848. });
  14849. }
  14850. }
  14851. // Create element for the status bar
  14852. var bar = document.createElement("div");
  14853. bar.className = "editor-statusbar";
  14854. // Create a new span for each item
  14855. for(i = 0; i < items.length; i++) {
  14856. // Store in temporary variable
  14857. var item = items[i];
  14858. // Create span element
  14859. var el = document.createElement("span");
  14860. el.className = item.className;
  14861. // Ensure the defaultValue is a function
  14862. if(typeof item.defaultValue === "function") {
  14863. item.defaultValue(el);
  14864. }
  14865. // Ensure the onUpdate is a function
  14866. if(typeof item.onUpdate === "function") {
  14867. // Create a closure around the span of the current action, then execute the onUpdate handler
  14868. this.codemirror.on("update", (function(el, item) {
  14869. return function() {
  14870. item.onUpdate(el);
  14871. };
  14872. }(el, item)));
  14873. }
  14874. // Append the item to the status bar
  14875. bar.appendChild(el);
  14876. }
  14877. // Insert the status bar into the DOM
  14878. var cmWrapper = this.codemirror.getWrapperElement();
  14879. cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);
  14880. return bar;
  14881. };
  14882. /**
  14883. * Get or set the text content.
  14884. */
  14885. SimpleMDE.prototype.value = function(val) {
  14886. if(val === undefined) {
  14887. return this.codemirror.getValue();
  14888. } else {
  14889. this.codemirror.getDoc().setValue(val);
  14890. return this;
  14891. }
  14892. };
  14893. /**
  14894. * Bind static methods for exports.
  14895. */
  14896. SimpleMDE.toggleBold = toggleBold;
  14897. SimpleMDE.toggleItalic = toggleItalic;
  14898. SimpleMDE.toggleStrikethrough = toggleStrikethrough;
  14899. SimpleMDE.toggleBlockquote = toggleBlockquote;
  14900. SimpleMDE.toggleHeadingSmaller = toggleHeadingSmaller;
  14901. SimpleMDE.toggleHeadingBigger = toggleHeadingBigger;
  14902. SimpleMDE.toggleHeading1 = toggleHeading1;
  14903. SimpleMDE.toggleHeading2 = toggleHeading2;
  14904. SimpleMDE.toggleHeading3 = toggleHeading3;
  14905. SimpleMDE.toggleCodeBlock = toggleCodeBlock;
  14906. SimpleMDE.toggleUnorderedList = toggleUnorderedList;
  14907. SimpleMDE.toggleOrderedList = toggleOrderedList;
  14908. SimpleMDE.cleanBlock = cleanBlock;
  14909. SimpleMDE.drawLink = drawLink;
  14910. SimpleMDE.drawImage = drawImage;
  14911. SimpleMDE.drawTable = drawTable;
  14912. SimpleMDE.drawHorizontalRule = drawHorizontalRule;
  14913. SimpleMDE.undo = undo;
  14914. SimpleMDE.redo = redo;
  14915. SimpleMDE.togglePreview = togglePreview;
  14916. SimpleMDE.toggleSideBySide = toggleSideBySide;
  14917. SimpleMDE.toggleFullScreen = toggleFullScreen;
  14918. /**
  14919. * Bind instance methods for exports.
  14920. */
  14921. SimpleMDE.prototype.toggleBold = function() {
  14922. toggleBold(this);
  14923. };
  14924. SimpleMDE.prototype.toggleItalic = function() {
  14925. toggleItalic(this);
  14926. };
  14927. SimpleMDE.prototype.toggleStrikethrough = function() {
  14928. toggleStrikethrough(this);
  14929. };
  14930. SimpleMDE.prototype.toggleBlockquote = function() {
  14931. toggleBlockquote(this);
  14932. };
  14933. SimpleMDE.prototype.toggleHeadingSmaller = function() {
  14934. toggleHeadingSmaller(this);
  14935. };
  14936. SimpleMDE.prototype.toggleHeadingBigger = function() {
  14937. toggleHeadingBigger(this);
  14938. };
  14939. SimpleMDE.prototype.toggleHeading1 = function() {
  14940. toggleHeading1(this);
  14941. };
  14942. SimpleMDE.prototype.toggleHeading2 = function() {
  14943. toggleHeading2(this);
  14944. };
  14945. SimpleMDE.prototype.toggleHeading3 = function() {
  14946. toggleHeading3(this);
  14947. };
  14948. SimpleMDE.prototype.toggleCodeBlock = function() {
  14949. toggleCodeBlock(this);
  14950. };
  14951. SimpleMDE.prototype.toggleUnorderedList = function() {
  14952. toggleUnorderedList(this);
  14953. };
  14954. SimpleMDE.prototype.toggleOrderedList = function() {
  14955. toggleOrderedList(this);
  14956. };
  14957. SimpleMDE.prototype.cleanBlock = function() {
  14958. cleanBlock(this);
  14959. };
  14960. SimpleMDE.prototype.drawLink = function() {
  14961. drawLink(this);
  14962. };
  14963. SimpleMDE.prototype.drawImage = function() {
  14964. drawImage(this);
  14965. };
  14966. SimpleMDE.prototype.drawTable = function() {
  14967. drawTable(this);
  14968. };
  14969. SimpleMDE.prototype.drawHorizontalRule = function() {
  14970. drawHorizontalRule(this);
  14971. };
  14972. SimpleMDE.prototype.undo = function() {
  14973. undo(this);
  14974. };
  14975. SimpleMDE.prototype.redo = function() {
  14976. redo(this);
  14977. };
  14978. SimpleMDE.prototype.togglePreview = function() {
  14979. togglePreview(this);
  14980. };
  14981. SimpleMDE.prototype.toggleSideBySide = function() {
  14982. toggleSideBySide(this);
  14983. };
  14984. SimpleMDE.prototype.toggleFullScreen = function() {
  14985. toggleFullScreen(this);
  14986. };
  14987. SimpleMDE.prototype.isPreviewActive = function() {
  14988. var cm = this.codemirror;
  14989. var wrapper = cm.getWrapperElement();
  14990. var preview = wrapper.lastChild;
  14991. return /editor-preview-active/.test(preview.className);
  14992. };
  14993. SimpleMDE.prototype.isSideBySideActive = function() {
  14994. var cm = this.codemirror;
  14995. var wrapper = cm.getWrapperElement();
  14996. var preview = wrapper.nextSibling;
  14997. return /editor-preview-active-side/.test(preview.className);
  14998. };
  14999. SimpleMDE.prototype.isFullscreenActive = function() {
  15000. var cm = this.codemirror;
  15001. return cm.getOption("fullScreen");
  15002. };
  15003. SimpleMDE.prototype.getState = function() {
  15004. var cm = this.codemirror;
  15005. return getState(cm);
  15006. };
  15007. SimpleMDE.prototype.toTextArea = function() {
  15008. var cm = this.codemirror;
  15009. var wrapper = cm.getWrapperElement();
  15010. if(wrapper.parentNode) {
  15011. if(this.gui.toolbar) {
  15012. wrapper.parentNode.removeChild(this.gui.toolbar);
  15013. }
  15014. if(this.gui.statusbar) {
  15015. wrapper.parentNode.removeChild(this.gui.statusbar);
  15016. }
  15017. if(this.gui.sideBySide) {
  15018. wrapper.parentNode.removeChild(this.gui.sideBySide);
  15019. }
  15020. }
  15021. cm.toTextArea();
  15022. if(this.autosaveTimeoutId) {
  15023. clearTimeout(this.autosaveTimeoutId);
  15024. this.autosaveTimeoutId = undefined;
  15025. this.clearAutosavedValue();
  15026. }
  15027. };
  15028. module.exports = SimpleMDE;
  15029. },{"./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)
  15030. });