You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // This is CodeMirror (https://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global = global || self, global.CodeMirror = factory());
  12. }(this, (function () {
  13. 'use strict';
  14. // Kludges for bugs and behavior differences that can't be feature
  15. // detected are enabled based on userAgent etc sniffing.
  16. var userAgent = navigator.userAgent;
  17. var platform = navigator.platform;
  18. var gecko = /gecko\/\d/i.test(userAgent);
  19. var ie_upto10 = /MSIE \d/.test(userAgent);
  20. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  21. var edge = /Edge\/(\d+)/.exec(userAgent);
  22. var ie = ie_upto10 || ie_11up || edge;
  23. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  24. var webkit = !edge && /WebKit\//.test(userAgent);
  25. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  26. var chrome = !edge && /Chrome\//.test(userAgent);
  27. var presto = /Opera\//.test(userAgent);
  28. var safari = /Apple Computer/.test(navigator.vendor);
  29. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  30. var phantom = /PhantomJS/.test(userAgent);
  31. var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  32. var android = /Android/.test(userAgent);
  33. // This is woefully incomplete. Suggestions for alternative methods welcome.
  34. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  35. var mac = ios || /Mac/.test(platform);
  36. var chromeOS = /\bCrOS\b/.test(userAgent);
  37. var windows = /win/i.test(platform);
  38. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  39. if (presto_version) {
  40. presto_version = Number(presto_version[1]);
  41. }
  42. if (presto_version && presto_version >= 15) {
  43. presto = false;
  44. webkit = true;
  45. }
  46. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  47. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  48. var captureRightClick = gecko || (ie && ie_version >= 9);
  49. function classTest(cls) {
  50. return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*")
  51. }
  52. var rmClass = function (node, cls) {
  53. var current = node.className;
  54. var match = classTest(cls).exec(current);
  55. if (match) {
  56. var after = current.slice(match.index + match[0].length);
  57. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  58. }
  59. };
  60. function removeChildren(e) {
  61. for (var count = e.childNodes.length; count > 0; --count) {
  62. e.removeChild(e.firstChild);
  63. }
  64. return e
  65. }
  66. function removeChildrenAndAdd(parent, e) {
  67. return removeChildren(parent).appendChild(e)
  68. }
  69. function elt(tag, content, className, style) {
  70. var e = document.createElement(tag);
  71. if (className) {
  72. e.className = className;
  73. }
  74. if (style) {
  75. e.style.cssText = style;
  76. }
  77. if (typeof content == "string") {
  78. e.appendChild(document.createTextNode(content));
  79. } else if (content) {
  80. for (var i = 0; i < content.length; ++i) {
  81. e.appendChild(content[i]);
  82. }
  83. }
  84. return e
  85. }
  86. // wrapper for elt, which removes the elt from the accessibility tree
  87. function eltP(tag, content, className, style) {
  88. var e = elt(tag, content, className, style);
  89. e.setAttribute("role", "presentation");
  90. return e
  91. }
  92. var range;
  93. if (document.createRange) {
  94. range = function (node, start, end, endNode) {
  95. var r = document.createRange();
  96. r.setEnd(endNode || node, end);
  97. r.setStart(node, start);
  98. return r
  99. };
  100. } else {
  101. range = function (node, start, end) {
  102. var r = document.body.createTextRange();
  103. try {
  104. r.moveToElementText(node.parentNode);
  105. } catch (e) {
  106. return r
  107. }
  108. r.collapse(true);
  109. r.moveEnd("character", end);
  110. r.moveStart("character", start);
  111. return r
  112. };
  113. }
  114. function contains(parent, child) {
  115. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  116. {
  117. child = child.parentNode;
  118. }
  119. if (parent.contains) {
  120. return parent.contains(child)
  121. }
  122. do {
  123. if (child.nodeType == 11) {
  124. child = child.host;
  125. }
  126. if (child == parent) {
  127. return true
  128. }
  129. } while (child = child.parentNode)
  130. }
  131. function activeElt() {
  132. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  133. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  134. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  135. var activeElement;
  136. try {
  137. activeElement = document.activeElement;
  138. } catch (e) {
  139. activeElement = document.body || null;
  140. }
  141. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) {
  142. activeElement = activeElement.shadowRoot.activeElement;
  143. }
  144. return activeElement
  145. }
  146. function addClass(node, cls) {
  147. var current = node.className;
  148. if (!classTest(cls).test(current)) {
  149. node.className += (current ? " " : "") + cls;
  150. }
  151. }
  152. function joinClasses(a, b) {
  153. var as = a.split(" ");
  154. for (var i = 0; i < as.length; i++) {
  155. if (as[i] && !classTest(as[i]).test(b)) {
  156. b += " " + as[i];
  157. }
  158. }
  159. return b
  160. }
  161. var selectInput = function (node) {
  162. node.select();
  163. };
  164. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  165. {
  166. selectInput = function (node) {
  167. node.selectionStart = 0;
  168. node.selectionEnd = node.value.length;
  169. };
  170. } else if (ie) // Suppress mysterious IE10 errors
  171. {
  172. selectInput = function (node) {
  173. try {
  174. node.select();
  175. } catch (_e) {
  176. }
  177. };
  178. }
  179. function bind(f) {
  180. var args = Array.prototype.slice.call(arguments, 1);
  181. return function () {
  182. return f.apply(null, args)
  183. }
  184. }
  185. function copyObj(obj, target, overwrite) {
  186. if (!target) {
  187. target = {};
  188. }
  189. for (var prop in obj) {
  190. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) {
  191. target[prop] = obj[prop];
  192. }
  193. }
  194. return target
  195. }
  196. // Counts the column offset in a string, taking tabs into account.
  197. // Used mostly to find indentation.
  198. function countColumn(string, end, tabSize, startIndex, startValue) {
  199. if (end == null) {
  200. end = string.search(/[^\s\u00a0]/);
  201. if (end == -1) {
  202. end = string.length;
  203. }
  204. }
  205. for (var i = startIndex || 0, n = startValue || 0; ;) {
  206. var nextTab = string.indexOf("\t", i);
  207. if (nextTab < 0 || nextTab >= end) {
  208. return n + (end - i)
  209. }
  210. n += nextTab - i;
  211. n += tabSize - (n % tabSize);
  212. i = nextTab + 1;
  213. }
  214. }
  215. var Delayed = function () {
  216. this.id = null;
  217. this.f = null;
  218. this.time = 0;
  219. this.handler = bind(this.onTimeout, this);
  220. };
  221. Delayed.prototype.onTimeout = function (self) {
  222. self.id = 0;
  223. if (self.time <= +new Date) {
  224. self.f();
  225. } else {
  226. setTimeout(self.handler, self.time - +new Date);
  227. }
  228. };
  229. Delayed.prototype.set = function (ms, f) {
  230. this.f = f;
  231. var time = +new Date + ms;
  232. if (!this.id || time < this.time) {
  233. clearTimeout(this.id);
  234. this.id = setTimeout(this.handler, ms);
  235. this.time = time;
  236. }
  237. };
  238. function indexOf(array, elt) {
  239. for (var i = 0; i < array.length; ++i) {
  240. if (array[i] == elt) {
  241. return i
  242. }
  243. }
  244. return -1
  245. }
  246. // Number of pixels added to scroller and sizer to hide scrollbar
  247. var scrollerGap = 50;
  248. // Returned or thrown by various protocols to signal 'I'm not
  249. // handling this'.
  250. var Pass = {
  251. toString: function () {
  252. return "CodeMirror.Pass"
  253. }
  254. };
  255. // Reused option objects for setSelection & friends
  256. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  257. // The inverse of countColumn -- find the offset that corresponds to
  258. // a particular column.
  259. function findColumn(string, goal, tabSize) {
  260. for (var pos = 0, col = 0; ;) {
  261. var nextTab = string.indexOf("\t", pos);
  262. if (nextTab == -1) {
  263. nextTab = string.length;
  264. }
  265. var skipped = nextTab - pos;
  266. if (nextTab == string.length || col + skipped >= goal) {
  267. return pos + Math.min(skipped, goal - col)
  268. }
  269. col += nextTab - pos;
  270. col += tabSize - (col % tabSize);
  271. pos = nextTab + 1;
  272. if (col >= goal) {
  273. return pos
  274. }
  275. }
  276. }
  277. var spaceStrs = [""];
  278. function spaceStr(n) {
  279. while (spaceStrs.length <= n) {
  280. spaceStrs.push(lst(spaceStrs) + " ");
  281. }
  282. return spaceStrs[n]
  283. }
  284. function lst(arr) {
  285. return arr[arr.length - 1]
  286. }
  287. function map(array, f) {
  288. var out = [];
  289. for (var i = 0; i < array.length; i++) {
  290. out[i] = f(array[i], i);
  291. }
  292. return out
  293. }
  294. function insertSorted(array, value, score) {
  295. var pos = 0, priority = score(value);
  296. while (pos < array.length && score(array[pos]) <= priority) {
  297. pos++;
  298. }
  299. array.splice(pos, 0, value);
  300. }
  301. function nothing() {
  302. }
  303. function createObj(base, props) {
  304. var inst;
  305. if (Object.create) {
  306. inst = Object.create(base);
  307. } else {
  308. nothing.prototype = base;
  309. inst = new nothing();
  310. }
  311. if (props) {
  312. copyObj(props, inst);
  313. }
  314. return inst
  315. }
  316. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  317. function isWordCharBasic(ch) {
  318. return /\w/.test(ch) || ch > "\x80" &&
  319. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  320. }
  321. function isWordChar(ch, helper) {
  322. if (!helper) {
  323. return isWordCharBasic(ch)
  324. }
  325. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) {
  326. return true
  327. }
  328. return helper.test(ch)
  329. }
  330. function isEmpty(obj) {
  331. for (var n in obj) {
  332. if (obj.hasOwnProperty(n) && obj[n]) {
  333. return false
  334. }
  335. }
  336. return true
  337. }
  338. // Extending unicode characters. A series of a non-extending char +
  339. // any number of extending chars is treated as a single unit as far
  340. // as editing and measuring is concerned. This is not fully correct,
  341. // since some scripts/fonts/browsers also treat other configurations
  342. // of code points as a group.
  343. 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]/;
  344. function isExtendingChar(ch) {
  345. return ch.charCodeAt(0) >= 768 && extendingChars.test(ch)
  346. }
  347. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  348. function skipExtendingChars(str, pos, dir) {
  349. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) {
  350. pos += dir;
  351. }
  352. return pos
  353. }
  354. // Returns the value from the range [`from`; `to`] that satisfies
  355. // `pred` and is closest to `from`. Assumes that at least `to`
  356. // satisfies `pred`. Supports `from` being greater than `to`.
  357. function findFirst(pred, from, to) {
  358. // At any point we are certain `to` satisfies `pred`, don't know
  359. // whether `from` does.
  360. var dir = from > to ? -1 : 1;
  361. for (; ;) {
  362. if (from == to) {
  363. return from
  364. }
  365. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  366. if (mid == from) {
  367. return pred(mid) ? from : to
  368. }
  369. if (pred(mid)) {
  370. to = mid;
  371. } else {
  372. from = mid + dir;
  373. }
  374. }
  375. }
  376. // BIDI HELPERS
  377. function iterateBidiSections(order, from, to, f) {
  378. if (!order) {
  379. return f(from, to, "ltr", 0)
  380. }
  381. var found = false;
  382. for (var i = 0; i < order.length; ++i) {
  383. var part = order[i];
  384. if (part.from < to && part.to > from || from == to && part.to == from) {
  385. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  386. found = true;
  387. }
  388. }
  389. if (!found) {
  390. f(from, to, "ltr");
  391. }
  392. }
  393. var bidiOther = null;
  394. function getBidiPartAt(order, ch, sticky) {
  395. var found;
  396. bidiOther = null;
  397. for (var i = 0; i < order.length; ++i) {
  398. var cur = order[i];
  399. if (cur.from < ch && cur.to > ch) {
  400. return i
  401. }
  402. if (cur.to == ch) {
  403. if (cur.from != cur.to && sticky == "before") {
  404. found = i;
  405. } else {
  406. bidiOther = i;
  407. }
  408. }
  409. if (cur.from == ch) {
  410. if (cur.from != cur.to && sticky != "before") {
  411. found = i;
  412. } else {
  413. bidiOther = i;
  414. }
  415. }
  416. }
  417. return found != null ? found : bidiOther
  418. }
  419. // Bidirectional ordering algorithm
  420. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  421. // that this (partially) implements.
  422. // One-char codes used for character types:
  423. // L (L): Left-to-Right
  424. // R (R): Right-to-Left
  425. // r (AL): Right-to-Left Arabic
  426. // 1 (EN): European Number
  427. // + (ES): European Number Separator
  428. // % (ET): European Number Terminator
  429. // n (AN): Arabic Number
  430. // , (CS): Common Number Separator
  431. // m (NSM): Non-Spacing Mark
  432. // b (BN): Boundary Neutral
  433. // s (B): Paragraph Separator
  434. // t (S): Segment Separator
  435. // w (WS): Whitespace
  436. // N (ON): Other Neutrals
  437. // Returns null if characters are ordered as they appear
  438. // (left-to-right), or an array of sections ({from, to, level}
  439. // objects) in the order in which they occur visually.
  440. var bidiOrdering = (function () {
  441. // Character types for codepoints 0 to 0xff
  442. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  443. // Character types for codepoints 0x600 to 0x6f9
  444. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  445. function charType(code) {
  446. if (code <= 0xf7) {
  447. return lowTypes.charAt(code)
  448. } else if (0x590 <= code && code <= 0x5f4) {
  449. return "R"
  450. } else if (0x600 <= code && code <= 0x6f9) {
  451. return arabicTypes.charAt(code - 0x600)
  452. } else if (0x6ee <= code && code <= 0x8ac) {
  453. return "r"
  454. } else if (0x2000 <= code && code <= 0x200b) {
  455. return "w"
  456. } else if (code == 0x200c) {
  457. return "b"
  458. } else {
  459. return "L"
  460. }
  461. }
  462. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  463. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  464. function BidiSpan(level, from, to) {
  465. this.level = level;
  466. this.from = from;
  467. this.to = to;
  468. }
  469. return function (str, direction) {
  470. var outerType = direction == "ltr" ? "L" : "R";
  471. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) {
  472. return false
  473. }
  474. var len = str.length, types = [];
  475. for (var i = 0; i < len; ++i) {
  476. types.push(charType(str.charCodeAt(i)));
  477. }
  478. // W1. Examine each non-spacing mark (NSM) in the level run, and
  479. // change the type of the NSM to the type of the previous
  480. // character. If the NSM is at the start of the level run, it will
  481. // get the type of sor.
  482. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  483. var type = types[i$1];
  484. if (type == "m") {
  485. types[i$1] = prev;
  486. } else {
  487. prev = type;
  488. }
  489. }
  490. // W2. Search backwards from each instance of a European number
  491. // until the first strong type (R, L, AL, or sor) is found. If an
  492. // AL is found, change the type of the European number to Arabic
  493. // number.
  494. // W3. Change all ALs to R.
  495. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  496. var type$1 = types[i$2];
  497. if (type$1 == "1" && cur == "r") {
  498. types[i$2] = "n";
  499. } else if (isStrong.test(type$1)) {
  500. cur = type$1;
  501. if (type$1 == "r") {
  502. types[i$2] = "R";
  503. }
  504. }
  505. }
  506. // W4. A single European separator between two European numbers
  507. // changes to a European number. A single common separator between
  508. // two numbers of the same type changes to that type.
  509. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  510. var type$2 = types[i$3];
  511. if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") {
  512. types[i$3] = "1";
  513. } else if (type$2 == "," && prev$1 == types[i$3 + 1] &&
  514. (prev$1 == "1" || prev$1 == "n")) {
  515. types[i$3] = prev$1;
  516. }
  517. prev$1 = type$2;
  518. }
  519. // W5. A sequence of European terminators adjacent to European
  520. // numbers changes to all European numbers.
  521. // W6. Otherwise, separators and terminators change to Other
  522. // Neutral.
  523. for (var i$4 = 0; i$4 < len; ++i$4) {
  524. var type$3 = types[i$4];
  525. if (type$3 == ",") {
  526. types[i$4] = "N";
  527. } else if (type$3 == "%") {
  528. var end = (void 0);
  529. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {
  530. }
  531. var replace = (i$4 && types[i$4 - 1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  532. for (var j = i$4; j < end; ++j) {
  533. types[j] = replace;
  534. }
  535. i$4 = end - 1;
  536. }
  537. }
  538. // W7. Search backwards from each instance of a European number
  539. // until the first strong type (R, L, or sor) is found. If an L is
  540. // found, then change the type of the European number to L.
  541. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  542. var type$4 = types[i$5];
  543. if (cur$1 == "L" && type$4 == "1") {
  544. types[i$5] = "L";
  545. } else if (isStrong.test(type$4)) {
  546. cur$1 = type$4;
  547. }
  548. }
  549. // N1. A sequence of neutrals takes the direction of the
  550. // surrounding strong text if the text on both sides has the same
  551. // direction. European and Arabic numbers act as if they were R in
  552. // terms of their influence on neutrals. Start-of-level-run (sor)
  553. // and end-of-level-run (eor) are used at level run boundaries.
  554. // N2. Any remaining neutrals take the embedding direction.
  555. for (var i$6 = 0; i$6 < len; ++i$6) {
  556. if (isNeutral.test(types[i$6])) {
  557. var end$1 = (void 0);
  558. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {
  559. }
  560. var before = (i$6 ? types[i$6 - 1] : outerType) == "L";
  561. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  562. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  563. for (var j$1 = i$6; j$1 < end$1; ++j$1) {
  564. types[j$1] = replace$1;
  565. }
  566. i$6 = end$1 - 1;
  567. }
  568. }
  569. // Here we depart from the documented algorithm, in order to avoid
  570. // building up an actual levels array. Since there are only three
  571. // levels (0, 1, 2) in an implementation that doesn't take
  572. // explicit embedding into account, we can build up the order on
  573. // the fly, without following the level-based algorithm.
  574. var order = [], m;
  575. for (var i$7 = 0; i$7 < len;) {
  576. if (countsAsLeft.test(types[i$7])) {
  577. var start = i$7;
  578. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {
  579. }
  580. order.push(new BidiSpan(0, start, i$7));
  581. } else {
  582. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  583. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {
  584. }
  585. for (var j$2 = pos; j$2 < i$7;) {
  586. if (countsAsNum.test(types[j$2])) {
  587. if (pos < j$2) {
  588. order.splice(at, 0, new BidiSpan(1, pos, j$2));
  589. at += isRTL;
  590. }
  591. var nstart = j$2;
  592. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {
  593. }
  594. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  595. at += isRTL;
  596. pos = j$2;
  597. } else {
  598. ++j$2;
  599. }
  600. }
  601. if (pos < i$7) {
  602. order.splice(at, 0, new BidiSpan(1, pos, i$7));
  603. }
  604. }
  605. }
  606. if (direction == "ltr") {
  607. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  608. order[0].from = m[0].length;
  609. order.unshift(new BidiSpan(0, 0, m[0].length));
  610. }
  611. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  612. lst(order).to -= m[0].length;
  613. order.push(new BidiSpan(0, len - m[0].length, len));
  614. }
  615. }
  616. return direction == "rtl" ? order.reverse() : order
  617. }
  618. })();
  619. // Get the bidi ordering for the given line (and cache it). Returns
  620. // false for lines that are fully left-to-right, and an array of
  621. // BidiSpan objects otherwise.
  622. function getOrder(line, direction) {
  623. var order = line.order;
  624. if (order == null) {
  625. order = line.order = bidiOrdering(line.text, direction);
  626. }
  627. return order
  628. }
  629. // EVENT HANDLING
  630. // Lightweight event framework. on/off also work on DOM nodes,
  631. // registering native DOM handlers.
  632. var noHandlers = [];
  633. var on = function (emitter, type, f) {
  634. if (emitter.addEventListener) {
  635. emitter.addEventListener(type, f, false);
  636. } else if (emitter.attachEvent) {
  637. emitter.attachEvent("on" + type, f);
  638. } else {
  639. var map = emitter._handlers || (emitter._handlers = {});
  640. map[type] = (map[type] || noHandlers).concat(f);
  641. }
  642. };
  643. function getHandlers(emitter, type) {
  644. return emitter._handlers && emitter._handlers[type] || noHandlers
  645. }
  646. function off(emitter, type, f) {
  647. if (emitter.removeEventListener) {
  648. emitter.removeEventListener(type, f, false);
  649. } else if (emitter.detachEvent) {
  650. emitter.detachEvent("on" + type, f);
  651. } else {
  652. var map = emitter._handlers, arr = map && map[type];
  653. if (arr) {
  654. var index = indexOf(arr, f);
  655. if (index > -1) {
  656. map[type] = arr.slice(0, index).concat(arr.slice(index + 1));
  657. }
  658. }
  659. }
  660. }
  661. function signal(emitter, type /*, values...*/) {
  662. var handlers = getHandlers(emitter, type);
  663. if (!handlers.length) {
  664. return
  665. }
  666. var args = Array.prototype.slice.call(arguments, 2);
  667. for (var i = 0; i < handlers.length; ++i) {
  668. handlers[i].apply(null, args);
  669. }
  670. }
  671. // The DOM events that CodeMirror handles can be overridden by
  672. // registering a (non-DOM) handler on the editor for the event name,
  673. // and preventDefault-ing the event in that handler.
  674. function signalDOMEvent(cm, e, override) {
  675. if (typeof e == "string") {
  676. e = {
  677. type: e, preventDefault: function () {
  678. this.defaultPrevented = true;
  679. }
  680. };
  681. }
  682. signal(cm, override || e.type, cm, e);
  683. return e_defaultPrevented(e) || e.codemirrorIgnore
  684. }
  685. function signalCursorActivity(cm) {
  686. var arr = cm._handlers && cm._handlers.cursorActivity;
  687. if (!arr) {
  688. return
  689. }
  690. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  691. for (var i = 0; i < arr.length; ++i) {
  692. if (indexOf(set, arr[i]) == -1) {
  693. set.push(arr[i]);
  694. }
  695. }
  696. }
  697. function hasHandler(emitter, type) {
  698. return getHandlers(emitter, type).length > 0
  699. }
  700. // Add on and off methods to a constructor's prototype, to make
  701. // registering events on such objects more convenient.
  702. function eventMixin(ctor) {
  703. ctor.prototype.on = function (type, f) {
  704. on(this, type, f);
  705. };
  706. ctor.prototype.off = function (type, f) {
  707. off(this, type, f);
  708. };
  709. }
  710. // Due to the fact that we still support jurassic IE versions, some
  711. // compatibility wrappers are needed.
  712. function e_preventDefault(e) {
  713. if (e.preventDefault) {
  714. e.preventDefault();
  715. } else {
  716. e.returnValue = false;
  717. }
  718. }
  719. function e_stopPropagation(e) {
  720. if (e.stopPropagation) {
  721. e.stopPropagation();
  722. } else {
  723. e.cancelBubble = true;
  724. }
  725. }
  726. function e_defaultPrevented(e) {
  727. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  728. }
  729. function e_stop(e) {
  730. e_preventDefault(e);
  731. e_stopPropagation(e);
  732. }
  733. function e_target(e) {
  734. return e.target || e.srcElement
  735. }
  736. function e_button(e) {
  737. var b = e.which;
  738. if (b == null) {
  739. if (e.button & 1) {
  740. b = 1;
  741. } else if (e.button & 2) {
  742. b = 3;
  743. } else if (e.button & 4) {
  744. b = 2;
  745. }
  746. }
  747. if (mac && e.ctrlKey && b == 1) {
  748. b = 3;
  749. }
  750. return b
  751. }
  752. // Detect drag-and-drop
  753. var dragAndDrop = function () {
  754. // There is *some* kind of drag-and-drop support in IE6-8, but I
  755. // couldn't get it to work yet.
  756. if (ie && ie_version < 9) {
  757. return false
  758. }
  759. var div = elt('div');
  760. return "draggable" in div || "dragDrop" in div
  761. }();
  762. var zwspSupported;
  763. function zeroWidthElement(measure) {
  764. if (zwspSupported == null) {
  765. var test = elt("span", "\u200b");
  766. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  767. if (measure.firstChild.offsetHeight != 0) {
  768. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  769. }
  770. }
  771. var node = zwspSupported ? elt("span", "\u200b") :
  772. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  773. node.setAttribute("cm-text", "");
  774. return node
  775. }
  776. // Feature-detect IE's crummy client rect reporting for bidi text
  777. var badBidiRects;
  778. function hasBadBidiRects(measure) {
  779. if (badBidiRects != null) {
  780. return badBidiRects
  781. }
  782. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  783. var r0 = range(txt, 0, 1).getBoundingClientRect();
  784. var r1 = range(txt, 1, 2).getBoundingClientRect();
  785. removeChildren(measure);
  786. if (!r0 || r0.left == r0.right) {
  787. return false
  788. } // Safari returns null in some cases (#2780)
  789. return badBidiRects = (r1.right - r0.right < 3)
  790. }
  791. // See if "".split is the broken IE version, if so, provide an
  792. // alternative way to split lines.
  793. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  794. var pos = 0, result = [], l = string.length;
  795. while (pos <= l) {
  796. var nl = string.indexOf("\n", pos);
  797. if (nl == -1) {
  798. nl = string.length;
  799. }
  800. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  801. var rt = line.indexOf("\r");
  802. if (rt != -1) {
  803. result.push(line.slice(0, rt));
  804. pos += rt + 1;
  805. } else {
  806. result.push(line);
  807. pos = nl + 1;
  808. }
  809. }
  810. return result
  811. } : function (string) {
  812. return string.split(/\r\n?|\n/);
  813. };
  814. var hasSelection = window.getSelection ? function (te) {
  815. try {
  816. return te.selectionStart != te.selectionEnd
  817. } catch (e) {
  818. return false
  819. }
  820. } : function (te) {
  821. var range;
  822. try {
  823. range = te.ownerDocument.selection.createRange();
  824. } catch (e) {
  825. }
  826. if (!range || range.parentElement() != te) {
  827. return false
  828. }
  829. return range.compareEndPoints("StartToEnd", range) != 0
  830. };
  831. var hasCopyEvent = (function () {
  832. var e = elt("div");
  833. if ("oncopy" in e) {
  834. return true
  835. }
  836. e.setAttribute("oncopy", "return;");
  837. return typeof e.oncopy == "function"
  838. })();
  839. var badZoomedRects = null;
  840. function hasBadZoomedRects(measure) {
  841. if (badZoomedRects != null) {
  842. return badZoomedRects
  843. }
  844. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  845. var normal = node.getBoundingClientRect();
  846. var fromRange = range(node, 0, 1).getBoundingClientRect();
  847. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  848. }
  849. // Known modes, by name and by MIME
  850. var modes = {}, mimeModes = {};
  851. // Extra arguments are stored as the mode's dependencies, which is
  852. // used by (legacy) mechanisms like loadmode.js to automatically
  853. // load a mode. (Preferred mechanism is the require/define calls.)
  854. function defineMode(name, mode) {
  855. if (arguments.length > 2) {
  856. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  857. }
  858. modes[name] = mode;
  859. }
  860. function defineMIME(mime, spec) {
  861. mimeModes[mime] = spec;
  862. }
  863. // Given a MIME type, a {name, ...options} config object, or a name
  864. // string, return a mode config object.
  865. function resolveMode(spec) {
  866. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  867. spec = mimeModes[spec];
  868. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  869. var found = mimeModes[spec.name];
  870. if (typeof found == "string") {
  871. found = {name: found};
  872. }
  873. spec = createObj(found, spec);
  874. spec.name = found.name;
  875. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  876. return resolveMode("application/xml")
  877. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  878. return resolveMode("application/json")
  879. }
  880. if (typeof spec == "string") {
  881. return {name: spec}
  882. } else {
  883. return spec || {name: "null"}
  884. }
  885. }
  886. // Given a mode spec (anything that resolveMode accepts), find and
  887. // initialize an actual mode object.
  888. function getMode(options, spec) {
  889. spec = resolveMode(spec);
  890. var mfactory = modes[spec.name];
  891. if (!mfactory) {
  892. return getMode(options, "text/plain")
  893. }
  894. var modeObj = mfactory(options, spec);
  895. if (modeExtensions.hasOwnProperty(spec.name)) {
  896. var exts = modeExtensions[spec.name];
  897. for (var prop in exts) {
  898. if (!exts.hasOwnProperty(prop)) {
  899. continue
  900. }
  901. if (modeObj.hasOwnProperty(prop)) {
  902. modeObj["_" + prop] = modeObj[prop];
  903. }
  904. modeObj[prop] = exts[prop];
  905. }
  906. }
  907. modeObj.name = spec.name;
  908. if (spec.helperType) {
  909. modeObj.helperType = spec.helperType;
  910. }
  911. if (spec.modeProps) {
  912. for (var prop$1 in spec.modeProps) {
  913. modeObj[prop$1] = spec.modeProps[prop$1];
  914. }
  915. }
  916. return modeObj
  917. }
  918. // This can be used to attach properties to mode objects from
  919. // outside the actual mode definition.
  920. var modeExtensions = {};
  921. function extendMode(mode, properties) {
  922. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  923. copyObj(properties, exts);
  924. }
  925. function copyState(mode, state) {
  926. if (state === true) {
  927. return state
  928. }
  929. if (mode.copyState) {
  930. return mode.copyState(state)
  931. }
  932. var nstate = {};
  933. for (var n in state) {
  934. var val = state[n];
  935. if (val instanceof Array) {
  936. val = val.concat([]);
  937. }
  938. nstate[n] = val;
  939. }
  940. return nstate
  941. }
  942. // Given a mode and a state (for that mode), find the inner mode and
  943. // state at the position that the state refers to.
  944. function innerMode(mode, state) {
  945. var info;
  946. while (mode.innerMode) {
  947. info = mode.innerMode(state);
  948. if (!info || info.mode == mode) {
  949. break
  950. }
  951. state = info.state;
  952. mode = info.mode;
  953. }
  954. return info || {mode: mode, state: state}
  955. }
  956. function startState(mode, a1, a2) {
  957. return mode.startState ? mode.startState(a1, a2) : true
  958. }
  959. // STRING STREAM
  960. // Fed to the mode parsers, provides helper functions to make
  961. // parsers more succinct.
  962. var StringStream = function (string, tabSize, lineOracle) {
  963. this.pos = this.start = 0;
  964. this.string = string;
  965. this.tabSize = tabSize || 8;
  966. this.lastColumnPos = this.lastColumnValue = 0;
  967. this.lineStart = 0;
  968. this.lineOracle = lineOracle;
  969. };
  970. StringStream.prototype.eol = function () {
  971. return this.pos >= this.string.length
  972. };
  973. StringStream.prototype.sol = function () {
  974. return this.pos == this.lineStart
  975. };
  976. StringStream.prototype.peek = function () {
  977. return this.string.charAt(this.pos) || undefined
  978. };
  979. StringStream.prototype.next = function () {
  980. if (this.pos < this.string.length) {
  981. return this.string.charAt(this.pos++)
  982. }
  983. };
  984. StringStream.prototype.eat = function (match) {
  985. var ch = this.string.charAt(this.pos);
  986. var ok;
  987. if (typeof match == "string") {
  988. ok = ch == match;
  989. } else {
  990. ok = ch && (match.test ? match.test(ch) : match(ch));
  991. }
  992. if (ok) {
  993. ++this.pos;
  994. return ch
  995. }
  996. };
  997. StringStream.prototype.eatWhile = function (match) {
  998. var start = this.pos;
  999. while (this.eat(match)) {
  1000. }
  1001. return this.pos > start
  1002. };
  1003. StringStream.prototype.eatSpace = function () {
  1004. var start = this.pos;
  1005. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) {
  1006. ++this.pos;
  1007. }
  1008. return this.pos > start
  1009. };
  1010. StringStream.prototype.skipToEnd = function () {
  1011. this.pos = this.string.length;
  1012. };
  1013. StringStream.prototype.skipTo = function (ch) {
  1014. var found = this.string.indexOf(ch, this.pos);
  1015. if (found > -1) {
  1016. this.pos = found;
  1017. return true
  1018. }
  1019. };
  1020. StringStream.prototype.backUp = function (n) {
  1021. this.pos -= n;
  1022. };
  1023. StringStream.prototype.column = function () {
  1024. if (this.lastColumnPos < this.start) {
  1025. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  1026. this.lastColumnPos = this.start;
  1027. }
  1028. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1029. };
  1030. StringStream.prototype.indentation = function () {
  1031. return countColumn(this.string, null, this.tabSize) -
  1032. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1033. };
  1034. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1035. if (typeof pattern == "string") {
  1036. var cased = function (str) {
  1037. return caseInsensitive ? str.toLowerCase() : str;
  1038. };
  1039. var substr = this.string.substr(this.pos, pattern.length);
  1040. if (cased(substr) == cased(pattern)) {
  1041. if (consume !== false) {
  1042. this.pos += pattern.length;
  1043. }
  1044. return true
  1045. }
  1046. } else {
  1047. var match = this.string.slice(this.pos).match(pattern);
  1048. if (match && match.index > 0) {
  1049. return null
  1050. }
  1051. if (match && consume !== false) {
  1052. this.pos += match[0].length;
  1053. }
  1054. return match
  1055. }
  1056. };
  1057. StringStream.prototype.current = function () {
  1058. return this.string.slice(this.start, this.pos)
  1059. };
  1060. StringStream.prototype.hideFirstChars = function (n, inner) {
  1061. this.lineStart += n;
  1062. try {
  1063. return inner()
  1064. } finally {
  1065. this.lineStart -= n;
  1066. }
  1067. };
  1068. StringStream.prototype.lookAhead = function (n) {
  1069. var oracle = this.lineOracle;
  1070. return oracle && oracle.lookAhead(n)
  1071. };
  1072. StringStream.prototype.baseToken = function () {
  1073. var oracle = this.lineOracle;
  1074. return oracle && oracle.baseToken(this.pos)
  1075. };
  1076. // Find the line object corresponding to the given line number.
  1077. function getLine(doc, n) {
  1078. n -= doc.first;
  1079. if (n < 0 || n >= doc.size) {
  1080. throw new Error("There is no line " + (n + doc.first) + " in the document.")
  1081. }
  1082. var chunk = doc;
  1083. while (!chunk.lines) {
  1084. for (var i = 0; ; ++i) {
  1085. var child = chunk.children[i], sz = child.chunkSize();
  1086. if (n < sz) {
  1087. chunk = child;
  1088. break
  1089. }
  1090. n -= sz;
  1091. }
  1092. }
  1093. return chunk.lines[n]
  1094. }
  1095. // Get the part of a document between two positions, as an array of
  1096. // strings.
  1097. function getBetween(doc, start, end) {
  1098. var out = [], n = start.line;
  1099. doc.iter(start.line, end.line + 1, function (line) {
  1100. var text = line.text;
  1101. if (n == end.line) {
  1102. text = text.slice(0, end.ch);
  1103. }
  1104. if (n == start.line) {
  1105. text = text.slice(start.ch);
  1106. }
  1107. out.push(text);
  1108. ++n;
  1109. });
  1110. return out
  1111. }
  1112. // Get the lines between from and to, as array of strings.
  1113. function getLines(doc, from, to) {
  1114. var out = [];
  1115. doc.iter(from, to, function (line) {
  1116. out.push(line.text);
  1117. }); // iter aborts when callback returns truthy value
  1118. return out
  1119. }
  1120. // Update the height of a line, propagating the height change
  1121. // upwards to parent nodes.
  1122. function updateLineHeight(line, height) {
  1123. var diff = height - line.height;
  1124. if (diff) {
  1125. for (var n = line; n; n = n.parent) {
  1126. n.height += diff;
  1127. }
  1128. }
  1129. }
  1130. // Given a line object, find its line number by walking up through
  1131. // its parent links.
  1132. function lineNo(line) {
  1133. if (line.parent == null) {
  1134. return null
  1135. }
  1136. var cur = line.parent, no = indexOf(cur.lines, line);
  1137. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  1138. for (var i = 0; ; ++i) {
  1139. if (chunk.children[i] == cur) {
  1140. break
  1141. }
  1142. no += chunk.children[i].chunkSize();
  1143. }
  1144. }
  1145. return no + cur.first
  1146. }
  1147. // Find the line at the given vertical position, using the height
  1148. // information in the document tree.
  1149. function lineAtHeight(chunk, h) {
  1150. var n = chunk.first;
  1151. outer: do {
  1152. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  1153. var child = chunk.children[i$1], ch = child.height;
  1154. if (h < ch) {
  1155. chunk = child;
  1156. continue outer
  1157. }
  1158. h -= ch;
  1159. n += child.chunkSize();
  1160. }
  1161. return n
  1162. } while (!chunk.lines)
  1163. var i = 0;
  1164. for (; i < chunk.lines.length; ++i) {
  1165. var line = chunk.lines[i], lh = line.height;
  1166. if (h < lh) {
  1167. break
  1168. }
  1169. h -= lh;
  1170. }
  1171. return n + i
  1172. }
  1173. function isLine(doc, l) {
  1174. return l >= doc.first && l < doc.first + doc.size
  1175. }
  1176. function lineNumberFor(options, i) {
  1177. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  1178. }
  1179. // A Pos instance represents a position within the text.
  1180. function Pos(line, ch, sticky) {
  1181. if (sticky === void 0) sticky = null;
  1182. if (!(this instanceof Pos)) {
  1183. return new Pos(line, ch, sticky)
  1184. }
  1185. this.line = line;
  1186. this.ch = ch;
  1187. this.sticky = sticky;
  1188. }
  1189. // Compare two positions, return 0 if they are the same, a negative
  1190. // number when a is less, and a positive number otherwise.
  1191. function cmp(a, b) {
  1192. return a.line - b.line || a.ch - b.ch
  1193. }
  1194. function equalCursorPos(a, b) {
  1195. return a.sticky == b.sticky && cmp(a, b) == 0
  1196. }
  1197. function copyPos(x) {
  1198. return Pos(x.line, x.ch)
  1199. }
  1200. function maxPos(a, b) {
  1201. return cmp(a, b) < 0 ? b : a
  1202. }
  1203. function minPos(a, b) {
  1204. return cmp(a, b) < 0 ? a : b
  1205. }
  1206. // Most of the external API clips given positions to make sure they
  1207. // actually exist within the document.
  1208. function clipLine(doc, n) {
  1209. return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))
  1210. }
  1211. function clipPos(doc, pos) {
  1212. if (pos.line < doc.first) {
  1213. return Pos(doc.first, 0)
  1214. }
  1215. var last = doc.first + doc.size - 1;
  1216. if (pos.line > last) {
  1217. return Pos(last, getLine(doc, last).text.length)
  1218. }
  1219. return clipToLen(pos, getLine(doc, pos.line).text.length)
  1220. }
  1221. function clipToLen(pos, linelen) {
  1222. var ch = pos.ch;
  1223. if (ch == null || ch > linelen) {
  1224. return Pos(pos.line, linelen)
  1225. } else if (ch < 0) {
  1226. return Pos(pos.line, 0)
  1227. } else {
  1228. return pos
  1229. }
  1230. }
  1231. function clipPosArray(doc, array) {
  1232. var out = [];
  1233. for (var i = 0; i < array.length; i++) {
  1234. out[i] = clipPos(doc, array[i]);
  1235. }
  1236. return out
  1237. }
  1238. var SavedContext = function (state, lookAhead) {
  1239. this.state = state;
  1240. this.lookAhead = lookAhead;
  1241. };
  1242. var Context = function (doc, state, line, lookAhead) {
  1243. this.state = state;
  1244. this.doc = doc;
  1245. this.line = line;
  1246. this.maxLookAhead = lookAhead || 0;
  1247. this.baseTokens = null;
  1248. this.baseTokenPos = 1;
  1249. };
  1250. Context.prototype.lookAhead = function (n) {
  1251. var line = this.doc.getLine(this.line + n);
  1252. if (line != null && n > this.maxLookAhead) {
  1253. this.maxLookAhead = n;
  1254. }
  1255. return line
  1256. };
  1257. Context.prototype.baseToken = function (n) {
  1258. if (!this.baseTokens) {
  1259. return null
  1260. }
  1261. while (this.baseTokens[this.baseTokenPos] <= n) {
  1262. this.baseTokenPos += 2;
  1263. }
  1264. var type = this.baseTokens[this.baseTokenPos + 1];
  1265. return {
  1266. type: type && type.replace(/( |^)overlay .*/, ""),
  1267. size: this.baseTokens[this.baseTokenPos] - n
  1268. }
  1269. };
  1270. Context.prototype.nextLine = function () {
  1271. this.line++;
  1272. if (this.maxLookAhead > 0) {
  1273. this.maxLookAhead--;
  1274. }
  1275. };
  1276. Context.fromSaved = function (doc, saved, line) {
  1277. if (saved instanceof SavedContext) {
  1278. return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead)
  1279. } else {
  1280. return new Context(doc, copyState(doc.mode, saved), line)
  1281. }
  1282. };
  1283. Context.prototype.save = function (copy) {
  1284. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  1285. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1286. };
  1287. // Compute a style array (an array starting with a mode generation
  1288. // -- for invalidation -- followed by pairs of end positions and
  1289. // style strings), which is used to highlight the tokens on the
  1290. // line.
  1291. function highlightLine(cm, line, context, forceToEnd) {
  1292. // A styles array always starts with a number identifying the
  1293. // mode/overlays that it is based on (for easy invalidation).
  1294. var st = [cm.state.modeGen], lineClasses = {};
  1295. // Compute the base array of styles
  1296. runMode(cm, line.text, cm.doc.mode, context, function (end, style) {
  1297. return st.push(end, style);
  1298. },
  1299. lineClasses, forceToEnd);
  1300. var state = context.state;
  1301. // Run overlays, adjust style array.
  1302. var loop = function (o) {
  1303. context.baseTokens = st;
  1304. var overlay = cm.state.overlays[o], i = 1, at = 0;
  1305. context.state = true;
  1306. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1307. var start = i;
  1308. // Ensure there's a token end at the current position, and that i points at it
  1309. while (at < end) {
  1310. var i_end = st[i];
  1311. if (i_end > end) {
  1312. st.splice(i, 1, end, st[i + 1], i_end);
  1313. }
  1314. i += 2;
  1315. at = Math.min(end, i_end);
  1316. }
  1317. if (!style) {
  1318. return
  1319. }
  1320. if (overlay.opaque) {
  1321. st.splice(start, i - start, end, "overlay " + style);
  1322. i = start + 2;
  1323. } else {
  1324. for (; start < i; start += 2) {
  1325. var cur = st[start + 1];
  1326. st[start + 1] = (cur ? cur + " " : "") + "overlay " + style;
  1327. }
  1328. }
  1329. }, lineClasses);
  1330. context.state = state;
  1331. context.baseTokens = null;
  1332. context.baseTokenPos = 1;
  1333. };
  1334. for (var o = 0; o < cm.state.overlays.length; ++o) loop(o);
  1335. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1336. }
  1337. function getLineStyles(cm, line, updateFrontier) {
  1338. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1339. var context = getContextBefore(cm, lineNo(line));
  1340. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  1341. var result = highlightLine(cm, line, context);
  1342. if (resetState) {
  1343. context.state = resetState;
  1344. }
  1345. line.stateAfter = context.save(!resetState);
  1346. line.styles = result.styles;
  1347. if (result.classes) {
  1348. line.styleClasses = result.classes;
  1349. } else if (line.styleClasses) {
  1350. line.styleClasses = null;
  1351. }
  1352. if (updateFrontier === cm.doc.highlightFrontier) {
  1353. cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier);
  1354. }
  1355. }
  1356. return line.styles
  1357. }
  1358. function getContextBefore(cm, n, precise) {
  1359. var doc = cm.doc, display = cm.display;
  1360. if (!doc.mode.startState) {
  1361. return new Context(doc, true, n)
  1362. }
  1363. var start = findStartLine(cm, n, precise);
  1364. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1365. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1366. doc.iter(start, n, function (line) {
  1367. processLine(cm, line.text, context);
  1368. var pos = context.line;
  1369. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1370. context.nextLine();
  1371. });
  1372. if (precise) {
  1373. doc.modeFrontier = context.line;
  1374. }
  1375. return context
  1376. }
  1377. // Lightweight form of highlight -- proceed over this line and
  1378. // update state, but don't save a style array. Used for lines that
  1379. // aren't currently visible.
  1380. function processLine(cm, text, context, startAt) {
  1381. var mode = cm.doc.mode;
  1382. var stream = new StringStream(text, cm.options.tabSize, context);
  1383. stream.start = stream.pos = startAt || 0;
  1384. if (text == "") {
  1385. callBlankLine(mode, context.state);
  1386. }
  1387. while (!stream.eol()) {
  1388. readToken(mode, stream, context.state);
  1389. stream.start = stream.pos;
  1390. }
  1391. }
  1392. function callBlankLine(mode, state) {
  1393. if (mode.blankLine) {
  1394. return mode.blankLine(state)
  1395. }
  1396. if (!mode.innerMode) {
  1397. return
  1398. }
  1399. var inner = innerMode(mode, state);
  1400. if (inner.mode.blankLine) {
  1401. return inner.mode.blankLine(inner.state)
  1402. }
  1403. }
  1404. function readToken(mode, stream, state, inner) {
  1405. for (var i = 0; i < 10; i++) {
  1406. if (inner) {
  1407. inner[0] = innerMode(mode, state).mode;
  1408. }
  1409. var style = mode.token(stream, state);
  1410. if (stream.pos > stream.start) {
  1411. return style
  1412. }
  1413. }
  1414. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1415. }
  1416. var Token = function (stream, type, state) {
  1417. this.start = stream.start;
  1418. this.end = stream.pos;
  1419. this.string = stream.current();
  1420. this.type = type || null;
  1421. this.state = state;
  1422. };
  1423. // Utility for getTokenAt and getLineTokens
  1424. function takeToken(cm, pos, precise, asArray) {
  1425. var doc = cm.doc, mode = doc.mode, style;
  1426. pos = clipPos(doc, pos);
  1427. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1428. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1429. if (asArray) {
  1430. tokens = [];
  1431. }
  1432. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1433. stream.start = stream.pos;
  1434. style = readToken(mode, stream, context.state);
  1435. if (asArray) {
  1436. tokens.push(new Token(stream, style, copyState(doc.mode, context.state)));
  1437. }
  1438. }
  1439. return asArray ? tokens : new Token(stream, style, context.state)
  1440. }
  1441. function extractLineClasses(type, output) {
  1442. if (type) {
  1443. for (; ;) {
  1444. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1445. if (!lineClass) {
  1446. break
  1447. }
  1448. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1449. var prop = lineClass[1] ? "bgClass" : "textClass";
  1450. if (output[prop] == null) {
  1451. output[prop] = lineClass[2];
  1452. } else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop])) {
  1453. output[prop] += " " + lineClass[2];
  1454. }
  1455. }
  1456. }
  1457. return type
  1458. }
  1459. // Run the given mode's parser over a line, calling f for each token.
  1460. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1461. var flattenSpans = mode.flattenSpans;
  1462. if (flattenSpans == null) {
  1463. flattenSpans = cm.options.flattenSpans;
  1464. }
  1465. var curStart = 0, curStyle = null;
  1466. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1467. var inner = cm.options.addModeClass && [null];
  1468. if (text == "") {
  1469. extractLineClasses(callBlankLine(mode, context.state), lineClasses);
  1470. }
  1471. while (!stream.eol()) {
  1472. if (stream.pos > cm.options.maxHighlightLength) {
  1473. flattenSpans = false;
  1474. if (forceToEnd) {
  1475. processLine(cm, text, context, stream.pos);
  1476. }
  1477. stream.pos = text.length;
  1478. style = null;
  1479. } else {
  1480. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1481. }
  1482. if (inner) {
  1483. var mName = inner[0].name;
  1484. if (mName) {
  1485. style = "m-" + (style ? mName + " " + style : mName);
  1486. }
  1487. }
  1488. if (!flattenSpans || curStyle != style) {
  1489. while (curStart < stream.start) {
  1490. curStart = Math.min(stream.start, curStart + 5000);
  1491. f(curStart, curStyle);
  1492. }
  1493. curStyle = style;
  1494. }
  1495. stream.start = stream.pos;
  1496. }
  1497. while (curStart < stream.pos) {
  1498. // Webkit seems to refuse to render text nodes longer than 57444
  1499. // characters, and returns inaccurate measurements in nodes
  1500. // starting around 5000 chars.
  1501. var pos = Math.min(stream.pos, curStart + 5000);
  1502. f(pos, curStyle);
  1503. curStart = pos;
  1504. }
  1505. }
  1506. // Finds the line to start with when starting a parse. Tries to
  1507. // find a line with a stateAfter, so that it can start with a
  1508. // valid state. If that fails, it returns the line with the
  1509. // smallest indentation, which tends to need the least context to
  1510. // parse correctly.
  1511. function findStartLine(cm, n, precise) {
  1512. var minindent, minline, doc = cm.doc;
  1513. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1514. for (var search = n; search > lim; --search) {
  1515. if (search <= doc.first) {
  1516. return doc.first
  1517. }
  1518. var line = getLine(doc, search - 1), after = line.stateAfter;
  1519. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) {
  1520. return search
  1521. }
  1522. var indented = countColumn(line.text, null, cm.options.tabSize);
  1523. if (minline == null || minindent > indented) {
  1524. minline = search - 1;
  1525. minindent = indented;
  1526. }
  1527. }
  1528. return minline
  1529. }
  1530. function retreatFrontier(doc, n) {
  1531. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1532. if (doc.highlightFrontier < n - 10) {
  1533. return
  1534. }
  1535. var start = doc.first;
  1536. for (var line = n - 1; line > start; line--) {
  1537. var saved = getLine(doc, line).stateAfter;
  1538. // change is on 3
  1539. // state on line 1 looked ahead 2 -- so saw 3
  1540. // test 1 + 2 < 3 should cover this
  1541. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1542. start = line + 1;
  1543. break
  1544. }
  1545. }
  1546. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1547. }
  1548. // Optimize some code when these features are not used.
  1549. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1550. function seeReadOnlySpans() {
  1551. sawReadOnlySpans = true;
  1552. }
  1553. function seeCollapsedSpans() {
  1554. sawCollapsedSpans = true;
  1555. }
  1556. // TEXTMARKER SPANS
  1557. function MarkedSpan(marker, from, to) {
  1558. this.marker = marker;
  1559. this.from = from;
  1560. this.to = to;
  1561. }
  1562. // Search an array of spans for a span matching the given marker.
  1563. function getMarkedSpanFor(spans, marker) {
  1564. if (spans) {
  1565. for (var i = 0; i < spans.length; ++i) {
  1566. var span = spans[i];
  1567. if (span.marker == marker) {
  1568. return span
  1569. }
  1570. }
  1571. }
  1572. }
  1573. // Remove a span from an array, returning undefined if no spans are
  1574. // left (we don't store arrays for lines without spans).
  1575. function removeMarkedSpan(spans, span) {
  1576. var r;
  1577. for (var i = 0; i < spans.length; ++i) {
  1578. if (spans[i] != span) {
  1579. (r || (r = [])).push(spans[i]);
  1580. }
  1581. }
  1582. return r
  1583. }
  1584. // Add a span to a line.
  1585. function addMarkedSpan(line, span) {
  1586. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1587. span.marker.attachLine(line);
  1588. }
  1589. // Used for the algorithm that adjusts markers for a change in the
  1590. // document. These functions cut an array of spans at a given
  1591. // character position, returning an array of remaining chunks (or
  1592. // undefined if nothing remains).
  1593. function markedSpansBefore(old, startCh, isInsert) {
  1594. var nw;
  1595. if (old) {
  1596. for (var i = 0; i < old.length; ++i) {
  1597. var span = old[i], marker = span.marker;
  1598. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1599. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1600. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1601. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1602. }
  1603. }
  1604. }
  1605. return nw
  1606. }
  1607. function markedSpansAfter(old, endCh, isInsert) {
  1608. var nw;
  1609. if (old) {
  1610. for (var i = 0; i < old.length; ++i) {
  1611. var span = old[i], marker = span.marker;
  1612. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1613. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1614. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1615. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1616. span.to == null ? null : span.to - endCh));
  1617. }
  1618. }
  1619. }
  1620. return nw
  1621. }
  1622. // Given a change object, compute the new set of marker spans that
  1623. // cover the line in which the change took place. Removes spans
  1624. // entirely within the change, reconnects spans belonging to the
  1625. // same marker that appear on both sides of the change, and cuts off
  1626. // spans partially within the change. Returns an array of span
  1627. // arrays with one element for each line in (after) the change.
  1628. function stretchSpansOverChange(doc, change) {
  1629. if (change.full) {
  1630. return null
  1631. }
  1632. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1633. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1634. if (!oldFirst && !oldLast) {
  1635. return null
  1636. }
  1637. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1638. // Get the spans that 'stick out' on both sides
  1639. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1640. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1641. // Next, merge those two ends
  1642. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1643. if (first) {
  1644. // Fix up .to properties of first
  1645. for (var i = 0; i < first.length; ++i) {
  1646. var span = first[i];
  1647. if (span.to == null) {
  1648. var found = getMarkedSpanFor(last, span.marker);
  1649. if (!found) {
  1650. span.to = startCh;
  1651. } else if (sameLine) {
  1652. span.to = found.to == null ? null : found.to + offset;
  1653. }
  1654. }
  1655. }
  1656. }
  1657. if (last) {
  1658. // Fix up .from in last (or move them into first in case of sameLine)
  1659. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1660. var span$1 = last[i$1];
  1661. if (span$1.to != null) {
  1662. span$1.to += offset;
  1663. }
  1664. if (span$1.from == null) {
  1665. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1666. if (!found$1) {
  1667. span$1.from = offset;
  1668. if (sameLine) {
  1669. (first || (first = [])).push(span$1);
  1670. }
  1671. }
  1672. } else {
  1673. span$1.from += offset;
  1674. if (sameLine) {
  1675. (first || (first = [])).push(span$1);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. // Make sure we didn't create any zero-length spans
  1681. if (first) {
  1682. first = clearEmptySpans(first);
  1683. }
  1684. if (last && last != first) {
  1685. last = clearEmptySpans(last);
  1686. }
  1687. var newMarkers = [first];
  1688. if (!sameLine) {
  1689. // Fill gap with whole-line-spans
  1690. var gap = change.text.length - 2, gapMarkers;
  1691. if (gap > 0 && first) {
  1692. for (var i$2 = 0; i$2 < first.length; ++i$2) {
  1693. if (first[i$2].to == null) {
  1694. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null));
  1695. }
  1696. }
  1697. }
  1698. for (var i$3 = 0; i$3 < gap; ++i$3) {
  1699. newMarkers.push(gapMarkers);
  1700. }
  1701. newMarkers.push(last);
  1702. }
  1703. return newMarkers
  1704. }
  1705. // Remove spans that are empty and don't have a clearWhenEmpty
  1706. // option of false.
  1707. function clearEmptySpans(spans) {
  1708. for (var i = 0; i < spans.length; ++i) {
  1709. var span = spans[i];
  1710. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {
  1711. spans.splice(i--, 1);
  1712. }
  1713. }
  1714. if (!spans.length) {
  1715. return null
  1716. }
  1717. return spans
  1718. }
  1719. // Used to 'clip' out readOnly ranges when making a change.
  1720. function removeReadOnlyRanges(doc, from, to) {
  1721. var markers = null;
  1722. doc.iter(from.line, to.line + 1, function (line) {
  1723. if (line.markedSpans) {
  1724. for (var i = 0; i < line.markedSpans.length; ++i) {
  1725. var mark = line.markedSpans[i].marker;
  1726. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {
  1727. (markers || (markers = [])).push(mark);
  1728. }
  1729. }
  1730. }
  1731. });
  1732. if (!markers) {
  1733. return null
  1734. }
  1735. var parts = [{from: from, to: to}];
  1736. for (var i = 0; i < markers.length; ++i) {
  1737. var mk = markers[i], m = mk.find(0);
  1738. for (var j = 0; j < parts.length; ++j) {
  1739. var p = parts[j];
  1740. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) {
  1741. continue
  1742. }
  1743. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1744. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) {
  1745. newParts.push({from: p.from, to: m.from});
  1746. }
  1747. if (dto > 0 || !mk.inclusiveRight && !dto) {
  1748. newParts.push({from: m.to, to: p.to});
  1749. }
  1750. parts.splice.apply(parts, newParts);
  1751. j += newParts.length - 3;
  1752. }
  1753. }
  1754. return parts
  1755. }
  1756. // Connect or disconnect spans from a line.
  1757. function detachMarkedSpans(line) {
  1758. var spans = line.markedSpans;
  1759. if (!spans) {
  1760. return
  1761. }
  1762. for (var i = 0; i < spans.length; ++i) {
  1763. spans[i].marker.detachLine(line);
  1764. }
  1765. line.markedSpans = null;
  1766. }
  1767. function attachMarkedSpans(line, spans) {
  1768. if (!spans) {
  1769. return
  1770. }
  1771. for (var i = 0; i < spans.length; ++i) {
  1772. spans[i].marker.attachLine(line);
  1773. }
  1774. line.markedSpans = spans;
  1775. }
  1776. // Helpers used when computing which overlapping collapsed span
  1777. // counts as the larger one.
  1778. function extraLeft(marker) {
  1779. return marker.inclusiveLeft ? -1 : 0
  1780. }
  1781. function extraRight(marker) {
  1782. return marker.inclusiveRight ? 1 : 0
  1783. }
  1784. // Returns a number indicating which of two overlapping collapsed
  1785. // spans is larger (and thus includes the other). Falls back to
  1786. // comparing ids when the spans cover exactly the same range.
  1787. function compareCollapsedMarkers(a, b) {
  1788. var lenDiff = a.lines.length - b.lines.length;
  1789. if (lenDiff != 0) {
  1790. return lenDiff
  1791. }
  1792. var aPos = a.find(), bPos = b.find();
  1793. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1794. if (fromCmp) {
  1795. return -fromCmp
  1796. }
  1797. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1798. if (toCmp) {
  1799. return toCmp
  1800. }
  1801. return b.id - a.id
  1802. }
  1803. // Find out whether a line ends or starts in a collapsed span. If
  1804. // so, return the marker for that span.
  1805. function collapsedSpanAtSide(line, start) {
  1806. var sps = sawCollapsedSpans && line.markedSpans, found;
  1807. if (sps) {
  1808. for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1809. sp = sps[i];
  1810. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1811. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
  1812. found = sp.marker;
  1813. }
  1814. }
  1815. }
  1816. return found
  1817. }
  1818. function collapsedSpanAtStart(line) {
  1819. return collapsedSpanAtSide(line, true)
  1820. }
  1821. function collapsedSpanAtEnd(line) {
  1822. return collapsedSpanAtSide(line, false)
  1823. }
  1824. function collapsedSpanAround(line, ch) {
  1825. var sps = sawCollapsedSpans && line.markedSpans, found;
  1826. if (sps) {
  1827. for (var i = 0; i < sps.length; ++i) {
  1828. var sp = sps[i];
  1829. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1830. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
  1831. found = sp.marker;
  1832. }
  1833. }
  1834. }
  1835. return found
  1836. }
  1837. // Test whether there exists a collapsed span that partially
  1838. // overlaps (covers the start or end, but not both) of a new span.
  1839. // Such overlap is not allowed.
  1840. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1841. var line = getLine(doc, lineNo);
  1842. var sps = sawCollapsedSpans && line.markedSpans;
  1843. if (sps) {
  1844. for (var i = 0; i < sps.length; ++i) {
  1845. var sp = sps[i];
  1846. if (!sp.marker.collapsed) {
  1847. continue
  1848. }
  1849. var found = sp.marker.find(0);
  1850. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1851. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1852. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) {
  1853. continue
  1854. }
  1855. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1856. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) {
  1857. return true
  1858. }
  1859. }
  1860. }
  1861. }
  1862. // A visual line is a line as drawn on the screen. Folding, for
  1863. // example, can cause multiple logical lines to appear on the same
  1864. // visual line. This finds the start of the visual line that the
  1865. // given line is part of (usually that is the line itself).
  1866. function visualLine(line) {
  1867. var merged;
  1868. while (merged = collapsedSpanAtStart(line)) {
  1869. line = merged.find(-1, true).line;
  1870. }
  1871. return line
  1872. }
  1873. function visualLineEnd(line) {
  1874. var merged;
  1875. while (merged = collapsedSpanAtEnd(line)) {
  1876. line = merged.find(1, true).line;
  1877. }
  1878. return line
  1879. }
  1880. // Returns an array of logical lines that continue the visual line
  1881. // started by the argument, or undefined if there are no such lines.
  1882. function visualLineContinued(line) {
  1883. var merged, lines;
  1884. while (merged = collapsedSpanAtEnd(line)) {
  1885. line = merged.find(1, true).line
  1886. ;(lines || (lines = [])).push(line);
  1887. }
  1888. return lines
  1889. }
  1890. // Get the line number of the start of the visual line that the
  1891. // given line number is part of.
  1892. function visualLineNo(doc, lineN) {
  1893. var line = getLine(doc, lineN), vis = visualLine(line);
  1894. if (line == vis) {
  1895. return lineN
  1896. }
  1897. return lineNo(vis)
  1898. }
  1899. // Get the line number of the start of the next visual line after
  1900. // the given line.
  1901. function visualLineEndNo(doc, lineN) {
  1902. if (lineN > doc.lastLine()) {
  1903. return lineN
  1904. }
  1905. var line = getLine(doc, lineN), merged;
  1906. if (!lineIsHidden(doc, line)) {
  1907. return lineN
  1908. }
  1909. while (merged = collapsedSpanAtEnd(line)) {
  1910. line = merged.find(1, true).line;
  1911. }
  1912. return lineNo(line) + 1
  1913. }
  1914. // Compute whether a line is hidden. Lines count as hidden when they
  1915. // are part of a visual line that starts with another line, or when
  1916. // they are entirely covered by collapsed, non-widget span.
  1917. function lineIsHidden(doc, line) {
  1918. var sps = sawCollapsedSpans && line.markedSpans;
  1919. if (sps) {
  1920. for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1921. sp = sps[i];
  1922. if (!sp.marker.collapsed) {
  1923. continue
  1924. }
  1925. if (sp.from == null) {
  1926. return true
  1927. }
  1928. if (sp.marker.widgetNode) {
  1929. continue
  1930. }
  1931. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) {
  1932. return true
  1933. }
  1934. }
  1935. }
  1936. }
  1937. function lineIsHiddenInner(doc, line, span) {
  1938. if (span.to == null) {
  1939. var end = span.marker.find(1, true);
  1940. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1941. }
  1942. if (span.marker.inclusiveRight && span.to == line.text.length) {
  1943. return true
  1944. }
  1945. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1946. sp = line.markedSpans[i];
  1947. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1948. (sp.to == null || sp.to != span.from) &&
  1949. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1950. lineIsHiddenInner(doc, line, sp)) {
  1951. return true
  1952. }
  1953. }
  1954. }
  1955. // Find the height above the given line.
  1956. function heightAtLine(lineObj) {
  1957. lineObj = visualLine(lineObj);
  1958. var h = 0, chunk = lineObj.parent;
  1959. for (var i = 0; i < chunk.lines.length; ++i) {
  1960. var line = chunk.lines[i];
  1961. if (line == lineObj) {
  1962. break
  1963. } else {
  1964. h += line.height;
  1965. }
  1966. }
  1967. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1968. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1969. var cur = p.children[i$1];
  1970. if (cur == chunk) {
  1971. break
  1972. } else {
  1973. h += cur.height;
  1974. }
  1975. }
  1976. }
  1977. return h
  1978. }
  1979. // Compute the character length of a line, taking into account
  1980. // collapsed ranges (see markText) that might hide parts, and join
  1981. // other lines onto it.
  1982. function lineLength(line) {
  1983. if (line.height == 0) {
  1984. return 0
  1985. }
  1986. var len = line.text.length, merged, cur = line;
  1987. while (merged = collapsedSpanAtStart(cur)) {
  1988. var found = merged.find(0, true);
  1989. cur = found.from.line;
  1990. len += found.from.ch - found.to.ch;
  1991. }
  1992. cur = line;
  1993. while (merged = collapsedSpanAtEnd(cur)) {
  1994. var found$1 = merged.find(0, true);
  1995. len -= cur.text.length - found$1.from.ch;
  1996. cur = found$1.to.line;
  1997. len += cur.text.length - found$1.to.ch;
  1998. }
  1999. return len
  2000. }
  2001. // Find the longest line in the document.
  2002. function findMaxLine(cm) {
  2003. var d = cm.display, doc = cm.doc;
  2004. d.maxLine = getLine(doc, doc.first);
  2005. d.maxLineLength = lineLength(d.maxLine);
  2006. d.maxLineChanged = true;
  2007. doc.iter(function (line) {
  2008. var len = lineLength(line);
  2009. if (len > d.maxLineLength) {
  2010. d.maxLineLength = len;
  2011. d.maxLine = line;
  2012. }
  2013. });
  2014. }
  2015. // LINE DATA STRUCTURE
  2016. // Line objects. These hold state related to a line, including
  2017. // highlighting info (the styles array).
  2018. var Line = function (text, markedSpans, estimateHeight) {
  2019. this.text = text;
  2020. attachMarkedSpans(this, markedSpans);
  2021. this.height = estimateHeight ? estimateHeight(this) : 1;
  2022. };
  2023. Line.prototype.lineNo = function () {
  2024. return lineNo(this)
  2025. };
  2026. eventMixin(Line);
  2027. // Change the content (text, markers) of a line. Automatically
  2028. // invalidates cached information and tries to re-estimate the
  2029. // line's height.
  2030. function updateLine(line, text, markedSpans, estimateHeight) {
  2031. line.text = text;
  2032. if (line.stateAfter) {
  2033. line.stateAfter = null;
  2034. }
  2035. if (line.styles) {
  2036. line.styles = null;
  2037. }
  2038. if (line.order != null) {
  2039. line.order = null;
  2040. }
  2041. detachMarkedSpans(line);
  2042. attachMarkedSpans(line, markedSpans);
  2043. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  2044. if (estHeight != line.height) {
  2045. updateLineHeight(line, estHeight);
  2046. }
  2047. }
  2048. // Detach a line from the document tree and its markers.
  2049. function cleanUpLine(line) {
  2050. line.parent = null;
  2051. detachMarkedSpans(line);
  2052. }
  2053. // Convert a style as returned by a mode (either null, or a string
  2054. // containing one or more styles) to a CSS style. This is cached,
  2055. // and also looks for line-wide styles.
  2056. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  2057. function interpretTokenStyle(style, options) {
  2058. if (!style || /^\s*$/.test(style)) {
  2059. return null
  2060. }
  2061. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  2062. return cache[style] ||
  2063. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  2064. }
  2065. // Render the DOM representation of the text of a line. Also builds
  2066. // up a 'line map', which points at the DOM nodes that represent
  2067. // specific stretches of text, and is used by the measuring code.
  2068. // The returned object contains the DOM node, this map, and
  2069. // information about line-wide styles that were set by the mode.
  2070. function buildLineContent(cm, lineView) {
  2071. // The padding-right forces the element to have a 'border', which
  2072. // is needed on Webkit to be able to get line-level bounding
  2073. // rectangles for it (in measureChar).
  2074. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  2075. var builder = {
  2076. pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  2077. col: 0, pos: 0, cm: cm,
  2078. trailingSpace: false,
  2079. splitSpaces: cm.getOption("lineWrapping")
  2080. };
  2081. lineView.measure = {};
  2082. // Iterate over the logical lines that make up this visual line.
  2083. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  2084. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  2085. builder.pos = 0;
  2086. builder.addToken = buildToken;
  2087. // Optionally wire in some hacks into the token-rendering
  2088. // algorithm, to deal with browser quirks.
  2089. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) {
  2090. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  2091. }
  2092. builder.map = [];
  2093. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  2094. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  2095. if (line.styleClasses) {
  2096. if (line.styleClasses.bgClass) {
  2097. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  2098. }
  2099. if (line.styleClasses.textClass) {
  2100. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  2101. }
  2102. }
  2103. // Ensure at least a single node is present, for measuring.
  2104. if (builder.map.length == 0) {
  2105. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  2106. }
  2107. // Store the map and a cache object for the current logical line
  2108. if (i == 0) {
  2109. lineView.measure.map = builder.map;
  2110. lineView.measure.cache = {};
  2111. } else {
  2112. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  2113. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  2114. }
  2115. }
  2116. // See issue #2901
  2117. if (webkit) {
  2118. var last = builder.content.lastChild;
  2119. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) {
  2120. builder.content.className = "cm-tab-wrap-hack";
  2121. }
  2122. }
  2123. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  2124. if (builder.pre.className) {
  2125. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  2126. }
  2127. return builder
  2128. }
  2129. function defaultSpecialCharPlaceholder(ch) {
  2130. var token = elt("span", "\u2022", "cm-invalidchar");
  2131. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  2132. token.setAttribute("aria-label", token.title);
  2133. return token
  2134. }
  2135. // Build up the DOM representation for a single token, and add it to
  2136. // the line map. Takes care to render special characters separately.
  2137. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  2138. if (!text) {
  2139. return
  2140. }
  2141. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  2142. var special = builder.cm.state.specialChars, mustWrap = false;
  2143. var content;
  2144. if (!special.test(text)) {
  2145. builder.col += text.length;
  2146. content = document.createTextNode(displayText);
  2147. builder.map.push(builder.pos, builder.pos + text.length, content);
  2148. if (ie && ie_version < 9) {
  2149. mustWrap = true;
  2150. }
  2151. builder.pos += text.length;
  2152. } else {
  2153. content = document.createDocumentFragment();
  2154. var pos = 0;
  2155. while (true) {
  2156. special.lastIndex = pos;
  2157. var m = special.exec(text);
  2158. var skipped = m ? m.index - pos : text.length - pos;
  2159. if (skipped) {
  2160. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  2161. if (ie && ie_version < 9) {
  2162. content.appendChild(elt("span", [txt]));
  2163. } else {
  2164. content.appendChild(txt);
  2165. }
  2166. builder.map.push(builder.pos, builder.pos + skipped, txt);
  2167. builder.col += skipped;
  2168. builder.pos += skipped;
  2169. }
  2170. if (!m) {
  2171. break
  2172. }
  2173. pos += skipped + 1;
  2174. var txt$1 = (void 0);
  2175. if (m[0] == "\t") {
  2176. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  2177. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  2178. txt$1.setAttribute("role", "presentation");
  2179. txt$1.setAttribute("cm-text", "\t");
  2180. builder.col += tabWidth;
  2181. } else if (m[0] == "\r" || m[0] == "\n") {
  2182. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  2183. txt$1.setAttribute("cm-text", m[0]);
  2184. builder.col += 1;
  2185. } else {
  2186. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  2187. txt$1.setAttribute("cm-text", m[0]);
  2188. if (ie && ie_version < 9) {
  2189. content.appendChild(elt("span", [txt$1]));
  2190. } else {
  2191. content.appendChild(txt$1);
  2192. }
  2193. builder.col += 1;
  2194. }
  2195. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  2196. builder.pos++;
  2197. }
  2198. }
  2199. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  2200. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  2201. var fullStyle = style || "";
  2202. if (startStyle) {
  2203. fullStyle += startStyle;
  2204. }
  2205. if (endStyle) {
  2206. fullStyle += endStyle;
  2207. }
  2208. var token = elt("span", [content], fullStyle, css);
  2209. if (attributes) {
  2210. for (var attr in attributes) {
  2211. if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") {
  2212. token.setAttribute(attr, attributes[attr]);
  2213. }
  2214. }
  2215. }
  2216. return builder.content.appendChild(token)
  2217. }
  2218. builder.content.appendChild(content);
  2219. }
  2220. // Change some spaces to NBSP to prevent the browser from collapsing
  2221. // trailing spaces at the end of a line when rendering text (issue #1362).
  2222. function splitSpaces(text, trailingBefore) {
  2223. if (text.length > 1 && !/ /.test(text)) {
  2224. return text
  2225. }
  2226. var spaceBefore = trailingBefore, result = "";
  2227. for (var i = 0; i < text.length; i++) {
  2228. var ch = text.charAt(i);
  2229. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) {
  2230. ch = "\u00a0";
  2231. }
  2232. result += ch;
  2233. spaceBefore = ch == " ";
  2234. }
  2235. return result
  2236. }
  2237. // Work around nonsense dimensions being reported for stretches of
  2238. // right-to-left text.
  2239. function buildTokenBadBidi(inner, order) {
  2240. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  2241. style = style ? style + " cm-force-border" : "cm-force-border";
  2242. var start = builder.pos, end = start + text.length;
  2243. for (; ;) {
  2244. // Find the part that overlaps with the start of this text
  2245. var part = (void 0);
  2246. for (var i = 0; i < order.length; i++) {
  2247. part = order[i];
  2248. if (part.to > start && part.from <= start) {
  2249. break
  2250. }
  2251. }
  2252. if (part.to >= end) {
  2253. return inner(builder, text, style, startStyle, endStyle, css, attributes)
  2254. }
  2255. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  2256. startStyle = null;
  2257. text = text.slice(part.to - start);
  2258. start = part.to;
  2259. }
  2260. }
  2261. }
  2262. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  2263. var widget = !ignoreWidget && marker.widgetNode;
  2264. if (widget) {
  2265. builder.map.push(builder.pos, builder.pos + size, widget);
  2266. }
  2267. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  2268. if (!widget) {
  2269. widget = builder.content.appendChild(document.createElement("span"));
  2270. }
  2271. widget.setAttribute("cm-marker", marker.id);
  2272. }
  2273. if (widget) {
  2274. builder.cm.display.input.setUneditable(widget);
  2275. builder.content.appendChild(widget);
  2276. }
  2277. builder.pos += size;
  2278. builder.trailingSpace = false;
  2279. }
  2280. // Outputs a number of spans to make up a line, taking highlighting
  2281. // and marked text into account.
  2282. function insertLineContent(line, builder, styles) {
  2283. var spans = line.markedSpans, allText = line.text, at = 0;
  2284. if (!spans) {
  2285. for (var i$1 = 1; i$1 < styles.length; i$1 += 2) {
  2286. builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1 + 1], builder.cm.options));
  2287. }
  2288. return
  2289. }
  2290. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  2291. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  2292. for (; ;) {
  2293. if (nextChange == pos) { // Update current marker set
  2294. spanStyle = spanEndStyle = spanStartStyle = css = "";
  2295. attributes = null;
  2296. collapsed = null;
  2297. nextChange = Infinity;
  2298. var foundBookmarks = [], endStyles = (void 0);
  2299. for (var j = 0; j < spans.length; ++j) {
  2300. var sp = spans[j], m = sp.marker;
  2301. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  2302. foundBookmarks.push(m);
  2303. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  2304. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  2305. nextChange = sp.to;
  2306. spanEndStyle = "";
  2307. }
  2308. if (m.className) {
  2309. spanStyle += " " + m.className;
  2310. }
  2311. if (m.css) {
  2312. css = (css ? css + ";" : "") + m.css;
  2313. }
  2314. if (m.startStyle && sp.from == pos) {
  2315. spanStartStyle += " " + m.startStyle;
  2316. }
  2317. if (m.endStyle && sp.to == nextChange) {
  2318. (endStyles || (endStyles = [])).push(m.endStyle, sp.to);
  2319. }
  2320. // support for the old title property
  2321. // https://github.com/codemirror/CodeMirror/pull/5673
  2322. if (m.title) {
  2323. (attributes || (attributes = {})).title = m.title;
  2324. }
  2325. if (m.attributes) {
  2326. for (var attr in m.attributes) {
  2327. (attributes || (attributes = {}))[attr] = m.attributes[attr];
  2328. }
  2329. }
  2330. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) {
  2331. collapsed = sp;
  2332. }
  2333. } else if (sp.from > pos && nextChange > sp.from) {
  2334. nextChange = sp.from;
  2335. }
  2336. }
  2337. if (endStyles) {
  2338. for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) {
  2339. if (endStyles[j$1 + 1] == nextChange) {
  2340. spanEndStyle += " " + endStyles[j$1];
  2341. }
  2342. }
  2343. }
  2344. if (!collapsed || collapsed.from == pos) {
  2345. for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) {
  2346. buildCollapsedSpan(builder, 0, foundBookmarks[j$2]);
  2347. }
  2348. }
  2349. if (collapsed && (collapsed.from || 0) == pos) {
  2350. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  2351. collapsed.marker, collapsed.from == null);
  2352. if (collapsed.to == null) {
  2353. return
  2354. }
  2355. if (collapsed.to == pos) {
  2356. collapsed = false;
  2357. }
  2358. }
  2359. }
  2360. if (pos >= len) {
  2361. break
  2362. }
  2363. var upto = Math.min(len, nextChange);
  2364. while (true) {
  2365. if (text) {
  2366. var end = pos + text.length;
  2367. if (!collapsed) {
  2368. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  2369. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  2370. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  2371. }
  2372. if (end >= upto) {
  2373. text = text.slice(upto - pos);
  2374. pos = upto;
  2375. break
  2376. }
  2377. pos = end;
  2378. spanStartStyle = "";
  2379. }
  2380. text = allText.slice(at, at = styles[i++]);
  2381. style = interpretTokenStyle(styles[i++], builder.cm.options);
  2382. }
  2383. }
  2384. }
  2385. // These objects are used to represent the visible (currently drawn)
  2386. // part of the document. A LineView may correspond to multiple
  2387. // logical lines, if those are connected by collapsed ranges.
  2388. function LineView(doc, line, lineN) {
  2389. // The starting line
  2390. this.line = line;
  2391. // Continuing lines, if any
  2392. this.rest = visualLineContinued(line);
  2393. // Number of logical lines in this visual line
  2394. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2395. this.node = this.text = null;
  2396. this.hidden = lineIsHidden(doc, line);
  2397. }
  2398. // Create a range of LineView objects for the given lines.
  2399. function buildViewArray(cm, from, to) {
  2400. var array = [], nextPos;
  2401. for (var pos = from; pos < to; pos = nextPos) {
  2402. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2403. nextPos = pos + view.size;
  2404. array.push(view);
  2405. }
  2406. return array
  2407. }
  2408. var operationGroup = null;
  2409. function pushOperation(op) {
  2410. if (operationGroup) {
  2411. operationGroup.ops.push(op);
  2412. } else {
  2413. op.ownsGroup = operationGroup = {
  2414. ops: [op],
  2415. delayedCallbacks: []
  2416. };
  2417. }
  2418. }
  2419. function fireCallbacksForOps(group) {
  2420. // Calls delayed callbacks and cursorActivity handlers until no
  2421. // new ones appear
  2422. var callbacks = group.delayedCallbacks, i = 0;
  2423. do {
  2424. for (; i < callbacks.length; i++) {
  2425. callbacks[i].call(null);
  2426. }
  2427. for (var j = 0; j < group.ops.length; j++) {
  2428. var op = group.ops[j];
  2429. if (op.cursorActivityHandlers) {
  2430. while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {
  2431. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  2432. }
  2433. }
  2434. }
  2435. } while (i < callbacks.length)
  2436. }
  2437. function finishOperation(op, endCb) {
  2438. var group = op.ownsGroup;
  2439. if (!group) {
  2440. return
  2441. }
  2442. try {
  2443. fireCallbacksForOps(group);
  2444. } finally {
  2445. operationGroup = null;
  2446. endCb(group);
  2447. }
  2448. }
  2449. var orphanDelayedCallbacks = null;
  2450. // Often, we want to signal events at a point where we are in the
  2451. // middle of some work, but don't want the handler to start calling
  2452. // other methods on the editor, which might be in an inconsistent
  2453. // state or simply not expect any other events to happen.
  2454. // signalLater looks whether there are any handlers, and schedules
  2455. // them to be executed when the last operation ends, or, if no
  2456. // operation is active, when a timeout fires.
  2457. function signalLater(emitter, type /*, values...*/) {
  2458. var arr = getHandlers(emitter, type);
  2459. if (!arr.length) {
  2460. return
  2461. }
  2462. var args = Array.prototype.slice.call(arguments, 2), list;
  2463. if (operationGroup) {
  2464. list = operationGroup.delayedCallbacks;
  2465. } else if (orphanDelayedCallbacks) {
  2466. list = orphanDelayedCallbacks;
  2467. } else {
  2468. list = orphanDelayedCallbacks = [];
  2469. setTimeout(fireOrphanDelayed, 0);
  2470. }
  2471. var loop = function (i) {
  2472. list.push(function () {
  2473. return arr[i].apply(null, args);
  2474. });
  2475. };
  2476. for (var i = 0; i < arr.length; ++i)
  2477. loop(i);
  2478. }
  2479. function fireOrphanDelayed() {
  2480. var delayed = orphanDelayedCallbacks;
  2481. orphanDelayedCallbacks = null;
  2482. for (var i = 0; i < delayed.length; ++i) {
  2483. delayed[i]();
  2484. }
  2485. }
  2486. // When an aspect of a line changes, a string is added to
  2487. // lineView.changes. This updates the relevant part of the line's
  2488. // DOM structure.
  2489. function updateLineForChanges(cm, lineView, lineN, dims) {
  2490. for (var j = 0; j < lineView.changes.length; j++) {
  2491. var type = lineView.changes[j];
  2492. if (type == "text") {
  2493. updateLineText(cm, lineView);
  2494. } else if (type == "gutter") {
  2495. updateLineGutter(cm, lineView, lineN, dims);
  2496. } else if (type == "class") {
  2497. updateLineClasses(cm, lineView);
  2498. } else if (type == "widget") {
  2499. updateLineWidgets(cm, lineView, dims);
  2500. }
  2501. }
  2502. lineView.changes = null;
  2503. }
  2504. // Lines with gutter elements, widgets or a background class need to
  2505. // be wrapped, and have the extra elements added to the wrapper div
  2506. function ensureLineWrapped(lineView) {
  2507. if (lineView.node == lineView.text) {
  2508. lineView.node = elt("div", null, null, "position: relative");
  2509. if (lineView.text.parentNode) {
  2510. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  2511. }
  2512. lineView.node.appendChild(lineView.text);
  2513. if (ie && ie_version < 8) {
  2514. lineView.node.style.zIndex = 2;
  2515. }
  2516. }
  2517. return lineView.node
  2518. }
  2519. function updateLineBackground(cm, lineView) {
  2520. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  2521. if (cls) {
  2522. cls += " CodeMirror-linebackground";
  2523. }
  2524. if (lineView.background) {
  2525. if (cls) {
  2526. lineView.background.className = cls;
  2527. } else {
  2528. lineView.background.parentNode.removeChild(lineView.background);
  2529. lineView.background = null;
  2530. }
  2531. } else if (cls) {
  2532. var wrap = ensureLineWrapped(lineView);
  2533. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  2534. cm.display.input.setUneditable(lineView.background);
  2535. }
  2536. }
  2537. // Wrapper around buildLineContent which will reuse the structure
  2538. // in display.externalMeasured when possible.
  2539. function getLineContent(cm, lineView) {
  2540. var ext = cm.display.externalMeasured;
  2541. if (ext && ext.line == lineView.line) {
  2542. cm.display.externalMeasured = null;
  2543. lineView.measure = ext.measure;
  2544. return ext.built
  2545. }
  2546. return buildLineContent(cm, lineView)
  2547. }
  2548. // Redraw the line's text. Interacts with the background and text
  2549. // classes because the mode may output tokens that influence these
  2550. // classes.
  2551. function updateLineText(cm, lineView) {
  2552. var cls = lineView.text.className;
  2553. var built = getLineContent(cm, lineView);
  2554. if (lineView.text == lineView.node) {
  2555. lineView.node = built.pre;
  2556. }
  2557. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2558. lineView.text = built.pre;
  2559. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2560. lineView.bgClass = built.bgClass;
  2561. lineView.textClass = built.textClass;
  2562. updateLineClasses(cm, lineView);
  2563. } else if (cls) {
  2564. lineView.text.className = cls;
  2565. }
  2566. }
  2567. function updateLineClasses(cm, lineView) {
  2568. updateLineBackground(cm, lineView);
  2569. if (lineView.line.wrapClass) {
  2570. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  2571. } else if (lineView.node != lineView.text) {
  2572. lineView.node.className = "";
  2573. }
  2574. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2575. lineView.text.className = textClass || "";
  2576. }
  2577. function updateLineGutter(cm, lineView, lineN, dims) {
  2578. if (lineView.gutter) {
  2579. lineView.node.removeChild(lineView.gutter);
  2580. lineView.gutter = null;
  2581. }
  2582. if (lineView.gutterBackground) {
  2583. lineView.node.removeChild(lineView.gutterBackground);
  2584. lineView.gutterBackground = null;
  2585. }
  2586. if (lineView.line.gutterClass) {
  2587. var wrap = ensureLineWrapped(lineView);
  2588. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2589. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  2590. cm.display.input.setUneditable(lineView.gutterBackground);
  2591. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2592. }
  2593. var markers = lineView.line.gutterMarkers;
  2594. if (cm.options.lineNumbers || markers) {
  2595. var wrap$1 = ensureLineWrapped(lineView);
  2596. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2597. cm.display.input.setUneditable(gutterWrap);
  2598. wrap$1.insertBefore(gutterWrap, lineView.text);
  2599. if (lineView.line.gutterClass) {
  2600. gutterWrap.className += " " + lineView.line.gutterClass;
  2601. }
  2602. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) {
  2603. lineView.lineNumber = gutterWrap.appendChild(
  2604. elt("div", lineNumberFor(cm.options, lineN),
  2605. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2606. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px")));
  2607. }
  2608. if (markers) {
  2609. for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2610. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2611. if (found) {
  2612. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2613. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px")));
  2614. }
  2615. }
  2616. }
  2617. }
  2618. }
  2619. function updateLineWidgets(cm, lineView, dims) {
  2620. if (lineView.alignable) {
  2621. lineView.alignable = null;
  2622. }
  2623. var isWidget = classTest("CodeMirror-linewidget");
  2624. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2625. next = node.nextSibling;
  2626. if (isWidget.test(node.className)) {
  2627. lineView.node.removeChild(node);
  2628. }
  2629. }
  2630. insertLineWidgets(cm, lineView, dims);
  2631. }
  2632. // Build a line's DOM representation from scratch
  2633. function buildLineElement(cm, lineView, lineN, dims) {
  2634. var built = getLineContent(cm, lineView);
  2635. lineView.text = lineView.node = built.pre;
  2636. if (built.bgClass) {
  2637. lineView.bgClass = built.bgClass;
  2638. }
  2639. if (built.textClass) {
  2640. lineView.textClass = built.textClass;
  2641. }
  2642. updateLineClasses(cm, lineView);
  2643. updateLineGutter(cm, lineView, lineN, dims);
  2644. insertLineWidgets(cm, lineView, dims);
  2645. return lineView.node
  2646. }
  2647. // A lineView may contain multiple logical lines (when merged by
  2648. // collapsed spans). The widgets for all of them need to be drawn.
  2649. function insertLineWidgets(cm, lineView, dims) {
  2650. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2651. if (lineView.rest) {
  2652. for (var i = 0; i < lineView.rest.length; i++) {
  2653. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  2654. }
  2655. }
  2656. }
  2657. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2658. if (!line.widgets) {
  2659. return
  2660. }
  2661. var wrap = ensureLineWrapped(lineView);
  2662. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2663. var widget = ws[i],
  2664. node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2665. if (!widget.handleMouseEvents) {
  2666. node.setAttribute("cm-ignore-events", "true");
  2667. }
  2668. positionLineWidget(widget, node, lineView, dims);
  2669. cm.display.input.setUneditable(node);
  2670. if (allowAbove && widget.above) {
  2671. wrap.insertBefore(node, lineView.gutter || lineView.text);
  2672. } else {
  2673. wrap.appendChild(node);
  2674. }
  2675. signalLater(widget, "redraw");
  2676. }
  2677. }
  2678. function positionLineWidget(widget, node, lineView, dims) {
  2679. if (widget.noHScroll) {
  2680. (lineView.alignable || (lineView.alignable = [])).push(node);
  2681. var width = dims.wrapperWidth;
  2682. node.style.left = dims.fixedPos + "px";
  2683. if (!widget.coverGutter) {
  2684. width -= dims.gutterTotalWidth;
  2685. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2686. }
  2687. node.style.width = width + "px";
  2688. }
  2689. if (widget.coverGutter) {
  2690. node.style.zIndex = 5;
  2691. node.style.position = "relative";
  2692. if (!widget.noHScroll) {
  2693. node.style.marginLeft = -dims.gutterTotalWidth + "px";
  2694. }
  2695. }
  2696. }
  2697. function widgetHeight(widget) {
  2698. if (widget.height != null) {
  2699. return widget.height
  2700. }
  2701. var cm = widget.doc.cm;
  2702. if (!cm) {
  2703. return 0
  2704. }
  2705. if (!contains(document.body, widget.node)) {
  2706. var parentStyle = "position: relative;";
  2707. if (widget.coverGutter) {
  2708. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  2709. }
  2710. if (widget.noHScroll) {
  2711. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  2712. }
  2713. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2714. }
  2715. return widget.height = widget.node.parentNode.offsetHeight
  2716. }
  2717. // Return true when the given mouse event happened in a widget
  2718. function eventInWidget(display, e) {
  2719. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2720. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2721. (n.parentNode == display.sizer && n != display.mover)) {
  2722. return true
  2723. }
  2724. }
  2725. }
  2726. // POSITION MEASUREMENT
  2727. function paddingTop(display) {
  2728. return display.lineSpace.offsetTop
  2729. }
  2730. function paddingVert(display) {
  2731. return display.mover.offsetHeight - display.lineSpace.offsetHeight
  2732. }
  2733. function paddingH(display) {
  2734. if (display.cachedPaddingH) {
  2735. return display.cachedPaddingH
  2736. }
  2737. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2738. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2739. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2740. if (!isNaN(data.left) && !isNaN(data.right)) {
  2741. display.cachedPaddingH = data;
  2742. }
  2743. return data
  2744. }
  2745. function scrollGap(cm) {
  2746. return scrollerGap - cm.display.nativeBarWidth
  2747. }
  2748. function displayWidth(cm) {
  2749. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2750. }
  2751. function displayHeight(cm) {
  2752. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2753. }
  2754. // Ensure the lineView.wrapping.heights array is populated. This is
  2755. // an array of bottom offsets for the lines that make up a drawn
  2756. // line. When lineWrapping is on, there might be more than one
  2757. // height.
  2758. function ensureLineHeights(cm, lineView, rect) {
  2759. var wrapping = cm.options.lineWrapping;
  2760. var curWidth = wrapping && displayWidth(cm);
  2761. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2762. var heights = lineView.measure.heights = [];
  2763. if (wrapping) {
  2764. lineView.measure.width = curWidth;
  2765. var rects = lineView.text.firstChild.getClientRects();
  2766. for (var i = 0; i < rects.length - 1; i++) {
  2767. var cur = rects[i], next = rects[i + 1];
  2768. if (Math.abs(cur.bottom - next.bottom) > 2) {
  2769. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2770. }
  2771. }
  2772. }
  2773. heights.push(rect.bottom - rect.top);
  2774. }
  2775. }
  2776. // Find a line map (mapping character offsets to text nodes) and a
  2777. // measurement cache for the given line number. (A line view might
  2778. // contain multiple lines when collapsed ranges are present.)
  2779. function mapFromLineView(lineView, line, lineN) {
  2780. if (lineView.line == line) {
  2781. return {map: lineView.measure.map, cache: lineView.measure.cache}
  2782. }
  2783. for (var i = 0; i < lineView.rest.length; i++) {
  2784. if (lineView.rest[i] == line) {
  2785. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}
  2786. }
  2787. }
  2788. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) {
  2789. if (lineNo(lineView.rest[i$1]) > lineN) {
  2790. return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true}
  2791. }
  2792. }
  2793. }
  2794. // Render a line into the hidden node display.externalMeasured. Used
  2795. // when measurement is needed for a line that's not in the viewport.
  2796. function updateExternalMeasurement(cm, line) {
  2797. line = visualLine(line);
  2798. var lineN = lineNo(line);
  2799. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2800. view.lineN = lineN;
  2801. var built = view.built = buildLineContent(cm, view);
  2802. view.text = built.pre;
  2803. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2804. return view
  2805. }
  2806. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2807. // for a given character.
  2808. function measureChar(cm, line, ch, bias) {
  2809. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2810. }
  2811. // Find a line view that corresponds to the given line number.
  2812. function findViewForLine(cm, lineN) {
  2813. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {
  2814. return cm.display.view[findViewIndex(cm, lineN)]
  2815. }
  2816. var ext = cm.display.externalMeasured;
  2817. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) {
  2818. return ext
  2819. }
  2820. }
  2821. // Measurement can be split in two steps, the set-up work that
  2822. // applies to the whole line, and the measurement of the actual
  2823. // character. Functions like coordsChar, that need to do a lot of
  2824. // measurements in a row, can thus ensure that the set-up work is
  2825. // only done once.
  2826. function prepareMeasureForLine(cm, line) {
  2827. var lineN = lineNo(line);
  2828. var view = findViewForLine(cm, lineN);
  2829. if (view && !view.text) {
  2830. view = null;
  2831. } else if (view && view.changes) {
  2832. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2833. cm.curOp.forceUpdate = true;
  2834. }
  2835. if (!view) {
  2836. view = updateExternalMeasurement(cm, line);
  2837. }
  2838. var info = mapFromLineView(view, line, lineN);
  2839. return {
  2840. line: line, view: view, rect: null,
  2841. map: info.map, cache: info.cache, before: info.before,
  2842. hasHeights: false
  2843. }
  2844. }
  2845. // Given a prepared measurement object, measures the position of an
  2846. // actual character (or fetches it from the cache).
  2847. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2848. if (prepared.before) {
  2849. ch = -1;
  2850. }
  2851. var key = ch + (bias || ""), found;
  2852. if (prepared.cache.hasOwnProperty(key)) {
  2853. found = prepared.cache[key];
  2854. } else {
  2855. if (!prepared.rect) {
  2856. prepared.rect = prepared.view.text.getBoundingClientRect();
  2857. }
  2858. if (!prepared.hasHeights) {
  2859. ensureLineHeights(cm, prepared.view, prepared.rect);
  2860. prepared.hasHeights = true;
  2861. }
  2862. found = measureCharInner(cm, prepared, ch, bias);
  2863. if (!found.bogus) {
  2864. prepared.cache[key] = found;
  2865. }
  2866. }
  2867. return {
  2868. left: found.left, right: found.right,
  2869. top: varHeight ? found.rtop : found.top,
  2870. bottom: varHeight ? found.rbottom : found.bottom
  2871. }
  2872. }
  2873. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2874. function nodeAndOffsetInLineMap(map, ch, bias) {
  2875. var node, start, end, collapse, mStart, mEnd;
  2876. // First, search the line map for the text node corresponding to,
  2877. // or closest to, the target character.
  2878. for (var i = 0; i < map.length; i += 3) {
  2879. mStart = map[i];
  2880. mEnd = map[i + 1];
  2881. if (ch < mStart) {
  2882. start = 0;
  2883. end = 1;
  2884. collapse = "left";
  2885. } else if (ch < mEnd) {
  2886. start = ch - mStart;
  2887. end = start + 1;
  2888. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2889. end = mEnd - mStart;
  2890. start = end - 1;
  2891. if (ch >= mEnd) {
  2892. collapse = "right";
  2893. }
  2894. }
  2895. if (start != null) {
  2896. node = map[i + 2];
  2897. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) {
  2898. collapse = bias;
  2899. }
  2900. if (bias == "left" && start == 0) {
  2901. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2902. node = map[(i -= 3) + 2];
  2903. collapse = "left";
  2904. }
  2905. }
  2906. if (bias == "right" && start == mEnd - mStart) {
  2907. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2908. node = map[(i += 3) + 2];
  2909. collapse = "right";
  2910. }
  2911. }
  2912. break
  2913. }
  2914. }
  2915. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2916. }
  2917. function getUsefulRect(rects, bias) {
  2918. var rect = nullRect;
  2919. if (bias == "left") {
  2920. for (var i = 0; i < rects.length; i++) {
  2921. if ((rect = rects[i]).left != rect.right) {
  2922. break
  2923. }
  2924. }
  2925. } else {
  2926. for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2927. if ((rect = rects[i$1]).left != rect.right) {
  2928. break
  2929. }
  2930. }
  2931. }
  2932. return rect
  2933. }
  2934. function measureCharInner(cm, prepared, ch, bias) {
  2935. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2936. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2937. var rect;
  2938. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2939. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2940. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) {
  2941. --start;
  2942. }
  2943. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) {
  2944. ++end;
  2945. }
  2946. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2947. rect = node.parentNode.getBoundingClientRect();
  2948. } else {
  2949. rect = getUsefulRect(range(node, start, end).getClientRects(), bias);
  2950. }
  2951. if (rect.left || rect.right || start == 0) {
  2952. break
  2953. }
  2954. end = start;
  2955. start = start - 1;
  2956. collapse = "right";
  2957. }
  2958. if (ie && ie_version < 11) {
  2959. rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2960. }
  2961. } else { // If it is a widget, simply get the box for the whole widget.
  2962. if (start > 0) {
  2963. collapse = bias = "right";
  2964. }
  2965. var rects;
  2966. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {
  2967. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2968. } else {
  2969. rect = node.getBoundingClientRect();
  2970. }
  2971. }
  2972. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2973. var rSpan = node.parentNode.getClientRects()[0];
  2974. if (rSpan) {
  2975. rect = {
  2976. left: rSpan.left,
  2977. right: rSpan.left + charWidth(cm.display),
  2978. top: rSpan.top,
  2979. bottom: rSpan.bottom
  2980. };
  2981. } else {
  2982. rect = nullRect;
  2983. }
  2984. }
  2985. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2986. var mid = (rtop + rbot) / 2;
  2987. var heights = prepared.view.measure.heights;
  2988. var i = 0;
  2989. for (; i < heights.length - 1; i++) {
  2990. if (mid < heights[i]) {
  2991. break
  2992. }
  2993. }
  2994. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2995. var result = {
  2996. left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2997. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2998. top: top, bottom: bot
  2999. };
  3000. if (!rect.left && !rect.right) {
  3001. result.bogus = true;
  3002. }
  3003. if (!cm.options.singleCursorHeightPerLine) {
  3004. result.rtop = rtop;
  3005. result.rbottom = rbot;
  3006. }
  3007. return result
  3008. }
  3009. // Work around problem with bounding client rects on ranges being
  3010. // returned incorrectly when zoomed on IE10 and below.
  3011. function maybeUpdateRectForZooming(measure, rect) {
  3012. if (!window.screen || screen.logicalXDPI == null ||
  3013. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {
  3014. return rect
  3015. }
  3016. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  3017. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  3018. return {
  3019. left: rect.left * scaleX, right: rect.right * scaleX,
  3020. top: rect.top * scaleY, bottom: rect.bottom * scaleY
  3021. }
  3022. }
  3023. function clearLineMeasurementCacheFor(lineView) {
  3024. if (lineView.measure) {
  3025. lineView.measure.cache = {};
  3026. lineView.measure.heights = null;
  3027. if (lineView.rest) {
  3028. for (var i = 0; i < lineView.rest.length; i++) {
  3029. lineView.measure.caches[i] = {};
  3030. }
  3031. }
  3032. }
  3033. }
  3034. function clearLineMeasurementCache(cm) {
  3035. cm.display.externalMeasure = null;
  3036. removeChildren(cm.display.lineMeasure);
  3037. for (var i = 0; i < cm.display.view.length; i++) {
  3038. clearLineMeasurementCacheFor(cm.display.view[i]);
  3039. }
  3040. }
  3041. function clearCaches(cm) {
  3042. clearLineMeasurementCache(cm);
  3043. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  3044. if (!cm.options.lineWrapping) {
  3045. cm.display.maxLineChanged = true;
  3046. }
  3047. cm.display.lineNumChars = null;
  3048. }
  3049. function pageScrollX() {
  3050. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  3051. // which causes page_Offset and bounding client rects to use
  3052. // different reference viewports and invalidate our calculations.
  3053. if (chrome && android) {
  3054. return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft))
  3055. }
  3056. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  3057. }
  3058. function pageScrollY() {
  3059. if (chrome && android) {
  3060. return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop))
  3061. }
  3062. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  3063. }
  3064. function widgetTopHeight(lineObj) {
  3065. var height = 0;
  3066. if (lineObj.widgets) {
  3067. for (var i = 0; i < lineObj.widgets.length; ++i) {
  3068. if (lineObj.widgets[i].above) {
  3069. height += widgetHeight(lineObj.widgets[i]);
  3070. }
  3071. }
  3072. }
  3073. return height
  3074. }
  3075. // Converts a {top, bottom, left, right} box from line-local
  3076. // coordinates into another coordinate system. Context may be one of
  3077. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  3078. // or "page".
  3079. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  3080. if (!includeWidgets) {
  3081. var height = widgetTopHeight(lineObj);
  3082. rect.top += height;
  3083. rect.bottom += height;
  3084. }
  3085. if (context == "line") {
  3086. return rect
  3087. }
  3088. if (!context) {
  3089. context = "local";
  3090. }
  3091. var yOff = heightAtLine(lineObj);
  3092. if (context == "local") {
  3093. yOff += paddingTop(cm.display);
  3094. } else {
  3095. yOff -= cm.display.viewOffset;
  3096. }
  3097. if (context == "page" || context == "window") {
  3098. var lOff = cm.display.lineSpace.getBoundingClientRect();
  3099. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  3100. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  3101. rect.left += xOff;
  3102. rect.right += xOff;
  3103. }
  3104. rect.top += yOff;
  3105. rect.bottom += yOff;
  3106. return rect
  3107. }
  3108. // Coverts a box from "div" coords to another coordinate system.
  3109. // Context may be "window", "page", "div", or "local"./null.
  3110. function fromCoordSystem(cm, coords, context) {
  3111. if (context == "div") {
  3112. return coords
  3113. }
  3114. var left = coords.left, top = coords.top;
  3115. // First move into "page" coordinate system
  3116. if (context == "page") {
  3117. left -= pageScrollX();
  3118. top -= pageScrollY();
  3119. } else if (context == "local" || !context) {
  3120. var localBox = cm.display.sizer.getBoundingClientRect();
  3121. left += localBox.left;
  3122. top += localBox.top;
  3123. }
  3124. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  3125. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  3126. }
  3127. function charCoords(cm, pos, context, lineObj, bias) {
  3128. if (!lineObj) {
  3129. lineObj = getLine(cm.doc, pos.line);
  3130. }
  3131. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  3132. }
  3133. // Returns a box for a given cursor position, which may have an
  3134. // 'other' property containing the position of the secondary cursor
  3135. // on a bidi boundary.
  3136. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  3137. // and after `char - 1` in writing order of `char - 1`
  3138. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  3139. // and before `char` in writing order of `char`
  3140. // Examples (upper-case letters are RTL, lower-case are LTR):
  3141. // Pos(0, 1, ...)
  3142. // before after
  3143. // ab a|b a|b
  3144. // aB a|B aB|
  3145. // Ab |Ab A|b
  3146. // AB B|A B|A
  3147. // Every position after the last character on a line is considered to stick
  3148. // to the last character on the line.
  3149. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  3150. lineObj = lineObj || getLine(cm.doc, pos.line);
  3151. if (!preparedMeasure) {
  3152. preparedMeasure = prepareMeasureForLine(cm, lineObj);
  3153. }
  3154. function get(ch, right) {
  3155. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  3156. if (right) {
  3157. m.left = m.right;
  3158. } else {
  3159. m.right = m.left;
  3160. }
  3161. return intoCoordSystem(cm, lineObj, m, context)
  3162. }
  3163. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  3164. if (ch >= lineObj.text.length) {
  3165. ch = lineObj.text.length;
  3166. sticky = "before";
  3167. } else if (ch <= 0) {
  3168. ch = 0;
  3169. sticky = "after";
  3170. }
  3171. if (!order) {
  3172. return get(sticky == "before" ? ch - 1 : ch, sticky == "before")
  3173. }
  3174. function getBidi(ch, partPos, invert) {
  3175. var part = order[partPos], right = part.level == 1;
  3176. return get(invert ? ch - 1 : ch, right != invert)
  3177. }
  3178. var partPos = getBidiPartAt(order, ch, sticky);
  3179. var other = bidiOther;
  3180. var val = getBidi(ch, partPos, sticky == "before");
  3181. if (other != null) {
  3182. val.other = getBidi(ch, other, sticky != "before");
  3183. }
  3184. return val
  3185. }
  3186. // Used to cheaply estimate the coordinates for a position. Used for
  3187. // intermediate scroll updates.
  3188. function estimateCoords(cm, pos) {
  3189. var left = 0;
  3190. pos = clipPos(cm.doc, pos);
  3191. if (!cm.options.lineWrapping) {
  3192. left = charWidth(cm.display) * pos.ch;
  3193. }
  3194. var lineObj = getLine(cm.doc, pos.line);
  3195. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  3196. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  3197. }
  3198. // Positions returned by coordsChar contain some extra information.
  3199. // xRel is the relative x position of the input coordinates compared
  3200. // to the found position (so xRel > 0 means the coordinates are to
  3201. // the right of the character position, for example). When outside
  3202. // is true, that means the coordinates lie outside the line's
  3203. // vertical range.
  3204. function PosWithInfo(line, ch, sticky, outside, xRel) {
  3205. var pos = Pos(line, ch, sticky);
  3206. pos.xRel = xRel;
  3207. if (outside) {
  3208. pos.outside = outside;
  3209. }
  3210. return pos
  3211. }
  3212. // Compute the character position closest to the given coordinates.
  3213. // Input must be lineSpace-local ("div" coordinate system).
  3214. function coordsChar(cm, x, y) {
  3215. var doc = cm.doc;
  3216. y += cm.display.viewOffset;
  3217. if (y < 0) {
  3218. return PosWithInfo(doc.first, 0, null, -1, -1)
  3219. }
  3220. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  3221. if (lineN > last) {
  3222. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1)
  3223. }
  3224. if (x < 0) {
  3225. x = 0;
  3226. }
  3227. var lineObj = getLine(doc, lineN);
  3228. for (; ;) {
  3229. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  3230. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  3231. if (!collapsed) {
  3232. return found
  3233. }
  3234. var rangeEnd = collapsed.find(1);
  3235. if (rangeEnd.line == lineN) {
  3236. return rangeEnd
  3237. }
  3238. lineObj = getLine(doc, lineN = rangeEnd.line);
  3239. }
  3240. }
  3241. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  3242. y -= widgetTopHeight(lineObj);
  3243. var end = lineObj.text.length;
  3244. var begin = findFirst(function (ch) {
  3245. return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y;
  3246. }, end, 0);
  3247. end = findFirst(function (ch) {
  3248. return measureCharPrepared(cm, preparedMeasure, ch).top > y;
  3249. }, begin, end);
  3250. return {begin: begin, end: end}
  3251. }
  3252. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  3253. if (!preparedMeasure) {
  3254. preparedMeasure = prepareMeasureForLine(cm, lineObj);
  3255. }
  3256. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  3257. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  3258. }
  3259. // Returns true if the given side of a box is after the given
  3260. // coordinates, in top-to-bottom, left-to-right order.
  3261. function boxIsAfter(box, x, y, left) {
  3262. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  3263. }
  3264. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  3265. // Move y into line-local coordinate space
  3266. y -= heightAtLine(lineObj);
  3267. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  3268. // When directly calling `measureCharPrepared`, we have to adjust
  3269. // for the widgets at this line.
  3270. var widgetHeight = widgetTopHeight(lineObj);
  3271. var begin = 0, end = lineObj.text.length, ltr = true;
  3272. var order = getOrder(lineObj, cm.doc.direction);
  3273. // If the line isn't plain left-to-right text, first figure out
  3274. // which bidi section the coordinates fall into.
  3275. if (order) {
  3276. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  3277. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  3278. ltr = part.level != 1;
  3279. // The awkward -1 offsets are needed because findFirst (called
  3280. // on these below) will treat its first bound as inclusive,
  3281. // second as exclusive, but we want to actually address the
  3282. // characters in the part's range
  3283. begin = ltr ? part.from : part.to - 1;
  3284. end = ltr ? part.to : part.from - 1;
  3285. }
  3286. // A binary search to find the first character whose bounding box
  3287. // starts after the coordinates. If we run across any whose box wrap
  3288. // the coordinates, store that.
  3289. var chAround = null, boxAround = null;
  3290. var ch = findFirst(function (ch) {
  3291. var box = measureCharPrepared(cm, preparedMeasure, ch);
  3292. box.top += widgetHeight;
  3293. box.bottom += widgetHeight;
  3294. if (!boxIsAfter(box, x, y, false)) {
  3295. return false
  3296. }
  3297. if (box.top <= y && box.left <= x) {
  3298. chAround = ch;
  3299. boxAround = box;
  3300. }
  3301. return true
  3302. }, begin, end);
  3303. var baseX, sticky, outside = false;
  3304. // If a box around the coordinates was found, use that
  3305. if (boxAround) {
  3306. // Distinguish coordinates nearer to the left or right side of the box
  3307. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  3308. ch = chAround + (atStart ? 0 : 1);
  3309. sticky = atStart ? "after" : "before";
  3310. baseX = atLeft ? boxAround.left : boxAround.right;
  3311. } else {
  3312. // (Adjust for extended bound, if necessary.)
  3313. if (!ltr && (ch == end || ch == begin)) {
  3314. ch++;
  3315. }
  3316. // To determine which side to associate with, get the box to the
  3317. // left of the character and compare it's vertical position to the
  3318. // coordinates
  3319. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  3320. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  3321. "after" : "before";
  3322. // Now get accurate coordinates for this place, in order to get a
  3323. // base X position
  3324. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  3325. baseX = coords.left;
  3326. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  3327. }
  3328. ch = skipExtendingChars(lineObj.text, ch, 1);
  3329. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  3330. }
  3331. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  3332. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  3333. // situation, we can take this ordering to correspond to the visual
  3334. // ordering. This finds the first part whose end is after the given
  3335. // coordinates.
  3336. var index = findFirst(function (i) {
  3337. var part = order[i], ltr = part.level != 1;
  3338. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  3339. "line", lineObj, preparedMeasure), x, y, true)
  3340. }, 0, order.length - 1);
  3341. var part = order[index];
  3342. // If this isn't the first part, the part's start is also after
  3343. // the coordinates, and the coordinates aren't on the same line as
  3344. // that start, move one part back.
  3345. if (index > 0) {
  3346. var ltr = part.level != 1;
  3347. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  3348. "line", lineObj, preparedMeasure);
  3349. if (boxIsAfter(start, x, y, true) && start.top > y) {
  3350. part = order[index - 1];
  3351. }
  3352. }
  3353. return part
  3354. }
  3355. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  3356. // In a wrapped line, rtl text on wrapping boundaries can do things
  3357. // that don't correspond to the ordering in our `order` array at
  3358. // all, so a binary search doesn't work, and we want to return a
  3359. // part that only spans one line so that the binary search in
  3360. // coordsCharInner is safe. As such, we first find the extent of the
  3361. // wrapped line, and then do a flat search in which we discard any
  3362. // spans that aren't on the line.
  3363. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  3364. var begin = ref.begin;
  3365. var end = ref.end;
  3366. if (/\s/.test(lineObj.text.charAt(end - 1))) {
  3367. end--;
  3368. }
  3369. var part = null, closestDist = null;
  3370. for (var i = 0; i < order.length; i++) {
  3371. var p = order[i];
  3372. if (p.from >= end || p.to <= begin) {
  3373. continue
  3374. }
  3375. var ltr = p.level != 1;
  3376. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  3377. // Weigh against spans ending before this, so that they are only
  3378. // picked if nothing ends after
  3379. var dist = endX < x ? x - endX + 1e9 : endX - x;
  3380. if (!part || closestDist > dist) {
  3381. part = p;
  3382. closestDist = dist;
  3383. }
  3384. }
  3385. if (!part) {
  3386. part = order[order.length - 1];
  3387. }
  3388. // Clip the part to the wrapped line.
  3389. if (part.from < begin) {
  3390. part = {from: begin, to: part.to, level: part.level};
  3391. }
  3392. if (part.to > end) {
  3393. part = {from: part.from, to: end, level: part.level};
  3394. }
  3395. return part
  3396. }
  3397. var measureText;
  3398. // Compute the default text height.
  3399. function textHeight(display) {
  3400. if (display.cachedTextHeight != null) {
  3401. return display.cachedTextHeight
  3402. }
  3403. if (measureText == null) {
  3404. measureText = elt("pre", null, "CodeMirror-line-like");
  3405. // Measure a bunch of lines, for browsers that compute
  3406. // fractional heights.
  3407. for (var i = 0; i < 49; ++i) {
  3408. measureText.appendChild(document.createTextNode("x"));
  3409. measureText.appendChild(elt("br"));
  3410. }
  3411. measureText.appendChild(document.createTextNode("x"));
  3412. }
  3413. removeChildrenAndAdd(display.measure, measureText);
  3414. var height = measureText.offsetHeight / 50;
  3415. if (height > 3) {
  3416. display.cachedTextHeight = height;
  3417. }
  3418. removeChildren(display.measure);
  3419. return height || 1
  3420. }
  3421. // Compute the default character width.
  3422. function charWidth(display) {
  3423. if (display.cachedCharWidth != null) {
  3424. return display.cachedCharWidth
  3425. }
  3426. var anchor = elt("span", "xxxxxxxxxx");
  3427. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  3428. removeChildrenAndAdd(display.measure, pre);
  3429. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  3430. if (width > 2) {
  3431. display.cachedCharWidth = width;
  3432. }
  3433. return width || 10
  3434. }
  3435. // Do a bulk-read of the DOM positions and sizes needed to draw the
  3436. // view, so that we don't interleave reading and writing to the DOM.
  3437. function getDimensions(cm) {
  3438. var d = cm.display, left = {}, width = {};
  3439. var gutterLeft = d.gutters.clientLeft;
  3440. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  3441. var id = cm.display.gutterSpecs[i].className;
  3442. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  3443. width[id] = n.clientWidth;
  3444. }
  3445. return {
  3446. fixedPos: compensateForHScroll(d),
  3447. gutterTotalWidth: d.gutters.offsetWidth,
  3448. gutterLeft: left,
  3449. gutterWidth: width,
  3450. wrapperWidth: d.wrapper.clientWidth
  3451. }
  3452. }
  3453. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  3454. // but using getBoundingClientRect to get a sub-pixel-accurate
  3455. // result.
  3456. function compensateForHScroll(display) {
  3457. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  3458. }
  3459. // Returns a function that estimates the height of a line, to use as
  3460. // first approximation until the line becomes visible (and is thus
  3461. // properly measurable).
  3462. function estimateHeight(cm) {
  3463. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  3464. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  3465. return function (line) {
  3466. if (lineIsHidden(cm.doc, line)) {
  3467. return 0
  3468. }
  3469. var widgetsHeight = 0;
  3470. if (line.widgets) {
  3471. for (var i = 0; i < line.widgets.length; i++) {
  3472. if (line.widgets[i].height) {
  3473. widgetsHeight += line.widgets[i].height;
  3474. }
  3475. }
  3476. }
  3477. if (wrapping) {
  3478. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th
  3479. } else {
  3480. return widgetsHeight + th
  3481. }
  3482. }
  3483. }
  3484. function estimateLineHeights(cm) {
  3485. var doc = cm.doc, est = estimateHeight(cm);
  3486. doc.iter(function (line) {
  3487. var estHeight = est(line);
  3488. if (estHeight != line.height) {
  3489. updateLineHeight(line, estHeight);
  3490. }
  3491. });
  3492. }
  3493. // Given a mouse event, find the corresponding position. If liberal
  3494. // is false, it checks whether a gutter or scrollbar was clicked,
  3495. // and returns null if it was. forRect is used by rectangular
  3496. // selections, and tries to estimate a character position even for
  3497. // coordinates beyond the right of the text.
  3498. function posFromMouse(cm, e, liberal, forRect) {
  3499. var display = cm.display;
  3500. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") {
  3501. return null
  3502. }
  3503. var x, y, space = display.lineSpace.getBoundingClientRect();
  3504. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3505. try {
  3506. x = e.clientX - space.left;
  3507. y = e.clientY - space.top;
  3508. } catch (e$1) {
  3509. return null
  3510. }
  3511. var coords = coordsChar(cm, x, y), line;
  3512. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3513. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3514. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3515. }
  3516. return coords
  3517. }
  3518. // Find the view element corresponding to a given line. Return null
  3519. // when the line isn't visible.
  3520. function findViewIndex(cm, n) {
  3521. if (n >= cm.display.viewTo) {
  3522. return null
  3523. }
  3524. n -= cm.display.viewFrom;
  3525. if (n < 0) {
  3526. return null
  3527. }
  3528. var view = cm.display.view;
  3529. for (var i = 0; i < view.length; i++) {
  3530. n -= view[i].size;
  3531. if (n < 0) {
  3532. return i
  3533. }
  3534. }
  3535. }
  3536. // Updates the display.view data structure for a given change to the
  3537. // document. From and to are in pre-change coordinates. Lendiff is
  3538. // the amount of lines added or subtracted by the change. This is
  3539. // used for changes that span multiple lines, or change the way
  3540. // lines are divided into visual lines. regLineChange (below)
  3541. // registers single-line changes.
  3542. function regChange(cm, from, to, lendiff) {
  3543. if (from == null) {
  3544. from = cm.doc.first;
  3545. }
  3546. if (to == null) {
  3547. to = cm.doc.first + cm.doc.size;
  3548. }
  3549. if (!lendiff) {
  3550. lendiff = 0;
  3551. }
  3552. var display = cm.display;
  3553. if (lendiff && to < display.viewTo &&
  3554. (display.updateLineNumbers == null || display.updateLineNumbers > from)) {
  3555. display.updateLineNumbers = from;
  3556. }
  3557. cm.curOp.viewChanged = true;
  3558. if (from >= display.viewTo) { // Change after
  3559. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {
  3560. resetView(cm);
  3561. }
  3562. } else if (to <= display.viewFrom) { // Change before
  3563. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3564. resetView(cm);
  3565. } else {
  3566. display.viewFrom += lendiff;
  3567. display.viewTo += lendiff;
  3568. }
  3569. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3570. resetView(cm);
  3571. } else if (from <= display.viewFrom) { // Top overlap
  3572. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  3573. if (cut) {
  3574. display.view = display.view.slice(cut.index);
  3575. display.viewFrom = cut.lineN;
  3576. display.viewTo += lendiff;
  3577. } else {
  3578. resetView(cm);
  3579. }
  3580. } else if (to >= display.viewTo) { // Bottom overlap
  3581. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  3582. if (cut$1) {
  3583. display.view = display.view.slice(0, cut$1.index);
  3584. display.viewTo = cut$1.lineN;
  3585. } else {
  3586. resetView(cm);
  3587. }
  3588. } else { // Gap in the middle
  3589. var cutTop = viewCuttingPoint(cm, from, from, -1);
  3590. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  3591. if (cutTop && cutBot) {
  3592. display.view = display.view.slice(0, cutTop.index)
  3593. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3594. .concat(display.view.slice(cutBot.index));
  3595. display.viewTo += lendiff;
  3596. } else {
  3597. resetView(cm);
  3598. }
  3599. }
  3600. var ext = display.externalMeasured;
  3601. if (ext) {
  3602. if (to < ext.lineN) {
  3603. ext.lineN += lendiff;
  3604. } else if (from < ext.lineN + ext.size) {
  3605. display.externalMeasured = null;
  3606. }
  3607. }
  3608. }
  3609. // Register a change to a single line. Type must be one of "text",
  3610. // "gutter", "class", "widget"
  3611. function regLineChange(cm, line, type) {
  3612. cm.curOp.viewChanged = true;
  3613. var display = cm.display, ext = cm.display.externalMeasured;
  3614. if (ext && line >= ext.lineN && line < ext.lineN + ext.size) {
  3615. display.externalMeasured = null;
  3616. }
  3617. if (line < display.viewFrom || line >= display.viewTo) {
  3618. return
  3619. }
  3620. var lineView = display.view[findViewIndex(cm, line)];
  3621. if (lineView.node == null) {
  3622. return
  3623. }
  3624. var arr = lineView.changes || (lineView.changes = []);
  3625. if (indexOf(arr, type) == -1) {
  3626. arr.push(type);
  3627. }
  3628. }
  3629. // Clear the view.
  3630. function resetView(cm) {
  3631. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  3632. cm.display.view = [];
  3633. cm.display.viewOffset = 0;
  3634. }
  3635. function viewCuttingPoint(cm, oldN, newN, dir) {
  3636. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  3637. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {
  3638. return {index: index, lineN: newN}
  3639. }
  3640. var n = cm.display.viewFrom;
  3641. for (var i = 0; i < index; i++) {
  3642. n += view[i].size;
  3643. }
  3644. if (n != oldN) {
  3645. if (dir > 0) {
  3646. if (index == view.length - 1) {
  3647. return null
  3648. }
  3649. diff = (n + view[index].size) - oldN;
  3650. index++;
  3651. } else {
  3652. diff = n - oldN;
  3653. }
  3654. oldN += diff;
  3655. newN += diff;
  3656. }
  3657. while (visualLineNo(cm.doc, newN) != newN) {
  3658. if (index == (dir < 0 ? 0 : view.length - 1)) {
  3659. return null
  3660. }
  3661. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3662. index += dir;
  3663. }
  3664. return {index: index, lineN: newN}
  3665. }
  3666. // Force the view to cover a given range, adding empty view element
  3667. // or clipping off existing ones as needed.
  3668. function adjustView(cm, from, to) {
  3669. var display = cm.display, view = display.view;
  3670. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3671. display.view = buildViewArray(cm, from, to);
  3672. display.viewFrom = from;
  3673. } else {
  3674. if (display.viewFrom > from) {
  3675. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  3676. } else if (display.viewFrom < from) {
  3677. display.view = display.view.slice(findViewIndex(cm, from));
  3678. }
  3679. display.viewFrom = from;
  3680. if (display.viewTo < to) {
  3681. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  3682. } else if (display.viewTo > to) {
  3683. display.view = display.view.slice(0, findViewIndex(cm, to));
  3684. }
  3685. }
  3686. display.viewTo = to;
  3687. }
  3688. // Count the number of lines in the view whose DOM representation is
  3689. // out of date (or nonexistent).
  3690. function countDirtyView(cm) {
  3691. var view = cm.display.view, dirty = 0;
  3692. for (var i = 0; i < view.length; i++) {
  3693. var lineView = view[i];
  3694. if (!lineView.hidden && (!lineView.node || lineView.changes)) {
  3695. ++dirty;
  3696. }
  3697. }
  3698. return dirty
  3699. }
  3700. function updateSelection(cm) {
  3701. cm.display.input.showSelection(cm.display.input.prepareSelection());
  3702. }
  3703. function prepareSelection(cm, primary) {
  3704. if (primary === void 0) primary = true;
  3705. var doc = cm.doc, result = {};
  3706. var curFragment = result.cursors = document.createDocumentFragment();
  3707. var selFragment = result.selection = document.createDocumentFragment();
  3708. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3709. if (!primary && i == doc.sel.primIndex) {
  3710. continue
  3711. }
  3712. var range = doc.sel.ranges[i];
  3713. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) {
  3714. continue
  3715. }
  3716. var collapsed = range.empty();
  3717. if (collapsed || cm.options.showCursorWhenSelecting) {
  3718. drawSelectionCursor(cm, range.head, curFragment);
  3719. }
  3720. if (!collapsed) {
  3721. drawSelectionRange(cm, range, selFragment);
  3722. }
  3723. }
  3724. return result
  3725. }
  3726. // Draws a cursor for the given range
  3727. function drawSelectionCursor(cm, head, output) {
  3728. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  3729. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  3730. cursor.style.left = pos.left + "px";
  3731. cursor.style.top = pos.top + "px";
  3732. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  3733. if (pos.other) {
  3734. // Secondary cursor, shown when on a 'jump' in bi-directional text
  3735. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  3736. otherCursor.style.display = "";
  3737. otherCursor.style.left = pos.other.left + "px";
  3738. otherCursor.style.top = pos.other.top + "px";
  3739. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  3740. }
  3741. }
  3742. function cmpCoords(a, b) {
  3743. return a.top - b.top || a.left - b.left
  3744. }
  3745. // Draws the given range as a highlighted selection
  3746. function drawSelectionRange(cm, range, output) {
  3747. var display = cm.display, doc = cm.doc;
  3748. var fragment = document.createDocumentFragment();
  3749. var padding = paddingH(cm.display), leftSide = padding.left;
  3750. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  3751. var docLTR = doc.direction == "ltr";
  3752. function add(left, top, width, bottom) {
  3753. if (top < 0) {
  3754. top = 0;
  3755. }
  3756. top = Math.round(top);
  3757. bottom = Math.round(bottom);
  3758. fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
  3759. }
  3760. function drawForLine(line, fromArg, toArg) {
  3761. var lineObj = getLine(doc, line);
  3762. var lineLen = lineObj.text.length;
  3763. var start, end;
  3764. function coords(ch, bias) {
  3765. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  3766. }
  3767. function wrapX(pos, dir, side) {
  3768. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  3769. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  3770. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  3771. return coords(ch, prop)[prop]
  3772. }
  3773. var order = getOrder(lineObj, doc.direction);
  3774. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  3775. var ltr = dir == "ltr";
  3776. var fromPos = coords(from, ltr ? "left" : "right");
  3777. var toPos = coords(to - 1, ltr ? "right" : "left");
  3778. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  3779. var first = i == 0, last = !order || i == order.length - 1;
  3780. if (toPos.top - fromPos.top <= 3) { // Single line
  3781. var openLeft = (docLTR ? openStart : openEnd) && first;
  3782. var openRight = (docLTR ? openEnd : openStart) && last;
  3783. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  3784. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  3785. add(left, fromPos.top, right - left, fromPos.bottom);
  3786. } else { // Multiple lines
  3787. var topLeft, topRight, botLeft, botRight;
  3788. if (ltr) {
  3789. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  3790. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  3791. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  3792. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  3793. } else {
  3794. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  3795. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  3796. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  3797. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  3798. }
  3799. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  3800. if (fromPos.bottom < toPos.top) {
  3801. add(leftSide, fromPos.bottom, null, toPos.top);
  3802. }
  3803. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  3804. }
  3805. if (!start || cmpCoords(fromPos, start) < 0) {
  3806. start = fromPos;
  3807. }
  3808. if (cmpCoords(toPos, start) < 0) {
  3809. start = toPos;
  3810. }
  3811. if (!end || cmpCoords(fromPos, end) < 0) {
  3812. end = fromPos;
  3813. }
  3814. if (cmpCoords(toPos, end) < 0) {
  3815. end = toPos;
  3816. }
  3817. });
  3818. return {start: start, end: end}
  3819. }
  3820. var sFrom = range.from(), sTo = range.to();
  3821. if (sFrom.line == sTo.line) {
  3822. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  3823. } else {
  3824. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  3825. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  3826. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  3827. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  3828. if (singleVLine) {
  3829. if (leftEnd.top < rightStart.top - 2) {
  3830. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  3831. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  3832. } else {
  3833. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  3834. }
  3835. }
  3836. if (leftEnd.bottom < rightStart.top) {
  3837. add(leftSide, leftEnd.bottom, null, rightStart.top);
  3838. }
  3839. }
  3840. output.appendChild(fragment);
  3841. }
  3842. // Cursor-blinking
  3843. function restartBlink(cm) {
  3844. if (!cm.state.focused) {
  3845. return
  3846. }
  3847. var display = cm.display;
  3848. clearInterval(display.blinker);
  3849. var on = true;
  3850. display.cursorDiv.style.visibility = "";
  3851. if (cm.options.cursorBlinkRate > 0) {
  3852. display.blinker = setInterval(function () {
  3853. if (!cm.hasFocus()) {
  3854. onBlur(cm);
  3855. }
  3856. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  3857. }, cm.options.cursorBlinkRate);
  3858. } else if (cm.options.cursorBlinkRate < 0) {
  3859. display.cursorDiv.style.visibility = "hidden";
  3860. }
  3861. }
  3862. function ensureFocus(cm) {
  3863. if (!cm.hasFocus()) {
  3864. cm.display.input.focus();
  3865. if (!cm.state.focused) {
  3866. onFocus(cm);
  3867. }
  3868. }
  3869. }
  3870. function delayBlurEvent(cm) {
  3871. cm.state.delayingBlurEvent = true;
  3872. setTimeout(function () {
  3873. if (cm.state.delayingBlurEvent) {
  3874. cm.state.delayingBlurEvent = false;
  3875. if (cm.state.focused) {
  3876. onBlur(cm);
  3877. }
  3878. }
  3879. }, 100);
  3880. }
  3881. function onFocus(cm, e) {
  3882. if (cm.state.delayingBlurEvent && !cm.state.draggingText) {
  3883. cm.state.delayingBlurEvent = false;
  3884. }
  3885. if (cm.options.readOnly == "nocursor") {
  3886. return
  3887. }
  3888. if (!cm.state.focused) {
  3889. signal(cm, "focus", cm, e);
  3890. cm.state.focused = true;
  3891. addClass(cm.display.wrapper, "CodeMirror-focused");
  3892. // This test prevents this from firing when a context
  3893. // menu is closed (since the input reset would kill the
  3894. // select-all detection hack)
  3895. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3896. cm.display.input.reset();
  3897. if (webkit) {
  3898. setTimeout(function () {
  3899. return cm.display.input.reset(true);
  3900. }, 20);
  3901. } // Issue #1730
  3902. }
  3903. cm.display.input.receivedFocus();
  3904. }
  3905. restartBlink(cm);
  3906. }
  3907. function onBlur(cm, e) {
  3908. if (cm.state.delayingBlurEvent) {
  3909. return
  3910. }
  3911. if (cm.state.focused) {
  3912. signal(cm, "blur", cm, e);
  3913. cm.state.focused = false;
  3914. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3915. }
  3916. clearInterval(cm.display.blinker);
  3917. setTimeout(function () {
  3918. if (!cm.state.focused) {
  3919. cm.display.shift = false;
  3920. }
  3921. }, 150);
  3922. }
  3923. // Read the actual heights of the rendered lines, and update their
  3924. // stored heights to match.
  3925. function updateHeightsInViewport(cm) {
  3926. var display = cm.display;
  3927. var prevBottom = display.lineDiv.offsetTop;
  3928. for (var i = 0; i < display.view.length; i++) {
  3929. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3930. var height = (void 0), width = 0;
  3931. if (cur.hidden) {
  3932. continue
  3933. }
  3934. if (ie && ie_version < 8) {
  3935. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3936. height = bot - prevBottom;
  3937. prevBottom = bot;
  3938. } else {
  3939. var box = cur.node.getBoundingClientRect();
  3940. height = box.bottom - box.top;
  3941. // Check that lines don't extend past the right of the current
  3942. // editor width
  3943. if (!wrapping && cur.text.firstChild) {
  3944. width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1;
  3945. }
  3946. }
  3947. var diff = cur.line.height - height;
  3948. if (diff > .005 || diff < -.005) {
  3949. updateLineHeight(cur.line, height);
  3950. updateWidgetHeight(cur.line);
  3951. if (cur.rest) {
  3952. for (var j = 0; j < cur.rest.length; j++) {
  3953. updateWidgetHeight(cur.rest[j]);
  3954. }
  3955. }
  3956. }
  3957. if (width > cm.display.sizerWidth) {
  3958. var chWidth = Math.ceil(width / charWidth(cm.display));
  3959. if (chWidth > cm.display.maxLineLength) {
  3960. cm.display.maxLineLength = chWidth;
  3961. cm.display.maxLine = cur.line;
  3962. cm.display.maxLineChanged = true;
  3963. }
  3964. }
  3965. }
  3966. }
  3967. // Read and store the height of line widgets associated with the
  3968. // given line.
  3969. function updateWidgetHeight(line) {
  3970. if (line.widgets) {
  3971. for (var i = 0; i < line.widgets.length; ++i) {
  3972. var w = line.widgets[i], parent = w.node.parentNode;
  3973. if (parent) {
  3974. w.height = parent.offsetHeight;
  3975. }
  3976. }
  3977. }
  3978. }
  3979. // Compute the lines that are visible in a given viewport (defaults
  3980. // the the current scroll position). viewport may contain top,
  3981. // height, and ensure (see op.scrollToPos) properties.
  3982. function visibleLines(display, doc, viewport) {
  3983. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3984. top = Math.floor(top - paddingTop(display));
  3985. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3986. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3987. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3988. // forces those lines into the viewport (if possible).
  3989. if (viewport && viewport.ensure) {
  3990. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3991. if (ensureFrom < from) {
  3992. from = ensureFrom;
  3993. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3994. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3995. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3996. to = ensureTo;
  3997. }
  3998. }
  3999. return {from: from, to: Math.max(to, from + 1)}
  4000. }
  4001. // SCROLLING THINGS INTO VIEW
  4002. // If an editor sits on the top or bottom of the window, partially
  4003. // scrolled out of view, this ensures that the cursor is visible.
  4004. function maybeScrollWindow(cm, rect) {
  4005. if (signalDOMEvent(cm, "scrollCursorIntoView")) {
  4006. return
  4007. }
  4008. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4009. if (rect.top + box.top < 0) {
  4010. doScroll = true;
  4011. } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) {
  4012. doScroll = false;
  4013. }
  4014. if (doScroll != null && !phantom) {
  4015. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
  4016. cm.display.lineSpace.appendChild(scrollNode);
  4017. scrollNode.scrollIntoView(doScroll);
  4018. cm.display.lineSpace.removeChild(scrollNode);
  4019. }
  4020. }
  4021. // Scroll a given position into view (immediately), verifying that
  4022. // it actually became visible (as line heights are accurately
  4023. // measured, the position of something may 'drift' during drawing).
  4024. function scrollPosIntoView(cm, pos, end, margin) {
  4025. if (margin == null) {
  4026. margin = 0;
  4027. }
  4028. var rect;
  4029. if (!cm.options.lineWrapping && pos == end) {
  4030. // Set pos and end to the cursor positions around the character pos sticks to
  4031. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  4032. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  4033. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  4034. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  4035. }
  4036. for (var limit = 0; limit < 5; limit++) {
  4037. var changed = false;
  4038. var coords = cursorCoords(cm, pos);
  4039. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4040. rect = {
  4041. left: Math.min(coords.left, endCoords.left),
  4042. top: Math.min(coords.top, endCoords.top) - margin,
  4043. right: Math.max(coords.left, endCoords.left),
  4044. bottom: Math.max(coords.bottom, endCoords.bottom) + margin
  4045. };
  4046. var scrollPos = calculateScrollPos(cm, rect);
  4047. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4048. if (scrollPos.scrollTop != null) {
  4049. updateScrollTop(cm, scrollPos.scrollTop);
  4050. if (Math.abs(cm.doc.scrollTop - startTop) > 1) {
  4051. changed = true;
  4052. }
  4053. }
  4054. if (scrollPos.scrollLeft != null) {
  4055. setScrollLeft(cm, scrollPos.scrollLeft);
  4056. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) {
  4057. changed = true;
  4058. }
  4059. }
  4060. if (!changed) {
  4061. break
  4062. }
  4063. }
  4064. return rect
  4065. }
  4066. // Scroll a given set of coordinates into view (immediately).
  4067. function scrollIntoView(cm, rect) {
  4068. var scrollPos = calculateScrollPos(cm, rect);
  4069. if (scrollPos.scrollTop != null) {
  4070. updateScrollTop(cm, scrollPos.scrollTop);
  4071. }
  4072. if (scrollPos.scrollLeft != null) {
  4073. setScrollLeft(cm, scrollPos.scrollLeft);
  4074. }
  4075. }
  4076. // Calculate a new scroll position needed to scroll the given
  4077. // rectangle into view. Returns an object with scrollTop and
  4078. // scrollLeft properties. When these are undefined, the
  4079. // vertical/horizontal position does not need to be adjusted.
  4080. function calculateScrollPos(cm, rect) {
  4081. var display = cm.display, snapMargin = textHeight(cm.display);
  4082. if (rect.top < 0) {
  4083. rect.top = 0;
  4084. }
  4085. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4086. var screen = displayHeight(cm), result = {};
  4087. if (rect.bottom - rect.top > screen) {
  4088. rect.bottom = rect.top + screen;
  4089. }
  4090. var docBottom = cm.doc.height + paddingVert(display);
  4091. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  4092. if (rect.top < screentop) {
  4093. result.scrollTop = atTop ? 0 : rect.top;
  4094. } else if (rect.bottom > screentop + screen) {
  4095. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  4096. if (newTop != screentop) {
  4097. result.scrollTop = newTop;
  4098. }
  4099. }
  4100. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  4101. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  4102. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  4103. var tooWide = rect.right - rect.left > screenw;
  4104. if (tooWide) {
  4105. rect.right = rect.left + screenw;
  4106. }
  4107. if (rect.left < 10) {
  4108. result.scrollLeft = 0;
  4109. } else if (rect.left < screenleft) {
  4110. result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10));
  4111. } else if (rect.right > screenw + screenleft - 3) {
  4112. result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw;
  4113. }
  4114. return result
  4115. }
  4116. // Store a relative adjustment to the scroll position in the current
  4117. // operation (to be applied when the operation finishes).
  4118. function addToScrollTop(cm, top) {
  4119. if (top == null) {
  4120. return
  4121. }
  4122. resolveScrollToPos(cm);
  4123. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4124. }
  4125. // Make sure that at the end of the operation the current cursor is
  4126. // shown.
  4127. function ensureCursorVisible(cm) {
  4128. resolveScrollToPos(cm);
  4129. var cur = cm.getCursor();
  4130. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  4131. }
  4132. function scrollToCoords(cm, x, y) {
  4133. if (x != null || y != null) {
  4134. resolveScrollToPos(cm);
  4135. }
  4136. if (x != null) {
  4137. cm.curOp.scrollLeft = x;
  4138. }
  4139. if (y != null) {
  4140. cm.curOp.scrollTop = y;
  4141. }
  4142. }
  4143. function scrollToRange(cm, range) {
  4144. resolveScrollToPos(cm);
  4145. cm.curOp.scrollToPos = range;
  4146. }
  4147. // When an operation has its scrollToPos property set, and another
  4148. // scroll action is applied before the end of the operation, this
  4149. // 'simulates' scrolling that position into view in a cheap way, so
  4150. // that the effect of intermediate scroll commands is not ignored.
  4151. function resolveScrollToPos(cm) {
  4152. var range = cm.curOp.scrollToPos;
  4153. if (range) {
  4154. cm.curOp.scrollToPos = null;
  4155. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4156. scrollToCoordsRange(cm, from, to, range.margin);
  4157. }
  4158. }
  4159. function scrollToCoordsRange(cm, from, to, margin) {
  4160. var sPos = calculateScrollPos(cm, {
  4161. left: Math.min(from.left, to.left),
  4162. top: Math.min(from.top, to.top) - margin,
  4163. right: Math.max(from.right, to.right),
  4164. bottom: Math.max(from.bottom, to.bottom) + margin
  4165. });
  4166. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  4167. }
  4168. // Sync the scrollable area and scrollbars, ensure the viewport
  4169. // covers the visible area.
  4170. function updateScrollTop(cm, val) {
  4171. if (Math.abs(cm.doc.scrollTop - val) < 2) {
  4172. return
  4173. }
  4174. if (!gecko) {
  4175. updateDisplaySimple(cm, {top: val});
  4176. }
  4177. setScrollTop(cm, val, true);
  4178. if (gecko) {
  4179. updateDisplaySimple(cm);
  4180. }
  4181. startWorker(cm, 100);
  4182. }
  4183. function setScrollTop(cm, val, forceScroll) {
  4184. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  4185. if (cm.display.scroller.scrollTop == val && !forceScroll) {
  4186. return
  4187. }
  4188. cm.doc.scrollTop = val;
  4189. cm.display.scrollbars.setScrollTop(val);
  4190. if (cm.display.scroller.scrollTop != val) {
  4191. cm.display.scroller.scrollTop = val;
  4192. }
  4193. }
  4194. // Sync scroller and scrollbar, ensure the gutter elements are
  4195. // aligned.
  4196. function setScrollLeft(cm, val, isScroller, forceScroll) {
  4197. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  4198. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) {
  4199. return
  4200. }
  4201. cm.doc.scrollLeft = val;
  4202. alignHorizontally(cm);
  4203. if (cm.display.scroller.scrollLeft != val) {
  4204. cm.display.scroller.scrollLeft = val;
  4205. }
  4206. cm.display.scrollbars.setScrollLeft(val);
  4207. }
  4208. // SCROLLBARS
  4209. // Prepare DOM reads needed to update the scrollbars. Done in one
  4210. // shot to minimize update/measure roundtrips.
  4211. function measureForScrollbars(cm) {
  4212. var d = cm.display, gutterW = d.gutters.offsetWidth;
  4213. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  4214. return {
  4215. clientHeight: d.scroller.clientHeight,
  4216. viewHeight: d.wrapper.clientHeight,
  4217. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  4218. viewWidth: d.wrapper.clientWidth,
  4219. barLeft: cm.options.fixedGutter ? gutterW : 0,
  4220. docHeight: docH,
  4221. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  4222. nativeBarWidth: d.nativeBarWidth,
  4223. gutterWidth: gutterW
  4224. }
  4225. }
  4226. var NativeScrollbars = function (place, scroll, cm) {
  4227. this.cm = cm;
  4228. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  4229. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  4230. vert.tabIndex = horiz.tabIndex = -1;
  4231. place(vert);
  4232. place(horiz);
  4233. on(vert, "scroll", function () {
  4234. if (vert.clientHeight) {
  4235. scroll(vert.scrollTop, "vertical");
  4236. }
  4237. });
  4238. on(horiz, "scroll", function () {
  4239. if (horiz.clientWidth) {
  4240. scroll(horiz.scrollLeft, "horizontal");
  4241. }
  4242. });
  4243. this.checkedZeroWidth = false;
  4244. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  4245. if (ie && ie_version < 8) {
  4246. this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  4247. }
  4248. };
  4249. NativeScrollbars.prototype.update = function (measure) {
  4250. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  4251. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  4252. var sWidth = measure.nativeBarWidth;
  4253. if (needsV) {
  4254. this.vert.style.display = "block";
  4255. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  4256. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  4257. // A bug in IE8 can cause this value to be negative, so guard it.
  4258. this.vert.firstChild.style.height =
  4259. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  4260. } else {
  4261. this.vert.style.display = "";
  4262. this.vert.firstChild.style.height = "0";
  4263. }
  4264. if (needsH) {
  4265. this.horiz.style.display = "block";
  4266. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  4267. this.horiz.style.left = measure.barLeft + "px";
  4268. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  4269. this.horiz.firstChild.style.width =
  4270. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  4271. } else {
  4272. this.horiz.style.display = "";
  4273. this.horiz.firstChild.style.width = "0";
  4274. }
  4275. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  4276. if (sWidth == 0) {
  4277. this.zeroWidthHack();
  4278. }
  4279. this.checkedZeroWidth = true;
  4280. }
  4281. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  4282. };
  4283. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  4284. if (this.horiz.scrollLeft != pos) {
  4285. this.horiz.scrollLeft = pos;
  4286. }
  4287. if (this.disableHoriz) {
  4288. this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz");
  4289. }
  4290. };
  4291. NativeScrollbars.prototype.setScrollTop = function (pos) {
  4292. if (this.vert.scrollTop != pos) {
  4293. this.vert.scrollTop = pos;
  4294. }
  4295. if (this.disableVert) {
  4296. this.enableZeroWidthBar(this.vert, this.disableVert, "vert");
  4297. }
  4298. };
  4299. NativeScrollbars.prototype.zeroWidthHack = function () {
  4300. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  4301. this.horiz.style.height = this.vert.style.width = w;
  4302. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  4303. this.disableHoriz = new Delayed;
  4304. this.disableVert = new Delayed;
  4305. };
  4306. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  4307. bar.style.pointerEvents = "auto";
  4308. function maybeDisable() {
  4309. // To find out whether the scrollbar is still visible, we
  4310. // check whether the element under the pixel in the bottom
  4311. // right corner of the scrollbar box is the scrollbar box
  4312. // itself (when the bar is still visible) or its filler child
  4313. // (when the bar is hidden). If it is still visible, we keep
  4314. // it enabled, if it's hidden, we disable pointer events.
  4315. var box = bar.getBoundingClientRect();
  4316. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  4317. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  4318. if (elt != bar) {
  4319. bar.style.pointerEvents = "none";
  4320. } else {
  4321. delay.set(1000, maybeDisable);
  4322. }
  4323. }
  4324. delay.set(1000, maybeDisable);
  4325. };
  4326. NativeScrollbars.prototype.clear = function () {
  4327. var parent = this.horiz.parentNode;
  4328. parent.removeChild(this.horiz);
  4329. parent.removeChild(this.vert);
  4330. };
  4331. var NullScrollbars = function () {
  4332. };
  4333. NullScrollbars.prototype.update = function () {
  4334. return {bottom: 0, right: 0}
  4335. };
  4336. NullScrollbars.prototype.setScrollLeft = function () {
  4337. };
  4338. NullScrollbars.prototype.setScrollTop = function () {
  4339. };
  4340. NullScrollbars.prototype.clear = function () {
  4341. };
  4342. function updateScrollbars(cm, measure) {
  4343. if (!measure) {
  4344. measure = measureForScrollbars(cm);
  4345. }
  4346. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  4347. updateScrollbarsInner(cm, measure);
  4348. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  4349. if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {
  4350. updateHeightsInViewport(cm);
  4351. }
  4352. updateScrollbarsInner(cm, measureForScrollbars(cm));
  4353. startWidth = cm.display.barWidth;
  4354. startHeight = cm.display.barHeight;
  4355. }
  4356. }
  4357. // Re-synchronize the fake scrollbars with the actual size of the
  4358. // content.
  4359. function updateScrollbarsInner(cm, measure) {
  4360. var d = cm.display;
  4361. var sizes = d.scrollbars.update(measure);
  4362. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  4363. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  4364. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  4365. if (sizes.right && sizes.bottom) {
  4366. d.scrollbarFiller.style.display = "block";
  4367. d.scrollbarFiller.style.height = sizes.bottom + "px";
  4368. d.scrollbarFiller.style.width = sizes.right + "px";
  4369. } else {
  4370. d.scrollbarFiller.style.display = "";
  4371. }
  4372. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  4373. d.gutterFiller.style.display = "block";
  4374. d.gutterFiller.style.height = sizes.bottom + "px";
  4375. d.gutterFiller.style.width = measure.gutterWidth + "px";
  4376. } else {
  4377. d.gutterFiller.style.display = "";
  4378. }
  4379. }
  4380. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  4381. function initScrollbars(cm) {
  4382. if (cm.display.scrollbars) {
  4383. cm.display.scrollbars.clear();
  4384. if (cm.display.scrollbars.addClass) {
  4385. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  4386. }
  4387. }
  4388. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  4389. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  4390. // Prevent clicks in the scrollbars from killing focus
  4391. on(node, "mousedown", function () {
  4392. if (cm.state.focused) {
  4393. setTimeout(function () {
  4394. return cm.display.input.focus();
  4395. }, 0);
  4396. }
  4397. });
  4398. node.setAttribute("cm-not-content", "true");
  4399. }, function (pos, axis) {
  4400. if (axis == "horizontal") {
  4401. setScrollLeft(cm, pos);
  4402. } else {
  4403. updateScrollTop(cm, pos);
  4404. }
  4405. }, cm);
  4406. if (cm.display.scrollbars.addClass) {
  4407. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  4408. }
  4409. }
  4410. // Operations are used to wrap a series of changes to the editor
  4411. // state in such a way that each change won't have to update the
  4412. // cursor and display (which would be awkward, slow, and
  4413. // error-prone). Instead, display updates are batched and then all
  4414. // combined and executed at once.
  4415. var nextOpId = 0;
  4416. // Start a new operation.
  4417. function startOperation(cm) {
  4418. cm.curOp = {
  4419. cm: cm,
  4420. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  4421. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  4422. forceUpdate: false, // Used to force a redraw
  4423. updateInput: 0, // Whether to reset the input textarea
  4424. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  4425. changeObjs: null, // Accumulated changes, for firing change events
  4426. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  4427. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  4428. selectionChanged: false, // Whether the selection needs to be redrawn
  4429. updateMaxLine: false, // Set when the widest line needs to be determined anew
  4430. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  4431. scrollToPos: null, // Used to scroll to a specific position
  4432. focus: false,
  4433. id: ++nextOpId // Unique ID
  4434. };
  4435. pushOperation(cm.curOp);
  4436. }
  4437. // Finish an operation, updating the display and signalling delayed events
  4438. function endOperation(cm) {
  4439. var op = cm.curOp;
  4440. if (op) {
  4441. finishOperation(op, function (group) {
  4442. for (var i = 0; i < group.ops.length; i++) {
  4443. group.ops[i].cm.curOp = null;
  4444. }
  4445. endOperations(group);
  4446. });
  4447. }
  4448. }
  4449. // The DOM updates done when an operation finishes are batched so
  4450. // that the minimum number of relayouts are required.
  4451. function endOperations(group) {
  4452. var ops = group.ops;
  4453. for (var i = 0; i < ops.length; i++) // Read DOM
  4454. {
  4455. endOperation_R1(ops[i]);
  4456. }
  4457. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  4458. {
  4459. endOperation_W1(ops[i$1]);
  4460. }
  4461. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  4462. {
  4463. endOperation_R2(ops[i$2]);
  4464. }
  4465. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  4466. {
  4467. endOperation_W2(ops[i$3]);
  4468. }
  4469. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  4470. {
  4471. endOperation_finish(ops[i$4]);
  4472. }
  4473. }
  4474. function endOperation_R1(op) {
  4475. var cm = op.cm, display = cm.display;
  4476. maybeClipScrollbars(cm);
  4477. if (op.updateMaxLine) {
  4478. findMaxLine(cm);
  4479. }
  4480. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  4481. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  4482. op.scrollToPos.to.line >= display.viewTo) ||
  4483. display.maxLineChanged && cm.options.lineWrapping;
  4484. op.update = op.mustUpdate &&
  4485. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  4486. }
  4487. function endOperation_W1(op) {
  4488. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  4489. }
  4490. function endOperation_R2(op) {
  4491. var cm = op.cm, display = cm.display;
  4492. if (op.updatedDisplay) {
  4493. updateHeightsInViewport(cm);
  4494. }
  4495. op.barMeasure = measureForScrollbars(cm);
  4496. // If the max line changed since it was last measured, measure it,
  4497. // and ensure the document's width matches it.
  4498. // updateDisplay_W2 will use these properties to do the actual resizing
  4499. if (display.maxLineChanged && !cm.options.lineWrapping) {
  4500. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  4501. cm.display.sizerWidth = op.adjustWidthTo;
  4502. op.barMeasure.scrollWidth =
  4503. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  4504. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  4505. }
  4506. if (op.updatedDisplay || op.selectionChanged) {
  4507. op.preparedSelection = display.input.prepareSelection();
  4508. }
  4509. }
  4510. function endOperation_W2(op) {
  4511. var cm = op.cm;
  4512. if (op.adjustWidthTo != null) {
  4513. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  4514. if (op.maxScrollLeft < cm.doc.scrollLeft) {
  4515. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  4516. }
  4517. cm.display.maxLineChanged = false;
  4518. }
  4519. var takeFocus = op.focus && op.focus == activeElt();
  4520. if (op.preparedSelection) {
  4521. cm.display.input.showSelection(op.preparedSelection, takeFocus);
  4522. }
  4523. if (op.updatedDisplay || op.startHeight != cm.doc.height) {
  4524. updateScrollbars(cm, op.barMeasure);
  4525. }
  4526. if (op.updatedDisplay) {
  4527. setDocumentHeight(cm, op.barMeasure);
  4528. }
  4529. if (op.selectionChanged) {
  4530. restartBlink(cm);
  4531. }
  4532. if (cm.state.focused && op.updateInput) {
  4533. cm.display.input.reset(op.typing);
  4534. }
  4535. if (takeFocus) {
  4536. ensureFocus(op.cm);
  4537. }
  4538. }
  4539. function endOperation_finish(op) {
  4540. var cm = op.cm, display = cm.display, doc = cm.doc;
  4541. if (op.updatedDisplay) {
  4542. postUpdateDisplay(cm, op.update);
  4543. }
  4544. // Abort mouse wheel delta measurement, when scrolling explicitly
  4545. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {
  4546. display.wheelStartX = display.wheelStartY = null;
  4547. }
  4548. // Propagate the scroll position to the actual DOM scroller
  4549. if (op.scrollTop != null) {
  4550. setScrollTop(cm, op.scrollTop, op.forceScroll);
  4551. }
  4552. if (op.scrollLeft != null) {
  4553. setScrollLeft(cm, op.scrollLeft, true, true);
  4554. }
  4555. // If we need to scroll a specific position into view, do so.
  4556. if (op.scrollToPos) {
  4557. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  4558. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  4559. maybeScrollWindow(cm, rect);
  4560. }
  4561. // Fire events for markers that are hidden/unidden by editing or
  4562. // undoing
  4563. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  4564. if (hidden) {
  4565. for (var i = 0; i < hidden.length; ++i) {
  4566. if (!hidden[i].lines.length) {
  4567. signal(hidden[i], "hide");
  4568. }
  4569. }
  4570. }
  4571. if (unhidden) {
  4572. for (var i$1 = 0; i$1 < unhidden.length; ++i$1) {
  4573. if (unhidden[i$1].lines.length) {
  4574. signal(unhidden[i$1], "unhide");
  4575. }
  4576. }
  4577. }
  4578. if (display.wrapper.offsetHeight) {
  4579. doc.scrollTop = cm.display.scroller.scrollTop;
  4580. }
  4581. // Fire change events, and delayed event handlers
  4582. if (op.changeObjs) {
  4583. signal(cm, "changes", cm, op.changeObjs);
  4584. }
  4585. if (op.update) {
  4586. op.update.finish();
  4587. }
  4588. }
  4589. // Run the given function in an operation
  4590. function runInOp(cm, f) {
  4591. if (cm.curOp) {
  4592. return f()
  4593. }
  4594. startOperation(cm);
  4595. try {
  4596. return f()
  4597. } finally {
  4598. endOperation(cm);
  4599. }
  4600. }
  4601. // Wraps a function in an operation. Returns the wrapped function.
  4602. function operation(cm, f) {
  4603. return function () {
  4604. if (cm.curOp) {
  4605. return f.apply(cm, arguments)
  4606. }
  4607. startOperation(cm);
  4608. try {
  4609. return f.apply(cm, arguments)
  4610. } finally {
  4611. endOperation(cm);
  4612. }
  4613. }
  4614. }
  4615. // Used to add methods to editor and doc instances, wrapping them in
  4616. // operations.
  4617. function methodOp(f) {
  4618. return function () {
  4619. if (this.curOp) {
  4620. return f.apply(this, arguments)
  4621. }
  4622. startOperation(this);
  4623. try {
  4624. return f.apply(this, arguments)
  4625. } finally {
  4626. endOperation(this);
  4627. }
  4628. }
  4629. }
  4630. function docMethodOp(f) {
  4631. return function () {
  4632. var cm = this.cm;
  4633. if (!cm || cm.curOp) {
  4634. return f.apply(this, arguments)
  4635. }
  4636. startOperation(cm);
  4637. try {
  4638. return f.apply(this, arguments)
  4639. } finally {
  4640. endOperation(cm);
  4641. }
  4642. }
  4643. }
  4644. // HIGHLIGHT WORKER
  4645. function startWorker(cm, time) {
  4646. if (cm.doc.highlightFrontier < cm.display.viewTo) {
  4647. cm.state.highlight.set(time, bind(highlightWorker, cm));
  4648. }
  4649. }
  4650. function highlightWorker(cm) {
  4651. var doc = cm.doc;
  4652. if (doc.highlightFrontier >= cm.display.viewTo) {
  4653. return
  4654. }
  4655. var end = +new Date + cm.options.workTime;
  4656. var context = getContextBefore(cm, doc.highlightFrontier);
  4657. var changedLines = [];
  4658. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  4659. if (context.line >= cm.display.viewFrom) { // Visible
  4660. var oldStyles = line.styles;
  4661. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  4662. var highlighted = highlightLine(cm, line, context, true);
  4663. if (resetState) {
  4664. context.state = resetState;
  4665. }
  4666. line.styles = highlighted.styles;
  4667. var oldCls = line.styleClasses, newCls = highlighted.classes;
  4668. if (newCls) {
  4669. line.styleClasses = newCls;
  4670. } else if (oldCls) {
  4671. line.styleClasses = null;
  4672. }
  4673. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  4674. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  4675. for (var i = 0; !ischange && i < oldStyles.length; ++i) {
  4676. ischange = oldStyles[i] != line.styles[i];
  4677. }
  4678. if (ischange) {
  4679. changedLines.push(context.line);
  4680. }
  4681. line.stateAfter = context.save();
  4682. context.nextLine();
  4683. } else {
  4684. if (line.text.length <= cm.options.maxHighlightLength) {
  4685. processLine(cm, line.text, context);
  4686. }
  4687. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  4688. context.nextLine();
  4689. }
  4690. if (+new Date > end) {
  4691. startWorker(cm, cm.options.workDelay);
  4692. return true
  4693. }
  4694. });
  4695. doc.highlightFrontier = context.line;
  4696. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  4697. if (changedLines.length) {
  4698. runInOp(cm, function () {
  4699. for (var i = 0; i < changedLines.length; i++) {
  4700. regLineChange(cm, changedLines[i], "text");
  4701. }
  4702. });
  4703. }
  4704. }
  4705. // DISPLAY DRAWING
  4706. var DisplayUpdate = function (cm, viewport, force) {
  4707. var display = cm.display;
  4708. this.viewport = viewport;
  4709. // Store some values that we'll need later (but don't want to force a relayout for)
  4710. this.visible = visibleLines(display, cm.doc, viewport);
  4711. this.editorIsHidden = !display.wrapper.offsetWidth;
  4712. this.wrapperHeight = display.wrapper.clientHeight;
  4713. this.wrapperWidth = display.wrapper.clientWidth;
  4714. this.oldDisplayWidth = displayWidth(cm);
  4715. this.force = force;
  4716. this.dims = getDimensions(cm);
  4717. this.events = [];
  4718. };
  4719. DisplayUpdate.prototype.signal = function (emitter, type) {
  4720. if (hasHandler(emitter, type)) {
  4721. this.events.push(arguments);
  4722. }
  4723. };
  4724. DisplayUpdate.prototype.finish = function () {
  4725. for (var i = 0; i < this.events.length; i++) {
  4726. signal.apply(null, this.events[i]);
  4727. }
  4728. };
  4729. function maybeClipScrollbars(cm) {
  4730. var display = cm.display;
  4731. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  4732. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  4733. display.heightForcer.style.height = scrollGap(cm) + "px";
  4734. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  4735. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  4736. display.scrollbarsClipped = true;
  4737. }
  4738. }
  4739. function selectionSnapshot(cm) {
  4740. if (cm.hasFocus()) {
  4741. return null
  4742. }
  4743. var active = activeElt();
  4744. if (!active || !contains(cm.display.lineDiv, active)) {
  4745. return null
  4746. }
  4747. var result = {activeElt: active};
  4748. if (window.getSelection) {
  4749. var sel = window.getSelection();
  4750. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  4751. result.anchorNode = sel.anchorNode;
  4752. result.anchorOffset = sel.anchorOffset;
  4753. result.focusNode = sel.focusNode;
  4754. result.focusOffset = sel.focusOffset;
  4755. }
  4756. }
  4757. return result
  4758. }
  4759. function restoreSelection(snapshot) {
  4760. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) {
  4761. return
  4762. }
  4763. snapshot.activeElt.focus();
  4764. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  4765. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  4766. var sel = window.getSelection(), range = document.createRange();
  4767. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  4768. range.collapse(false);
  4769. sel.removeAllRanges();
  4770. sel.addRange(range);
  4771. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  4772. }
  4773. }
  4774. // Does the actual updating of the line display. Bails out
  4775. // (returning false) when there is nothing to be done and forced is
  4776. // false.
  4777. function updateDisplayIfNeeded(cm, update) {
  4778. var display = cm.display, doc = cm.doc;
  4779. if (update.editorIsHidden) {
  4780. resetView(cm);
  4781. return false
  4782. }
  4783. // Bail out if the visible area is already rendered and nothing changed.
  4784. if (!update.force &&
  4785. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  4786. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  4787. display.renderedView == display.view && countDirtyView(cm) == 0) {
  4788. return false
  4789. }
  4790. if (maybeUpdateLineNumberWidth(cm)) {
  4791. resetView(cm);
  4792. update.dims = getDimensions(cm);
  4793. }
  4794. // Compute a suitable new viewport (from & to)
  4795. var end = doc.first + doc.size;
  4796. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  4797. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  4798. if (display.viewFrom < from && from - display.viewFrom < 20) {
  4799. from = Math.max(doc.first, display.viewFrom);
  4800. }
  4801. if (display.viewTo > to && display.viewTo - to < 20) {
  4802. to = Math.min(end, display.viewTo);
  4803. }
  4804. if (sawCollapsedSpans) {
  4805. from = visualLineNo(cm.doc, from);
  4806. to = visualLineEndNo(cm.doc, to);
  4807. }
  4808. var different = from != display.viewFrom || to != display.viewTo ||
  4809. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  4810. adjustView(cm, from, to);
  4811. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  4812. // Position the mover div to align with the current scroll position
  4813. cm.display.mover.style.top = display.viewOffset + "px";
  4814. var toUpdate = countDirtyView(cm);
  4815. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  4816. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {
  4817. return false
  4818. }
  4819. // For big changes, we hide the enclosing element during the
  4820. // update, since that speeds up the operations on most browsers.
  4821. var selSnapshot = selectionSnapshot(cm);
  4822. if (toUpdate > 4) {
  4823. display.lineDiv.style.display = "none";
  4824. }
  4825. patchDisplay(cm, display.updateLineNumbers, update.dims);
  4826. if (toUpdate > 4) {
  4827. display.lineDiv.style.display = "";
  4828. }
  4829. display.renderedView = display.view;
  4830. // There might have been a widget with a focused element that got
  4831. // hidden or updated, if so re-focus it.
  4832. restoreSelection(selSnapshot);
  4833. // Prevent selection and cursors from interfering with the scroll
  4834. // width and height.
  4835. removeChildren(display.cursorDiv);
  4836. removeChildren(display.selectionDiv);
  4837. display.gutters.style.height = display.sizer.style.minHeight = 0;
  4838. if (different) {
  4839. display.lastWrapHeight = update.wrapperHeight;
  4840. display.lastWrapWidth = update.wrapperWidth;
  4841. startWorker(cm, 400);
  4842. }
  4843. display.updateLineNumbers = null;
  4844. return true
  4845. }
  4846. function postUpdateDisplay(cm, update) {
  4847. var viewport = update.viewport;
  4848. for (var first = true; ; first = false) {
  4849. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  4850. // Clip forced viewport to actual scrollable area.
  4851. if (viewport && viewport.top != null) {
  4852. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  4853. }
  4854. // Updated line heights might result in the drawn area not
  4855. // actually covering the viewport. Keep looping until it does.
  4856. update.visible = visibleLines(cm.display, cm.doc, viewport);
  4857. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) {
  4858. break
  4859. }
  4860. } else if (first) {
  4861. update.visible = visibleLines(cm.display, cm.doc, viewport);
  4862. }
  4863. if (!updateDisplayIfNeeded(cm, update)) {
  4864. break
  4865. }
  4866. updateHeightsInViewport(cm);
  4867. var barMeasure = measureForScrollbars(cm);
  4868. updateSelection(cm);
  4869. updateScrollbars(cm, barMeasure);
  4870. setDocumentHeight(cm, barMeasure);
  4871. update.force = false;
  4872. }
  4873. update.signal(cm, "update", cm);
  4874. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  4875. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  4876. cm.display.reportedViewFrom = cm.display.viewFrom;
  4877. cm.display.reportedViewTo = cm.display.viewTo;
  4878. }
  4879. }
  4880. function updateDisplaySimple(cm, viewport) {
  4881. var update = new DisplayUpdate(cm, viewport);
  4882. if (updateDisplayIfNeeded(cm, update)) {
  4883. updateHeightsInViewport(cm);
  4884. postUpdateDisplay(cm, update);
  4885. var barMeasure = measureForScrollbars(cm);
  4886. updateSelection(cm);
  4887. updateScrollbars(cm, barMeasure);
  4888. setDocumentHeight(cm, barMeasure);
  4889. update.finish();
  4890. }
  4891. }
  4892. // Sync the actual display DOM structure with display.view, removing
  4893. // nodes for lines that are no longer in view, and creating the ones
  4894. // that are not there yet, and updating the ones that are out of
  4895. // date.
  4896. function patchDisplay(cm, updateNumbersFrom, dims) {
  4897. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  4898. var container = display.lineDiv, cur = container.firstChild;
  4899. function rm(node) {
  4900. var next = node.nextSibling;
  4901. // Works around a throw-scroll bug in OS X Webkit
  4902. if (webkit && mac && cm.display.currentWheelTarget == node) {
  4903. node.style.display = "none";
  4904. } else {
  4905. node.parentNode.removeChild(node);
  4906. }
  4907. return next
  4908. }
  4909. var view = display.view, lineN = display.viewFrom;
  4910. // Loop over the elements in the view, syncing cur (the DOM nodes
  4911. // in display.lineDiv) with the view as we go.
  4912. for (var i = 0; i < view.length; i++) {
  4913. var lineView = view[i];
  4914. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  4915. var node = buildLineElement(cm, lineView, lineN, dims);
  4916. container.insertBefore(node, cur);
  4917. } else { // Already drawn
  4918. while (cur != lineView.node) {
  4919. cur = rm(cur);
  4920. }
  4921. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  4922. updateNumbersFrom <= lineN && lineView.lineNumber;
  4923. if (lineView.changes) {
  4924. if (indexOf(lineView.changes, "gutter") > -1) {
  4925. updateNumber = false;
  4926. }
  4927. updateLineForChanges(cm, lineView, lineN, dims);
  4928. }
  4929. if (updateNumber) {
  4930. removeChildren(lineView.lineNumber);
  4931. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  4932. }
  4933. cur = lineView.node.nextSibling;
  4934. }
  4935. lineN += lineView.size;
  4936. }
  4937. while (cur) {
  4938. cur = rm(cur);
  4939. }
  4940. }
  4941. function updateGutterSpace(display) {
  4942. var width = display.gutters.offsetWidth;
  4943. display.sizer.style.marginLeft = width + "px";
  4944. }
  4945. function setDocumentHeight(cm, measure) {
  4946. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  4947. cm.display.heightForcer.style.top = measure.docHeight + "px";
  4948. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  4949. }
  4950. // Re-align line numbers and gutter marks to compensate for
  4951. // horizontal scrolling.
  4952. function alignHorizontally(cm) {
  4953. var display = cm.display, view = display.view;
  4954. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) {
  4955. return
  4956. }
  4957. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  4958. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  4959. for (var i = 0; i < view.length; i++) {
  4960. if (!view[i].hidden) {
  4961. if (cm.options.fixedGutter) {
  4962. if (view[i].gutter) {
  4963. view[i].gutter.style.left = left;
  4964. }
  4965. if (view[i].gutterBackground) {
  4966. view[i].gutterBackground.style.left = left;
  4967. }
  4968. }
  4969. var align = view[i].alignable;
  4970. if (align) {
  4971. for (var j = 0; j < align.length; j++) {
  4972. align[j].style.left = left;
  4973. }
  4974. }
  4975. }
  4976. }
  4977. if (cm.options.fixedGutter) {
  4978. display.gutters.style.left = (comp + gutterW) + "px";
  4979. }
  4980. }
  4981. // Used to ensure that the line number gutter is still the right
  4982. // size for the current document size. Returns true when an update
  4983. // is needed.
  4984. function maybeUpdateLineNumberWidth(cm) {
  4985. if (!cm.options.lineNumbers) {
  4986. return false
  4987. }
  4988. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  4989. if (last.length != display.lineNumChars) {
  4990. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  4991. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  4992. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  4993. display.lineGutter.style.width = "";
  4994. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  4995. display.lineNumWidth = display.lineNumInnerWidth + padding;
  4996. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  4997. display.lineGutter.style.width = display.lineNumWidth + "px";
  4998. updateGutterSpace(cm.display);
  4999. return true
  5000. }
  5001. return false
  5002. }
  5003. function getGutters(gutters, lineNumbers) {
  5004. var result = [], sawLineNumbers = false;
  5005. for (var i = 0; i < gutters.length; i++) {
  5006. var name = gutters[i], style = null;
  5007. if (typeof name != "string") {
  5008. style = name.style;
  5009. name = name.className;
  5010. }
  5011. if (name == "CodeMirror-linenumbers") {
  5012. if (!lineNumbers) {
  5013. continue
  5014. } else {
  5015. sawLineNumbers = true;
  5016. }
  5017. }
  5018. result.push({className: name, style: style});
  5019. }
  5020. if (lineNumbers && !sawLineNumbers) {
  5021. result.push({className: "CodeMirror-linenumbers", style: null});
  5022. }
  5023. return result
  5024. }
  5025. // Rebuild the gutter elements, ensure the margin to the left of the
  5026. // code matches their width.
  5027. function renderGutters(display) {
  5028. var gutters = display.gutters, specs = display.gutterSpecs;
  5029. removeChildren(gutters);
  5030. display.lineGutter = null;
  5031. for (var i = 0; i < specs.length; ++i) {
  5032. var ref = specs[i];
  5033. var className = ref.className;
  5034. var style = ref.style;
  5035. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  5036. if (style) {
  5037. gElt.style.cssText = style;
  5038. }
  5039. if (className == "CodeMirror-linenumbers") {
  5040. display.lineGutter = gElt;
  5041. gElt.style.width = (display.lineNumWidth || 1) + "px";
  5042. }
  5043. }
  5044. gutters.style.display = specs.length ? "" : "none";
  5045. updateGutterSpace(display);
  5046. }
  5047. function updateGutters(cm) {
  5048. renderGutters(cm.display);
  5049. regChange(cm);
  5050. alignHorizontally(cm);
  5051. }
  5052. // The display handles the DOM integration, both for input reading
  5053. // and content drawing. It holds references to DOM nodes and
  5054. // display-related state.
  5055. function Display(place, doc, input, options) {
  5056. var d = this;
  5057. this.input = input;
  5058. // Covers bottom-right square when both scrollbars are present.
  5059. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  5060. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  5061. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  5062. // and h scrollbar is present.
  5063. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  5064. d.gutterFiller.setAttribute("cm-not-content", "true");
  5065. // Will contain the actual code, positioned to cover the viewport.
  5066. d.lineDiv = eltP("div", null, "CodeMirror-code");
  5067. // Elements are added to these to represent selection and cursors.
  5068. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  5069. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  5070. // A visibility: hidden element used to find the size of things.
  5071. d.measure = elt("div", null, "CodeMirror-measure");
  5072. // When lines outside of the viewport are measured, they are drawn in this.
  5073. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  5074. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  5075. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  5076. null, "position: relative; outline: none");
  5077. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  5078. // Moved around its parent to cover visible view.
  5079. d.mover = elt("div", [lines], null, "position: relative");
  5080. // Set to the height of the document, allowing scrolling.
  5081. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  5082. d.sizerWidth = null;
  5083. // Behavior of elts with overflow: auto and padding is
  5084. // inconsistent across browsers. This is used to ensure the
  5085. // scrollable area is big enough.
  5086. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  5087. // Will contain the gutters, if any.
  5088. d.gutters = elt("div", null, "CodeMirror-gutters");
  5089. d.lineGutter = null;
  5090. // Actual scrollable element.
  5091. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  5092. d.scroller.setAttribute("tabIndex", "-1");
  5093. // The element in which the editor lives.
  5094. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  5095. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  5096. if (ie && ie_version < 8) {
  5097. d.gutters.style.zIndex = -1;
  5098. d.scroller.style.paddingRight = 0;
  5099. }
  5100. if (!webkit && !(gecko && mobile)) {
  5101. d.scroller.draggable = true;
  5102. }
  5103. if (place) {
  5104. if (place.appendChild) {
  5105. place.appendChild(d.wrapper);
  5106. } else {
  5107. place(d.wrapper);
  5108. }
  5109. }
  5110. // Current rendered range (may be bigger than the view window).
  5111. d.viewFrom = d.viewTo = doc.first;
  5112. d.reportedViewFrom = d.reportedViewTo = doc.first;
  5113. // Information about the rendered lines.
  5114. d.view = [];
  5115. d.renderedView = null;
  5116. // Holds info about a single rendered line when it was rendered
  5117. // for measurement, while not in view.
  5118. d.externalMeasured = null;
  5119. // Empty space (in pixels) above the view
  5120. d.viewOffset = 0;
  5121. d.lastWrapHeight = d.lastWrapWidth = 0;
  5122. d.updateLineNumbers = null;
  5123. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  5124. d.scrollbarsClipped = false;
  5125. // Used to only resize the line number gutter when necessary (when
  5126. // the amount of lines crosses a boundary that makes its width change)
  5127. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  5128. // Set to true when a non-horizontal-scrolling line widget is
  5129. // added. As an optimization, line widget aligning is skipped when
  5130. // this is false.
  5131. d.alignWidgets = false;
  5132. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5133. // Tracks the maximum line length so that the horizontal scrollbar
  5134. // can be kept static when scrolling.
  5135. d.maxLine = null;
  5136. d.maxLineLength = 0;
  5137. d.maxLineChanged = false;
  5138. // Used for measuring wheel scrolling granularity
  5139. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  5140. // True when shift is held down.
  5141. d.shift = false;
  5142. // Used to track whether anything happened since the context menu
  5143. // was opened.
  5144. d.selForContextMenu = null;
  5145. d.activeTouch = null;
  5146. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  5147. renderGutters(d);
  5148. input.init(d);
  5149. }
  5150. // Since the delta values reported on mouse wheel events are
  5151. // unstandardized between browsers and even browser versions, and
  5152. // generally horribly unpredictable, this code starts by measuring
  5153. // the scroll effect that the first few mouse wheel events have,
  5154. // and, from that, detects the way it can convert deltas to pixel
  5155. // offsets afterwards.
  5156. //
  5157. // The reason we want to know the amount a wheel event will scroll
  5158. // is that it gives us a chance to update the display before the
  5159. // actual scrolling happens, reducing flickering.
  5160. var wheelSamples = 0, wheelPixelsPerUnit = null;
  5161. // Fill in a browser-detected starting value on browsers where we
  5162. // know one. These don't have to be accurate -- the result of them
  5163. // being wrong would just be a slight flicker on the first wheel
  5164. // scroll (if it is large enough).
  5165. if (ie) {
  5166. wheelPixelsPerUnit = -.53;
  5167. } else if (gecko) {
  5168. wheelPixelsPerUnit = 15;
  5169. } else if (chrome) {
  5170. wheelPixelsPerUnit = -.7;
  5171. } else if (safari) {
  5172. wheelPixelsPerUnit = -1 / 3;
  5173. }
  5174. function wheelEventDelta(e) {
  5175. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  5176. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) {
  5177. dx = e.detail;
  5178. }
  5179. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) {
  5180. dy = e.detail;
  5181. } else if (dy == null) {
  5182. dy = e.wheelDelta;
  5183. }
  5184. return {x: dx, y: dy}
  5185. }
  5186. function wheelEventPixels(e) {
  5187. var delta = wheelEventDelta(e);
  5188. delta.x *= wheelPixelsPerUnit;
  5189. delta.y *= wheelPixelsPerUnit;
  5190. return delta
  5191. }
  5192. function onScrollWheel(cm, e) {
  5193. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  5194. var display = cm.display, scroll = display.scroller;
  5195. // Quit if there's nothing to scroll here
  5196. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  5197. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  5198. if (!(dx && canScrollX || dy && canScrollY)) {
  5199. return
  5200. }
  5201. // Webkit browsers on OS X abort momentum scrolls when the target
  5202. // of the scroll event is removed from the scrollable element.
  5203. // This hack (see related code in patchDisplay) makes sure the
  5204. // element is kept around.
  5205. if (dy && mac && webkit) {
  5206. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  5207. for (var i = 0; i < view.length; i++) {
  5208. if (view[i].node == cur) {
  5209. cm.display.currentWheelTarget = cur;
  5210. break outer
  5211. }
  5212. }
  5213. }
  5214. }
  5215. // On some browsers, horizontal scrolling will cause redraws to
  5216. // happen before the gutter has been realigned, causing it to
  5217. // wriggle around in a most unseemly way. When we have an
  5218. // estimated pixels/delta value, we just handle horizontal
  5219. // scrolling entirely here. It'll be slightly off from native, but
  5220. // better than glitching out.
  5221. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  5222. if (dy && canScrollY) {
  5223. updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit));
  5224. }
  5225. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  5226. // Only prevent default scrolling if vertical scrolling is
  5227. // actually possible. Otherwise, it causes vertical scroll
  5228. // jitter on OSX trackpads when deltaX is small and deltaY
  5229. // is large (issue #3579)
  5230. if (!dy || (dy && canScrollY)) {
  5231. e_preventDefault(e);
  5232. }
  5233. display.wheelStartX = null; // Abort measurement, if in progress
  5234. return
  5235. }
  5236. // 'Project' the visible viewport to cover the area that is being
  5237. // scrolled into view (if we know enough to estimate it).
  5238. if (dy && wheelPixelsPerUnit != null) {
  5239. var pixels = dy * wheelPixelsPerUnit;
  5240. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  5241. if (pixels < 0) {
  5242. top = Math.max(0, top + pixels - 50);
  5243. } else {
  5244. bot = Math.min(cm.doc.height, bot + pixels + 50);
  5245. }
  5246. updateDisplaySimple(cm, {top: top, bottom: bot});
  5247. }
  5248. if (wheelSamples < 20) {
  5249. if (display.wheelStartX == null) {
  5250. display.wheelStartX = scroll.scrollLeft;
  5251. display.wheelStartY = scroll.scrollTop;
  5252. display.wheelDX = dx;
  5253. display.wheelDY = dy;
  5254. setTimeout(function () {
  5255. if (display.wheelStartX == null) {
  5256. return
  5257. }
  5258. var movedX = scroll.scrollLeft - display.wheelStartX;
  5259. var movedY = scroll.scrollTop - display.wheelStartY;
  5260. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  5261. (movedX && display.wheelDX && movedX / display.wheelDX);
  5262. display.wheelStartX = display.wheelStartY = null;
  5263. if (!sample) {
  5264. return
  5265. }
  5266. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  5267. ++wheelSamples;
  5268. }, 200);
  5269. } else {
  5270. display.wheelDX += dx;
  5271. display.wheelDY += dy;
  5272. }
  5273. }
  5274. }
  5275. // Selection objects are immutable. A new one is created every time
  5276. // the selection changes. A selection is one or more non-overlapping
  5277. // (and non-touching) ranges, sorted, and an integer that indicates
  5278. // which one is the primary selection (the one that's scrolled into
  5279. // view, that getCursor returns, etc).
  5280. var Selection = function (ranges, primIndex) {
  5281. this.ranges = ranges;
  5282. this.primIndex = primIndex;
  5283. };
  5284. Selection.prototype.primary = function () {
  5285. return this.ranges[this.primIndex]
  5286. };
  5287. Selection.prototype.equals = function (other) {
  5288. if (other == this) {
  5289. return true
  5290. }
  5291. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) {
  5292. return false
  5293. }
  5294. for (var i = 0; i < this.ranges.length; i++) {
  5295. var here = this.ranges[i], there = other.ranges[i];
  5296. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) {
  5297. return false
  5298. }
  5299. }
  5300. return true
  5301. };
  5302. Selection.prototype.deepCopy = function () {
  5303. var out = [];
  5304. for (var i = 0; i < this.ranges.length; i++) {
  5305. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  5306. }
  5307. return new Selection(out, this.primIndex)
  5308. };
  5309. Selection.prototype.somethingSelected = function () {
  5310. for (var i = 0; i < this.ranges.length; i++) {
  5311. if (!this.ranges[i].empty()) {
  5312. return true
  5313. }
  5314. }
  5315. return false
  5316. };
  5317. Selection.prototype.contains = function (pos, end) {
  5318. if (!end) {
  5319. end = pos;
  5320. }
  5321. for (var i = 0; i < this.ranges.length; i++) {
  5322. var range = this.ranges[i];
  5323. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) {
  5324. return i
  5325. }
  5326. }
  5327. return -1
  5328. };
  5329. var Range = function (anchor, head) {
  5330. this.anchor = anchor;
  5331. this.head = head;
  5332. };
  5333. Range.prototype.from = function () {
  5334. return minPos(this.anchor, this.head)
  5335. };
  5336. Range.prototype.to = function () {
  5337. return maxPos(this.anchor, this.head)
  5338. };
  5339. Range.prototype.empty = function () {
  5340. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch
  5341. };
  5342. // Take an unsorted, potentially overlapping set of ranges, and
  5343. // build a selection out of it. 'Consumes' ranges array (modifying
  5344. // it).
  5345. function normalizeSelection(cm, ranges, primIndex) {
  5346. var mayTouch = cm && cm.options.selectionsMayTouch;
  5347. var prim = ranges[primIndex];
  5348. ranges.sort(function (a, b) {
  5349. return cmp(a.from(), b.from());
  5350. });
  5351. primIndex = indexOf(ranges, prim);
  5352. for (var i = 1; i < ranges.length; i++) {
  5353. var cur = ranges[i], prev = ranges[i - 1];
  5354. var diff = cmp(prev.to(), cur.from());
  5355. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  5356. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  5357. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  5358. if (i <= primIndex) {
  5359. --primIndex;
  5360. }
  5361. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  5362. }
  5363. }
  5364. return new Selection(ranges, primIndex)
  5365. }
  5366. function simpleSelection(anchor, head) {
  5367. return new Selection([new Range(anchor, head || anchor)], 0)
  5368. }
  5369. // Compute the position of the end of a change (its 'to' property
  5370. // refers to the pre-change end).
  5371. function changeEnd(change) {
  5372. if (!change.text) {
  5373. return change.to
  5374. }
  5375. return Pos(change.from.line + change.text.length - 1,
  5376. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  5377. }
  5378. // Adjust a position to refer to the post-change position of the
  5379. // same text, or the end of the change if the change covers it.
  5380. function adjustForChange(pos, change) {
  5381. if (cmp(pos, change.from) < 0) {
  5382. return pos
  5383. }
  5384. if (cmp(pos, change.to) <= 0) {
  5385. return changeEnd(change)
  5386. }
  5387. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  5388. if (pos.line == change.to.line) {
  5389. ch += changeEnd(change).ch - change.to.ch;
  5390. }
  5391. return Pos(line, ch)
  5392. }
  5393. function computeSelAfterChange(doc, change) {
  5394. var out = [];
  5395. for (var i = 0; i < doc.sel.ranges.length; i++) {
  5396. var range = doc.sel.ranges[i];
  5397. out.push(new Range(adjustForChange(range.anchor, change),
  5398. adjustForChange(range.head, change)));
  5399. }
  5400. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  5401. }
  5402. function offsetPos(pos, old, nw) {
  5403. if (pos.line == old.line) {
  5404. return Pos(nw.line, pos.ch - old.ch + nw.ch)
  5405. } else {
  5406. return Pos(nw.line + (pos.line - old.line), pos.ch)
  5407. }
  5408. }
  5409. // Used by replaceSelections to allow moving the selection to the
  5410. // start or around the replaced test. Hint may be "start" or "around".
  5411. function computeReplacedSel(doc, changes, hint) {
  5412. var out = [];
  5413. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  5414. for (var i = 0; i < changes.length; i++) {
  5415. var change = changes[i];
  5416. var from = offsetPos(change.from, oldPrev, newPrev);
  5417. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  5418. oldPrev = change.to;
  5419. newPrev = to;
  5420. if (hint == "around") {
  5421. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  5422. out[i] = new Range(inv ? to : from, inv ? from : to);
  5423. } else {
  5424. out[i] = new Range(from, from);
  5425. }
  5426. }
  5427. return new Selection(out, doc.sel.primIndex)
  5428. }
  5429. // Used to get the editor into a consistent state again when options change.
  5430. function loadMode(cm) {
  5431. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  5432. resetModeState(cm);
  5433. }
  5434. function resetModeState(cm) {
  5435. cm.doc.iter(function (line) {
  5436. if (line.stateAfter) {
  5437. line.stateAfter = null;
  5438. }
  5439. if (line.styles) {
  5440. line.styles = null;
  5441. }
  5442. });
  5443. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  5444. startWorker(cm, 100);
  5445. cm.state.modeGen++;
  5446. if (cm.curOp) {
  5447. regChange(cm);
  5448. }
  5449. }
  5450. // DOCUMENT DATA STRUCTURE
  5451. // By default, updates that start and end at the beginning of a line
  5452. // are treated specially, in order to make the association of line
  5453. // widgets and marker elements with the text behave more intuitive.
  5454. function isWholeLineUpdate(doc, change) {
  5455. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  5456. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  5457. }
  5458. // Perform a change on the document data structure.
  5459. function updateDoc(doc, change, markedSpans, estimateHeight) {
  5460. function spansFor(n) {
  5461. return markedSpans ? markedSpans[n] : null
  5462. }
  5463. function update(line, text, spans) {
  5464. updateLine(line, text, spans, estimateHeight);
  5465. signalLater(line, "change", line, change);
  5466. }
  5467. function linesFor(start, end) {
  5468. var result = [];
  5469. for (var i = start; i < end; ++i) {
  5470. result.push(new Line(text[i], spansFor(i), estimateHeight));
  5471. }
  5472. return result
  5473. }
  5474. var from = change.from, to = change.to, text = change.text;
  5475. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  5476. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  5477. // Adjust the line structure
  5478. if (change.full) {
  5479. doc.insert(0, linesFor(0, text.length));
  5480. doc.remove(text.length, doc.size - text.length);
  5481. } else if (isWholeLineUpdate(doc, change)) {
  5482. // This is a whole-line replace. Treated specially to make
  5483. // sure line objects move the way they are supposed to.
  5484. var added = linesFor(0, text.length - 1);
  5485. update(lastLine, lastLine.text, lastSpans);
  5486. if (nlines) {
  5487. doc.remove(from.line, nlines);
  5488. }
  5489. if (added.length) {
  5490. doc.insert(from.line, added);
  5491. }
  5492. } else if (firstLine == lastLine) {
  5493. if (text.length == 1) {
  5494. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  5495. } else {
  5496. var added$1 = linesFor(1, text.length - 1);
  5497. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  5498. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  5499. doc.insert(from.line + 1, added$1);
  5500. }
  5501. } else if (text.length == 1) {
  5502. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  5503. doc.remove(from.line + 1, nlines);
  5504. } else {
  5505. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  5506. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  5507. var added$2 = linesFor(1, text.length - 1);
  5508. if (nlines > 1) {
  5509. doc.remove(from.line + 1, nlines - 1);
  5510. }
  5511. doc.insert(from.line + 1, added$2);
  5512. }
  5513. signalLater(doc, "change", doc, change);
  5514. }
  5515. // Call f for all linked documents.
  5516. function linkedDocs(doc, f, sharedHistOnly) {
  5517. function propagate(doc, skip, sharedHist) {
  5518. if (doc.linked) {
  5519. for (var i = 0; i < doc.linked.length; ++i) {
  5520. var rel = doc.linked[i];
  5521. if (rel.doc == skip) {
  5522. continue
  5523. }
  5524. var shared = sharedHist && rel.sharedHist;
  5525. if (sharedHistOnly && !shared) {
  5526. continue
  5527. }
  5528. f(rel.doc, shared);
  5529. propagate(rel.doc, doc, shared);
  5530. }
  5531. }
  5532. }
  5533. propagate(doc, null, true);
  5534. }
  5535. // Attach a document to an editor.
  5536. function attachDoc(cm, doc) {
  5537. if (doc.cm) {
  5538. throw new Error("This document is already in use.")
  5539. }
  5540. cm.doc = doc;
  5541. doc.cm = cm;
  5542. estimateLineHeights(cm);
  5543. loadMode(cm);
  5544. setDirectionClass(cm);
  5545. if (!cm.options.lineWrapping) {
  5546. findMaxLine(cm);
  5547. }
  5548. cm.options.mode = doc.modeOption;
  5549. regChange(cm);
  5550. }
  5551. function setDirectionClass(cm) {
  5552. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  5553. }
  5554. function directionChanged(cm) {
  5555. runInOp(cm, function () {
  5556. setDirectionClass(cm);
  5557. regChange(cm);
  5558. });
  5559. }
  5560. function History(prev) {
  5561. // Arrays of change events and selections. Doing something adds an
  5562. // event to done and clears undo. Undoing moves events from done
  5563. // to undone, redoing moves them in the other direction.
  5564. this.done = [];
  5565. this.undone = [];
  5566. this.undoDepth = prev ? prev.undoDepth : Infinity;
  5567. // Used to track when changes can be merged into a single undo
  5568. // event
  5569. this.lastModTime = this.lastSelTime = 0;
  5570. this.lastOp = this.lastSelOp = null;
  5571. this.lastOrigin = this.lastSelOrigin = null;
  5572. // Used by the isClean() method
  5573. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  5574. }
  5575. // Create a history change event from an updateDoc-style change
  5576. // object.
  5577. function historyChangeFromChange(doc, change) {
  5578. var histChange = {
  5579. from: copyPos(change.from),
  5580. to: changeEnd(change),
  5581. text: getBetween(doc, change.from, change.to)
  5582. };
  5583. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  5584. linkedDocs(doc, function (doc) {
  5585. return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  5586. }, true);
  5587. return histChange
  5588. }
  5589. // Pop all selection events off the end of a history array. Stop at
  5590. // a change event.
  5591. function clearSelectionEvents(array) {
  5592. while (array.length) {
  5593. var last = lst(array);
  5594. if (last.ranges) {
  5595. array.pop();
  5596. } else {
  5597. break
  5598. }
  5599. }
  5600. }
  5601. // Find the top change event in the history. Pop off selection
  5602. // events that are in the way.
  5603. function lastChangeEvent(hist, force) {
  5604. if (force) {
  5605. clearSelectionEvents(hist.done);
  5606. return lst(hist.done)
  5607. } else if (hist.done.length && !lst(hist.done).ranges) {
  5608. return lst(hist.done)
  5609. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  5610. hist.done.pop();
  5611. return lst(hist.done)
  5612. }
  5613. }
  5614. // Register a change in the history. Merges changes that are within
  5615. // a single operation, or are close together with an origin that
  5616. // allows merging (starting with "+") into a single event.
  5617. function addChangeToHistory(doc, change, selAfter, opId) {
  5618. var hist = doc.history;
  5619. hist.undone.length = 0;
  5620. var time = +new Date, cur;
  5621. var last;
  5622. if ((hist.lastOp == opId ||
  5623. hist.lastOrigin == change.origin && change.origin &&
  5624. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  5625. change.origin.charAt(0) == "*")) &&
  5626. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  5627. // Merge this change into the last event
  5628. last = lst(cur.changes);
  5629. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  5630. // Optimized case for simple insertion -- don't want to add
  5631. // new changesets for every character typed
  5632. last.to = changeEnd(change);
  5633. } else {
  5634. // Add new sub-event
  5635. cur.changes.push(historyChangeFromChange(doc, change));
  5636. }
  5637. } else {
  5638. // Can not be merged, start a new event.
  5639. var before = lst(hist.done);
  5640. if (!before || !before.ranges) {
  5641. pushSelectionToHistory(doc.sel, hist.done);
  5642. }
  5643. cur = {
  5644. changes: [historyChangeFromChange(doc, change)],
  5645. generation: hist.generation
  5646. };
  5647. hist.done.push(cur);
  5648. while (hist.done.length > hist.undoDepth) {
  5649. hist.done.shift();
  5650. if (!hist.done[0].ranges) {
  5651. hist.done.shift();
  5652. }
  5653. }
  5654. }
  5655. hist.done.push(selAfter);
  5656. hist.generation = ++hist.maxGeneration;
  5657. hist.lastModTime = hist.lastSelTime = time;
  5658. hist.lastOp = hist.lastSelOp = opId;
  5659. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  5660. if (!last) {
  5661. signal(doc, "historyAdded");
  5662. }
  5663. }
  5664. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  5665. var ch = origin.charAt(0);
  5666. return ch == "*" ||
  5667. ch == "+" &&
  5668. prev.ranges.length == sel.ranges.length &&
  5669. prev.somethingSelected() == sel.somethingSelected() &&
  5670. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  5671. }
  5672. // Called whenever the selection changes, sets the new selection as
  5673. // the pending selection in the history, and pushes the old pending
  5674. // selection into the 'done' array when it was significantly
  5675. // different (in number of selected ranges, emptiness, or time).
  5676. function addSelectionToHistory(doc, sel, opId, options) {
  5677. var hist = doc.history, origin = options && options.origin;
  5678. // A new event is started when the previous origin does not match
  5679. // the current, or the origins don't allow matching. Origins
  5680. // starting with * are always merged, those starting with + are
  5681. // merged when similar and close together in time.
  5682. if (opId == hist.lastSelOp ||
  5683. (origin && hist.lastSelOrigin == origin &&
  5684. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  5685. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) {
  5686. hist.done[hist.done.length - 1] = sel;
  5687. } else {
  5688. pushSelectionToHistory(sel, hist.done);
  5689. }
  5690. hist.lastSelTime = +new Date;
  5691. hist.lastSelOrigin = origin;
  5692. hist.lastSelOp = opId;
  5693. if (options && options.clearRedo !== false) {
  5694. clearSelectionEvents(hist.undone);
  5695. }
  5696. }
  5697. function pushSelectionToHistory(sel, dest) {
  5698. var top = lst(dest);
  5699. if (!(top && top.ranges && top.equals(sel))) {
  5700. dest.push(sel);
  5701. }
  5702. }
  5703. // Used to store marked span information in the history.
  5704. function attachLocalSpans(doc, change, from, to) {
  5705. var existing = change["spans_" + doc.id], n = 0;
  5706. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  5707. if (line.markedSpans) {
  5708. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  5709. }
  5710. ++n;
  5711. });
  5712. }
  5713. // When un/re-doing restores text containing marked spans, those
  5714. // that have been explicitly cleared should not be restored.
  5715. function removeClearedSpans(spans) {
  5716. if (!spans) {
  5717. return null
  5718. }
  5719. var out;
  5720. for (var i = 0; i < spans.length; ++i) {
  5721. if (spans[i].marker.explicitlyCleared) {
  5722. if (!out) {
  5723. out = spans.slice(0, i);
  5724. }
  5725. } else if (out) {
  5726. out.push(spans[i]);
  5727. }
  5728. }
  5729. return !out ? spans : out.length ? out : null
  5730. }
  5731. // Retrieve and filter the old marked spans stored in a change event.
  5732. function getOldSpans(doc, change) {
  5733. var found = change["spans_" + doc.id];
  5734. if (!found) {
  5735. return null
  5736. }
  5737. var nw = [];
  5738. for (var i = 0; i < change.text.length; ++i) {
  5739. nw.push(removeClearedSpans(found[i]));
  5740. }
  5741. return nw
  5742. }
  5743. // Used for un/re-doing changes from the history. Combines the
  5744. // result of computing the existing spans with the set of spans that
  5745. // existed in the history (so that deleting around a span and then
  5746. // undoing brings back the span).
  5747. function mergeOldSpans(doc, change) {
  5748. var old = getOldSpans(doc, change);
  5749. var stretched = stretchSpansOverChange(doc, change);
  5750. if (!old) {
  5751. return stretched
  5752. }
  5753. if (!stretched) {
  5754. return old
  5755. }
  5756. for (var i = 0; i < old.length; ++i) {
  5757. var oldCur = old[i], stretchCur = stretched[i];
  5758. if (oldCur && stretchCur) {
  5759. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5760. var span = stretchCur[j];
  5761. for (var k = 0; k < oldCur.length; ++k) {
  5762. if (oldCur[k].marker == span.marker) {
  5763. continue spans
  5764. }
  5765. }
  5766. oldCur.push(span);
  5767. }
  5768. } else if (stretchCur) {
  5769. old[i] = stretchCur;
  5770. }
  5771. }
  5772. return old
  5773. }
  5774. // Used both to provide a JSON-safe object in .getHistory, and, when
  5775. // detaching a document, to split the history in two
  5776. function copyHistoryArray(events, newGroup, instantiateSel) {
  5777. var copy = [];
  5778. for (var i = 0; i < events.length; ++i) {
  5779. var event = events[i];
  5780. if (event.ranges) {
  5781. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  5782. continue
  5783. }
  5784. var changes = event.changes, newChanges = [];
  5785. copy.push({changes: newChanges});
  5786. for (var j = 0; j < changes.length; ++j) {
  5787. var change = changes[j], m = (void 0);
  5788. newChanges.push({from: change.from, to: change.to, text: change.text});
  5789. if (newGroup) {
  5790. for (var prop in change) {
  5791. if (m = prop.match(/^spans_(\d+)$/)) {
  5792. if (indexOf(newGroup, Number(m[1])) > -1) {
  5793. lst(newChanges)[prop] = change[prop];
  5794. delete change[prop];
  5795. }
  5796. }
  5797. }
  5798. }
  5799. }
  5800. }
  5801. return copy
  5802. }
  5803. // The 'scroll' parameter given to many of these indicated whether
  5804. // the new cursor position should be scrolled into view after
  5805. // modifying the selection.
  5806. // If shift is held or the extend flag is set, extends a range to
  5807. // include a given position (and optionally a second position).
  5808. // Otherwise, simply returns the range between the given positions.
  5809. // Used for cursor motion and such.
  5810. function extendRange(range, head, other, extend) {
  5811. if (extend) {
  5812. var anchor = range.anchor;
  5813. if (other) {
  5814. var posBefore = cmp(head, anchor) < 0;
  5815. if (posBefore != (cmp(other, anchor) < 0)) {
  5816. anchor = head;
  5817. head = other;
  5818. } else if (posBefore != (cmp(head, other) < 0)) {
  5819. head = other;
  5820. }
  5821. }
  5822. return new Range(anchor, head)
  5823. } else {
  5824. return new Range(other || head, head)
  5825. }
  5826. }
  5827. // Extend the primary selection range, discard the rest.
  5828. function extendSelection(doc, head, other, options, extend) {
  5829. if (extend == null) {
  5830. extend = doc.cm && (doc.cm.display.shift || doc.extend);
  5831. }
  5832. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  5833. }
  5834. // Extend all selections (pos is an array of selections with length
  5835. // equal the number of selections)
  5836. function extendSelections(doc, heads, options) {
  5837. var out = [];
  5838. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  5839. for (var i = 0; i < doc.sel.ranges.length; i++) {
  5840. out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend);
  5841. }
  5842. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  5843. setSelection(doc, newSel, options);
  5844. }
  5845. // Updates a single range in the selection.
  5846. function replaceOneSelection(doc, i, range, options) {
  5847. var ranges = doc.sel.ranges.slice(0);
  5848. ranges[i] = range;
  5849. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  5850. }
  5851. // Reset the selection to a single range.
  5852. function setSimpleSelection(doc, anchor, head, options) {
  5853. setSelection(doc, simpleSelection(anchor, head), options);
  5854. }
  5855. // Give beforeSelectionChange handlers a change to influence a
  5856. // selection update.
  5857. function filterSelectionChange(doc, sel, options) {
  5858. var obj = {
  5859. ranges: sel.ranges,
  5860. update: function (ranges) {
  5861. this.ranges = [];
  5862. for (var i = 0; i < ranges.length; i++) {
  5863. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  5864. clipPos(doc, ranges[i].head));
  5865. }
  5866. },
  5867. origin: options && options.origin
  5868. };
  5869. signal(doc, "beforeSelectionChange", doc, obj);
  5870. if (doc.cm) {
  5871. signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  5872. }
  5873. if (obj.ranges != sel.ranges) {
  5874. return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1)
  5875. } else {
  5876. return sel
  5877. }
  5878. }
  5879. function setSelectionReplaceHistory(doc, sel, options) {
  5880. var done = doc.history.done, last = lst(done);
  5881. if (last && last.ranges) {
  5882. done[done.length - 1] = sel;
  5883. setSelectionNoUndo(doc, sel, options);
  5884. } else {
  5885. setSelection(doc, sel, options);
  5886. }
  5887. }
  5888. // Set a new selection.
  5889. function setSelection(doc, sel, options) {
  5890. setSelectionNoUndo(doc, sel, options);
  5891. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  5892. }
  5893. function setSelectionNoUndo(doc, sel, options) {
  5894. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
  5895. sel = filterSelectionChange(doc, sel, options);
  5896. }
  5897. var bias = options && options.bias ||
  5898. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  5899. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  5900. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") {
  5901. ensureCursorVisible(doc.cm);
  5902. }
  5903. }
  5904. function setSelectionInner(doc, sel) {
  5905. if (sel.equals(doc.sel)) {
  5906. return
  5907. }
  5908. doc.sel = sel;
  5909. if (doc.cm) {
  5910. doc.cm.curOp.updateInput = 1;
  5911. doc.cm.curOp.selectionChanged = true;
  5912. signalCursorActivity(doc.cm);
  5913. }
  5914. signalLater(doc, "cursorActivity", doc);
  5915. }
  5916. // Verify that the selection does not partially select any atomic
  5917. // marked ranges.
  5918. function reCheckSelection(doc) {
  5919. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  5920. }
  5921. // Return a selection that does not partially select any atomic
  5922. // ranges.
  5923. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  5924. var out;
  5925. for (var i = 0; i < sel.ranges.length; i++) {
  5926. var range = sel.ranges[i];
  5927. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  5928. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  5929. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  5930. if (out || newAnchor != range.anchor || newHead != range.head) {
  5931. if (!out) {
  5932. out = sel.ranges.slice(0, i);
  5933. }
  5934. out[i] = new Range(newAnchor, newHead);
  5935. }
  5936. }
  5937. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  5938. }
  5939. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  5940. var line = getLine(doc, pos.line);
  5941. if (line.markedSpans) {
  5942. for (var i = 0; i < line.markedSpans.length; ++i) {
  5943. var sp = line.markedSpans[i], m = sp.marker;
  5944. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  5945. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  5946. // is with selectLeft/Right
  5947. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  5948. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  5949. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  5950. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  5951. if (mayClear) {
  5952. signal(m, "beforeCursorEnter");
  5953. if (m.explicitlyCleared) {
  5954. if (!line.markedSpans) {
  5955. break
  5956. } else {
  5957. --i;
  5958. continue
  5959. }
  5960. }
  5961. }
  5962. if (!m.atomic) {
  5963. continue
  5964. }
  5965. if (oldPos) {
  5966. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  5967. if (dir < 0 ? preventCursorRight : preventCursorLeft) {
  5968. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
  5969. }
  5970. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) {
  5971. return skipAtomicInner(doc, near, pos, dir, mayClear)
  5972. }
  5973. }
  5974. var far = m.find(dir < 0 ? -1 : 1);
  5975. if (dir < 0 ? preventCursorLeft : preventCursorRight) {
  5976. far = movePos(doc, far, dir, far.line == pos.line ? line : null);
  5977. }
  5978. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  5979. }
  5980. }
  5981. }
  5982. return pos
  5983. }
  5984. // Ensure a given position is not inside an atomic range.
  5985. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  5986. var dir = bias || 1;
  5987. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  5988. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  5989. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  5990. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  5991. if (!found) {
  5992. doc.cantEdit = true;
  5993. return Pos(doc.first, 0)
  5994. }
  5995. return found
  5996. }
  5997. function movePos(doc, pos, dir, line) {
  5998. if (dir < 0 && pos.ch == 0) {
  5999. if (pos.line > doc.first) {
  6000. return clipPos(doc, Pos(pos.line - 1))
  6001. } else {
  6002. return null
  6003. }
  6004. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  6005. if (pos.line < doc.first + doc.size - 1) {
  6006. return Pos(pos.line + 1, 0)
  6007. } else {
  6008. return null
  6009. }
  6010. } else {
  6011. return new Pos(pos.line, pos.ch + dir)
  6012. }
  6013. }
  6014. function selectAll(cm) {
  6015. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  6016. }
  6017. // UPDATING
  6018. // Allow "beforeChange" event handlers to influence a change
  6019. function filterChange(doc, change, update) {
  6020. var obj = {
  6021. canceled: false,
  6022. from: change.from,
  6023. to: change.to,
  6024. text: change.text,
  6025. origin: change.origin,
  6026. cancel: function () {
  6027. return obj.canceled = true;
  6028. }
  6029. };
  6030. if (update) {
  6031. obj.update = function (from, to, text, origin) {
  6032. if (from) {
  6033. obj.from = clipPos(doc, from);
  6034. }
  6035. if (to) {
  6036. obj.to = clipPos(doc, to);
  6037. }
  6038. if (text) {
  6039. obj.text = text;
  6040. }
  6041. if (origin !== undefined) {
  6042. obj.origin = origin;
  6043. }
  6044. };
  6045. }
  6046. signal(doc, "beforeChange", doc, obj);
  6047. if (doc.cm) {
  6048. signal(doc.cm, "beforeChange", doc.cm, obj);
  6049. }
  6050. if (obj.canceled) {
  6051. if (doc.cm) {
  6052. doc.cm.curOp.updateInput = 2;
  6053. }
  6054. return null
  6055. }
  6056. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  6057. }
  6058. // Apply a change to a document, and add it to the document's
  6059. // history, and propagating it to all linked documents.
  6060. function makeChange(doc, change, ignoreReadOnly) {
  6061. if (doc.cm) {
  6062. if (!doc.cm.curOp) {
  6063. return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly)
  6064. }
  6065. if (doc.cm.state.suppressEdits) {
  6066. return
  6067. }
  6068. }
  6069. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  6070. change = filterChange(doc, change, true);
  6071. if (!change) {
  6072. return
  6073. }
  6074. }
  6075. // Possibly split or suppress the update based on the presence
  6076. // of read-only spans in its range.
  6077. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  6078. if (split) {
  6079. for (var i = split.length - 1; i >= 0; --i) {
  6080. makeChangeInner(doc, {
  6081. from: split[i].from,
  6082. to: split[i].to,
  6083. text: i ? [""] : change.text,
  6084. origin: change.origin
  6085. });
  6086. }
  6087. } else {
  6088. makeChangeInner(doc, change);
  6089. }
  6090. }
  6091. function makeChangeInner(doc, change) {
  6092. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) {
  6093. return
  6094. }
  6095. var selAfter = computeSelAfterChange(doc, change);
  6096. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  6097. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  6098. var rebased = [];
  6099. linkedDocs(doc, function (doc, sharedHist) {
  6100. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6101. rebaseHist(doc.history, change);
  6102. rebased.push(doc.history);
  6103. }
  6104. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  6105. });
  6106. }
  6107. // Revert a change stored in a document's history.
  6108. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  6109. var suppress = doc.cm && doc.cm.state.suppressEdits;
  6110. if (suppress && !allowSelectionOnly) {
  6111. return
  6112. }
  6113. var hist = doc.history, event, selAfter = doc.sel;
  6114. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  6115. // Verify that there is a useable event (so that ctrl-z won't
  6116. // needlessly clear selection events)
  6117. var i = 0;
  6118. for (; i < source.length; i++) {
  6119. event = source[i];
  6120. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) {
  6121. break
  6122. }
  6123. }
  6124. if (i == source.length) {
  6125. return
  6126. }
  6127. hist.lastOrigin = hist.lastSelOrigin = null;
  6128. for (; ;) {
  6129. event = source.pop();
  6130. if (event.ranges) {
  6131. pushSelectionToHistory(event, dest);
  6132. if (allowSelectionOnly && !event.equals(doc.sel)) {
  6133. setSelection(doc, event, {clearRedo: false});
  6134. return
  6135. }
  6136. selAfter = event;
  6137. } else if (suppress) {
  6138. source.push(event);
  6139. return
  6140. } else {
  6141. break
  6142. }
  6143. }
  6144. // Build up a reverse change object to add to the opposite history
  6145. // stack (redo when undoing, and vice versa).
  6146. var antiChanges = [];
  6147. pushSelectionToHistory(selAfter, dest);
  6148. dest.push({changes: antiChanges, generation: hist.generation});
  6149. hist.generation = event.generation || ++hist.maxGeneration;
  6150. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  6151. var loop = function (i) {
  6152. var change = event.changes[i];
  6153. change.origin = type;
  6154. if (filter && !filterChange(doc, change, false)) {
  6155. source.length = 0;
  6156. return {}
  6157. }
  6158. antiChanges.push(historyChangeFromChange(doc, change));
  6159. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  6160. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  6161. if (!i && doc.cm) {
  6162. doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  6163. }
  6164. var rebased = [];
  6165. // Propagate to the linked documents
  6166. linkedDocs(doc, function (doc, sharedHist) {
  6167. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6168. rebaseHist(doc.history, change);
  6169. rebased.push(doc.history);
  6170. }
  6171. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  6172. });
  6173. };
  6174. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  6175. var returned = loop(i$1);
  6176. if (returned) return returned.v;
  6177. }
  6178. }
  6179. // Sub-views need their line numbers shifted when text is added
  6180. // above or below them in the parent document.
  6181. function shiftDoc(doc, distance) {
  6182. if (distance == 0) {
  6183. return
  6184. }
  6185. doc.first += distance;
  6186. doc.sel = new Selection(map(doc.sel.ranges, function (range) {
  6187. return new Range(
  6188. Pos(range.anchor.line + distance, range.anchor.ch),
  6189. Pos(range.head.line + distance, range.head.ch)
  6190. );
  6191. }), doc.sel.primIndex);
  6192. if (doc.cm) {
  6193. regChange(doc.cm, doc.first, doc.first - distance, distance);
  6194. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) {
  6195. regLineChange(doc.cm, l, "gutter");
  6196. }
  6197. }
  6198. }
  6199. // More lower-level change function, handling only a single document
  6200. // (not linked ones).
  6201. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  6202. if (doc.cm && !doc.cm.curOp) {
  6203. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans)
  6204. }
  6205. if (change.to.line < doc.first) {
  6206. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  6207. return
  6208. }
  6209. if (change.from.line > doc.lastLine()) {
  6210. return
  6211. }
  6212. // Clip the change to the size of this doc
  6213. if (change.from.line < doc.first) {
  6214. var shift = change.text.length - 1 - (doc.first - change.from.line);
  6215. shiftDoc(doc, shift);
  6216. change = {
  6217. from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  6218. text: [lst(change.text)], origin: change.origin
  6219. };
  6220. }
  6221. var last = doc.lastLine();
  6222. if (change.to.line > last) {
  6223. change = {
  6224. from: change.from, to: Pos(last, getLine(doc, last).text.length),
  6225. text: [change.text[0]], origin: change.origin
  6226. };
  6227. }
  6228. change.removed = getBetween(doc, change.from, change.to);
  6229. if (!selAfter) {
  6230. selAfter = computeSelAfterChange(doc, change);
  6231. }
  6232. if (doc.cm) {
  6233. makeChangeSingleDocInEditor(doc.cm, change, spans);
  6234. } else {
  6235. updateDoc(doc, change, spans);
  6236. }
  6237. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  6238. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) {
  6239. doc.cantEdit = false;
  6240. }
  6241. }
  6242. // Handle the interaction of a change to a document with the editor
  6243. // that this document is part of.
  6244. function makeChangeSingleDocInEditor(cm, change, spans) {
  6245. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  6246. var recomputeMaxLength = false, checkWidthStart = from.line;
  6247. if (!cm.options.lineWrapping) {
  6248. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  6249. doc.iter(checkWidthStart, to.line + 1, function (line) {
  6250. if (line == display.maxLine) {
  6251. recomputeMaxLength = true;
  6252. return true
  6253. }
  6254. });
  6255. }
  6256. if (doc.sel.contains(change.from, change.to) > -1) {
  6257. signalCursorActivity(cm);
  6258. }
  6259. updateDoc(doc, change, spans, estimateHeight(cm));
  6260. if (!cm.options.lineWrapping) {
  6261. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  6262. var len = lineLength(line);
  6263. if (len > display.maxLineLength) {
  6264. display.maxLine = line;
  6265. display.maxLineLength = len;
  6266. display.maxLineChanged = true;
  6267. recomputeMaxLength = false;
  6268. }
  6269. });
  6270. if (recomputeMaxLength) {
  6271. cm.curOp.updateMaxLine = true;
  6272. }
  6273. }
  6274. retreatFrontier(doc, from.line);
  6275. startWorker(cm, 400);
  6276. var lendiff = change.text.length - (to.line - from.line) - 1;
  6277. // Remember that these lines changed, for updating the display
  6278. if (change.full) {
  6279. regChange(cm);
  6280. } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {
  6281. regLineChange(cm, from.line, "text");
  6282. } else {
  6283. regChange(cm, from.line, to.line + 1, lendiff);
  6284. }
  6285. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  6286. if (changeHandler || changesHandler) {
  6287. var obj = {
  6288. from: from, to: to,
  6289. text: change.text,
  6290. removed: change.removed,
  6291. origin: change.origin
  6292. };
  6293. if (changeHandler) {
  6294. signalLater(cm, "change", cm, obj);
  6295. }
  6296. if (changesHandler) {
  6297. (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  6298. }
  6299. }
  6300. cm.display.selForContextMenu = null;
  6301. }
  6302. function replaceRange(doc, code, from, to, origin) {
  6303. var assign;
  6304. if (!to) {
  6305. to = from;
  6306. }
  6307. if (cmp(to, from) < 0) {
  6308. (assign = [to, from], from = assign[0], to = assign[1]);
  6309. }
  6310. if (typeof code == "string") {
  6311. code = doc.splitLines(code);
  6312. }
  6313. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  6314. }
  6315. // Rebasing/resetting history to deal with externally-sourced changes
  6316. function rebaseHistSelSingle(pos, from, to, diff) {
  6317. if (to < pos.line) {
  6318. pos.line += diff;
  6319. } else if (from < pos.line) {
  6320. pos.line = from;
  6321. pos.ch = 0;
  6322. }
  6323. }
  6324. // Tries to rebase an array of history events given a change in the
  6325. // document. If the change touches the same lines as the event, the
  6326. // event, and everything 'behind' it, is discarded. If the change is
  6327. // before the event, the event's positions are updated. Uses a
  6328. // copy-on-write scheme for the positions, to avoid having to
  6329. // reallocate them all on every rebase, but also avoid problems with
  6330. // shared position objects being unsafely updated.
  6331. function rebaseHistArray(array, from, to, diff) {
  6332. for (var i = 0; i < array.length; ++i) {
  6333. var sub = array[i], ok = true;
  6334. if (sub.ranges) {
  6335. if (!sub.copied) {
  6336. sub = array[i] = sub.deepCopy();
  6337. sub.copied = true;
  6338. }
  6339. for (var j = 0; j < sub.ranges.length; j++) {
  6340. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  6341. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  6342. }
  6343. continue
  6344. }
  6345. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  6346. var cur = sub.changes[j$1];
  6347. if (to < cur.from.line) {
  6348. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  6349. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  6350. } else if (from <= cur.to.line) {
  6351. ok = false;
  6352. break
  6353. }
  6354. }
  6355. if (!ok) {
  6356. array.splice(0, i + 1);
  6357. i = 0;
  6358. }
  6359. }
  6360. }
  6361. function rebaseHist(hist, change) {
  6362. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  6363. rebaseHistArray(hist.done, from, to, diff);
  6364. rebaseHistArray(hist.undone, from, to, diff);
  6365. }
  6366. // Utility for applying a change to a line by handle or number,
  6367. // returning the number and optionally registering the line as
  6368. // changed.
  6369. function changeLine(doc, handle, changeType, op) {
  6370. var no = handle, line = handle;
  6371. if (typeof handle == "number") {
  6372. line = getLine(doc, clipLine(doc, handle));
  6373. } else {
  6374. no = lineNo(handle);
  6375. }
  6376. if (no == null) {
  6377. return null
  6378. }
  6379. if (op(line, no) && doc.cm) {
  6380. regLineChange(doc.cm, no, changeType);
  6381. }
  6382. return line
  6383. }
  6384. // The document is represented as a BTree consisting of leaves, with
  6385. // chunk of lines in them, and branches, with up to ten leaves or
  6386. // other branch nodes below them. The top node is always a branch
  6387. // node, and is the document object itself (meaning it has
  6388. // additional methods and properties).
  6389. //
  6390. // All nodes have parent links. The tree is used both to go from
  6391. // line numbers to line objects, and to go from objects to numbers.
  6392. // It also indexes by height, and is used to convert between height
  6393. // and line object, and to find the total height of the document.
  6394. //
  6395. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6396. function LeafChunk(lines) {
  6397. this.lines = lines;
  6398. this.parent = null;
  6399. var height = 0;
  6400. for (var i = 0; i < lines.length; ++i) {
  6401. lines[i].parent = this;
  6402. height += lines[i].height;
  6403. }
  6404. this.height = height;
  6405. }
  6406. LeafChunk.prototype = {
  6407. chunkSize: function () {
  6408. return this.lines.length
  6409. },
  6410. // Remove the n lines at offset 'at'.
  6411. removeInner: function (at, n) {
  6412. for (var i = at, e = at + n; i < e; ++i) {
  6413. var line = this.lines[i];
  6414. this.height -= line.height;
  6415. cleanUpLine(line);
  6416. signalLater(line, "delete");
  6417. }
  6418. this.lines.splice(at, n);
  6419. },
  6420. // Helper used to collapse a small branch into a single leaf.
  6421. collapse: function (lines) {
  6422. lines.push.apply(lines, this.lines);
  6423. },
  6424. // Insert the given array of lines at offset 'at', count them as
  6425. // having the given height.
  6426. insertInner: function (at, lines, height) {
  6427. this.height += height;
  6428. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6429. for (var i = 0; i < lines.length; ++i) {
  6430. lines[i].parent = this;
  6431. }
  6432. },
  6433. // Used to iterate over a part of the tree.
  6434. iterN: function (at, n, op) {
  6435. for (var e = at + n; at < e; ++at) {
  6436. if (op(this.lines[at])) {
  6437. return true
  6438. }
  6439. }
  6440. }
  6441. };
  6442. function BranchChunk(children) {
  6443. this.children = children;
  6444. var size = 0, height = 0;
  6445. for (var i = 0; i < children.length; ++i) {
  6446. var ch = children[i];
  6447. size += ch.chunkSize();
  6448. height += ch.height;
  6449. ch.parent = this;
  6450. }
  6451. this.size = size;
  6452. this.height = height;
  6453. this.parent = null;
  6454. }
  6455. BranchChunk.prototype = {
  6456. chunkSize: function () {
  6457. return this.size
  6458. },
  6459. removeInner: function (at, n) {
  6460. this.size -= n;
  6461. for (var i = 0; i < this.children.length; ++i) {
  6462. var child = this.children[i], sz = child.chunkSize();
  6463. if (at < sz) {
  6464. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6465. child.removeInner(at, rm);
  6466. this.height -= oldHeight - child.height;
  6467. if (sz == rm) {
  6468. this.children.splice(i--, 1);
  6469. child.parent = null;
  6470. }
  6471. if ((n -= rm) == 0) {
  6472. break
  6473. }
  6474. at = 0;
  6475. } else {
  6476. at -= sz;
  6477. }
  6478. }
  6479. // If the result is smaller than 25 lines, ensure that it is a
  6480. // single leaf node.
  6481. if (this.size - n < 25 &&
  6482. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6483. var lines = [];
  6484. this.collapse(lines);
  6485. this.children = [new LeafChunk(lines)];
  6486. this.children[0].parent = this;
  6487. }
  6488. },
  6489. collapse: function (lines) {
  6490. for (var i = 0; i < this.children.length; ++i) {
  6491. this.children[i].collapse(lines);
  6492. }
  6493. },
  6494. insertInner: function (at, lines, height) {
  6495. this.size += lines.length;
  6496. this.height += height;
  6497. for (var i = 0; i < this.children.length; ++i) {
  6498. var child = this.children[i], sz = child.chunkSize();
  6499. if (at <= sz) {
  6500. child.insertInner(at, lines, height);
  6501. if (child.lines && child.lines.length > 50) {
  6502. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  6503. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  6504. var remaining = child.lines.length % 25 + 25;
  6505. for (var pos = remaining; pos < child.lines.length;) {
  6506. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  6507. child.height -= leaf.height;
  6508. this.children.splice(++i, 0, leaf);
  6509. leaf.parent = this;
  6510. }
  6511. child.lines = child.lines.slice(0, remaining);
  6512. this.maybeSpill();
  6513. }
  6514. break
  6515. }
  6516. at -= sz;
  6517. }
  6518. },
  6519. // When a node has grown, check whether it should be split.
  6520. maybeSpill: function () {
  6521. if (this.children.length <= 10) {
  6522. return
  6523. }
  6524. var me = this;
  6525. do {
  6526. var spilled = me.children.splice(me.children.length - 5, 5);
  6527. var sibling = new BranchChunk(spilled);
  6528. if (!me.parent) { // Become the parent node
  6529. var copy = new BranchChunk(me.children);
  6530. copy.parent = me;
  6531. me.children = [copy, sibling];
  6532. me = copy;
  6533. } else {
  6534. me.size -= sibling.size;
  6535. me.height -= sibling.height;
  6536. var myIndex = indexOf(me.parent.children, me);
  6537. me.parent.children.splice(myIndex + 1, 0, sibling);
  6538. }
  6539. sibling.parent = me.parent;
  6540. } while (me.children.length > 10)
  6541. me.parent.maybeSpill();
  6542. },
  6543. iterN: function (at, n, op) {
  6544. for (var i = 0; i < this.children.length; ++i) {
  6545. var child = this.children[i], sz = child.chunkSize();
  6546. if (at < sz) {
  6547. var used = Math.min(n, sz - at);
  6548. if (child.iterN(at, used, op)) {
  6549. return true
  6550. }
  6551. if ((n -= used) == 0) {
  6552. break
  6553. }
  6554. at = 0;
  6555. } else {
  6556. at -= sz;
  6557. }
  6558. }
  6559. }
  6560. };
  6561. // Line widgets are block elements displayed above or below a line.
  6562. var LineWidget = function (doc, node, options) {
  6563. if (options) {
  6564. for (var opt in options) {
  6565. if (options.hasOwnProperty(opt)) {
  6566. this[opt] = options[opt];
  6567. }
  6568. }
  6569. }
  6570. this.doc = doc;
  6571. this.node = node;
  6572. };
  6573. LineWidget.prototype.clear = function () {
  6574. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  6575. if (no == null || !ws) {
  6576. return
  6577. }
  6578. for (var i = 0; i < ws.length; ++i) {
  6579. if (ws[i] == this) {
  6580. ws.splice(i--, 1);
  6581. }
  6582. }
  6583. if (!ws.length) {
  6584. line.widgets = null;
  6585. }
  6586. var height = widgetHeight(this);
  6587. updateLineHeight(line, Math.max(0, line.height - height));
  6588. if (cm) {
  6589. runInOp(cm, function () {
  6590. adjustScrollWhenAboveVisible(cm, line, -height);
  6591. regLineChange(cm, no, "widget");
  6592. });
  6593. signalLater(cm, "lineWidgetCleared", cm, this, no);
  6594. }
  6595. };
  6596. LineWidget.prototype.changed = function () {
  6597. var this$1 = this;
  6598. var oldH = this.height, cm = this.doc.cm, line = this.line;
  6599. this.height = null;
  6600. var diff = widgetHeight(this) - oldH;
  6601. if (!diff) {
  6602. return
  6603. }
  6604. if (!lineIsHidden(this.doc, line)) {
  6605. updateLineHeight(line, line.height + diff);
  6606. }
  6607. if (cm) {
  6608. runInOp(cm, function () {
  6609. cm.curOp.forceUpdate = true;
  6610. adjustScrollWhenAboveVisible(cm, line, diff);
  6611. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  6612. });
  6613. }
  6614. };
  6615. eventMixin(LineWidget);
  6616. function adjustScrollWhenAboveVisible(cm, line, diff) {
  6617. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) {
  6618. addToScrollTop(cm, diff);
  6619. }
  6620. }
  6621. function addLineWidget(doc, handle, node, options) {
  6622. var widget = new LineWidget(doc, node, options);
  6623. var cm = doc.cm;
  6624. if (cm && widget.noHScroll) {
  6625. cm.display.alignWidgets = true;
  6626. }
  6627. changeLine(doc, handle, "widget", function (line) {
  6628. var widgets = line.widgets || (line.widgets = []);
  6629. if (widget.insertAt == null) {
  6630. widgets.push(widget);
  6631. } else {
  6632. widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget);
  6633. }
  6634. widget.line = line;
  6635. if (cm && !lineIsHidden(doc, line)) {
  6636. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  6637. updateLineHeight(line, line.height + widgetHeight(widget));
  6638. if (aboveVisible) {
  6639. addToScrollTop(cm, widget.height);
  6640. }
  6641. cm.curOp.forceUpdate = true;
  6642. }
  6643. return true
  6644. });
  6645. if (cm) {
  6646. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
  6647. }
  6648. return widget
  6649. }
  6650. // TEXTMARKERS
  6651. // Created with markText and setBookmark methods. A TextMarker is a
  6652. // handle that can be used to clear or find a marked position in the
  6653. // document. Line objects hold arrays (markedSpans) containing
  6654. // {from, to, marker} object pointing to such marker objects, and
  6655. // indicating that such a marker is present on that line. Multiple
  6656. // lines may point to the same marker when it spans across lines.
  6657. // The spans will have null for their from/to properties when the
  6658. // marker continues beyond the start/end of the line. Markers have
  6659. // links back to the lines they currently touch.
  6660. // Collapsed markers have unique ids, in order to be able to order
  6661. // them, which is needed for uniquely determining an outer marker
  6662. // when they overlap (they may nest, but not partially overlap).
  6663. var nextMarkerId = 0;
  6664. var TextMarker = function (doc, type) {
  6665. this.lines = [];
  6666. this.type = type;
  6667. this.doc = doc;
  6668. this.id = ++nextMarkerId;
  6669. };
  6670. // Clear the marker.
  6671. TextMarker.prototype.clear = function () {
  6672. if (this.explicitlyCleared) {
  6673. return
  6674. }
  6675. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  6676. if (withOp) {
  6677. startOperation(cm);
  6678. }
  6679. if (hasHandler(this, "clear")) {
  6680. var found = this.find();
  6681. if (found) {
  6682. signalLater(this, "clear", found.from, found.to);
  6683. }
  6684. }
  6685. var min = null, max = null;
  6686. for (var i = 0; i < this.lines.length; ++i) {
  6687. var line = this.lines[i];
  6688. var span = getMarkedSpanFor(line.markedSpans, this);
  6689. if (cm && !this.collapsed) {
  6690. regLineChange(cm, lineNo(line), "text");
  6691. } else if (cm) {
  6692. if (span.to != null) {
  6693. max = lineNo(line);
  6694. }
  6695. if (span.from != null) {
  6696. min = lineNo(line);
  6697. }
  6698. }
  6699. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  6700. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {
  6701. updateLineHeight(line, textHeight(cm.display));
  6702. }
  6703. }
  6704. if (cm && this.collapsed && !cm.options.lineWrapping) {
  6705. for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  6706. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  6707. if (len > cm.display.maxLineLength) {
  6708. cm.display.maxLine = visual;
  6709. cm.display.maxLineLength = len;
  6710. cm.display.maxLineChanged = true;
  6711. }
  6712. }
  6713. }
  6714. if (min != null && cm && this.collapsed) {
  6715. regChange(cm, min, max + 1);
  6716. }
  6717. this.lines.length = 0;
  6718. this.explicitlyCleared = true;
  6719. if (this.atomic && this.doc.cantEdit) {
  6720. this.doc.cantEdit = false;
  6721. if (cm) {
  6722. reCheckSelection(cm.doc);
  6723. }
  6724. }
  6725. if (cm) {
  6726. signalLater(cm, "markerCleared", cm, this, min, max);
  6727. }
  6728. if (withOp) {
  6729. endOperation(cm);
  6730. }
  6731. if (this.parent) {
  6732. this.parent.clear();
  6733. }
  6734. };
  6735. // Find the position of the marker in the document. Returns a {from,
  6736. // to} object by default. Side can be passed to get a specific side
  6737. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  6738. // Pos objects returned contain a line object, rather than a line
  6739. // number (used to prevent looking up the same line twice).
  6740. TextMarker.prototype.find = function (side, lineObj) {
  6741. if (side == null && this.type == "bookmark") {
  6742. side = 1;
  6743. }
  6744. var from, to;
  6745. for (var i = 0; i < this.lines.length; ++i) {
  6746. var line = this.lines[i];
  6747. var span = getMarkedSpanFor(line.markedSpans, this);
  6748. if (span.from != null) {
  6749. from = Pos(lineObj ? line : lineNo(line), span.from);
  6750. if (side == -1) {
  6751. return from
  6752. }
  6753. }
  6754. if (span.to != null) {
  6755. to = Pos(lineObj ? line : lineNo(line), span.to);
  6756. if (side == 1) {
  6757. return to
  6758. }
  6759. }
  6760. }
  6761. return from && {from: from, to: to}
  6762. };
  6763. // Signals that the marker's widget changed, and surrounding layout
  6764. // should be recomputed.
  6765. TextMarker.prototype.changed = function () {
  6766. var this$1 = this;
  6767. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  6768. if (!pos || !cm) {
  6769. return
  6770. }
  6771. runInOp(cm, function () {
  6772. var line = pos.line, lineN = lineNo(pos.line);
  6773. var view = findViewForLine(cm, lineN);
  6774. if (view) {
  6775. clearLineMeasurementCacheFor(view);
  6776. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  6777. }
  6778. cm.curOp.updateMaxLine = true;
  6779. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  6780. var oldHeight = widget.height;
  6781. widget.height = null;
  6782. var dHeight = widgetHeight(widget) - oldHeight;
  6783. if (dHeight) {
  6784. updateLineHeight(line, line.height + dHeight);
  6785. }
  6786. }
  6787. signalLater(cm, "markerChanged", cm, this$1);
  6788. });
  6789. };
  6790. TextMarker.prototype.attachLine = function (line) {
  6791. if (!this.lines.length && this.doc.cm) {
  6792. var op = this.doc.cm.curOp;
  6793. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {
  6794. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  6795. }
  6796. }
  6797. this.lines.push(line);
  6798. };
  6799. TextMarker.prototype.detachLine = function (line) {
  6800. this.lines.splice(indexOf(this.lines, line), 1);
  6801. if (!this.lines.length && this.doc.cm) {
  6802. var op = this.doc.cm.curOp
  6803. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  6804. }
  6805. };
  6806. eventMixin(TextMarker);
  6807. // Create a marker, wire it up to the right lines, and
  6808. function markText(doc, from, to, options, type) {
  6809. // Shared markers (across linked documents) are handled separately
  6810. // (markTextShared will call out to this again, once per
  6811. // document).
  6812. if (options && options.shared) {
  6813. return markTextShared(doc, from, to, options, type)
  6814. }
  6815. // Ensure we are in an operation.
  6816. if (doc.cm && !doc.cm.curOp) {
  6817. return operation(doc.cm, markText)(doc, from, to, options, type)
  6818. }
  6819. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  6820. if (options) {
  6821. copyObj(options, marker, false);
  6822. }
  6823. // Don't connect empty markers unless clearWhenEmpty is false
  6824. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) {
  6825. return marker
  6826. }
  6827. if (marker.replacedWith) {
  6828. // Showing up as a widget implies collapsed (widget replaces text)
  6829. marker.collapsed = true;
  6830. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  6831. if (!options.handleMouseEvents) {
  6832. marker.widgetNode.setAttribute("cm-ignore-events", "true");
  6833. }
  6834. if (options.insertLeft) {
  6835. marker.widgetNode.insertLeft = true;
  6836. }
  6837. }
  6838. if (marker.collapsed) {
  6839. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  6840. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) {
  6841. throw new Error("Inserting collapsed marker partially overlapping an existing one")
  6842. }
  6843. seeCollapsedSpans();
  6844. }
  6845. if (marker.addToHistory) {
  6846. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  6847. }
  6848. var curLine = from.line, cm = doc.cm, updateMaxLine;
  6849. doc.iter(curLine, to.line + 1, function (line) {
  6850. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {
  6851. updateMaxLine = true;
  6852. }
  6853. if (marker.collapsed && curLine != from.line) {
  6854. updateLineHeight(line, 0);
  6855. }
  6856. addMarkedSpan(line, new MarkedSpan(marker,
  6857. curLine == from.line ? from.ch : null,
  6858. curLine == to.line ? to.ch : null));
  6859. ++curLine;
  6860. });
  6861. // lineIsHidden depends on the presence of the spans, so needs a second pass
  6862. if (marker.collapsed) {
  6863. doc.iter(from.line, to.line + 1, function (line) {
  6864. if (lineIsHidden(doc, line)) {
  6865. updateLineHeight(line, 0);
  6866. }
  6867. });
  6868. }
  6869. if (marker.clearOnEnter) {
  6870. on(marker, "beforeCursorEnter", function () {
  6871. return marker.clear();
  6872. });
  6873. }
  6874. if (marker.readOnly) {
  6875. seeReadOnlySpans();
  6876. if (doc.history.done.length || doc.history.undone.length) {
  6877. doc.clearHistory();
  6878. }
  6879. }
  6880. if (marker.collapsed) {
  6881. marker.id = ++nextMarkerId;
  6882. marker.atomic = true;
  6883. }
  6884. if (cm) {
  6885. // Sync editor state
  6886. if (updateMaxLine) {
  6887. cm.curOp.updateMaxLine = true;
  6888. }
  6889. if (marker.collapsed) {
  6890. regChange(cm, from.line, to.line + 1);
  6891. } else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  6892. marker.attributes || marker.title) {
  6893. for (var i = from.line; i <= to.line; i++) {
  6894. regLineChange(cm, i, "text");
  6895. }
  6896. }
  6897. if (marker.atomic) {
  6898. reCheckSelection(cm.doc);
  6899. }
  6900. signalLater(cm, "markerAdded", cm, marker);
  6901. }
  6902. return marker
  6903. }
  6904. // SHARED TEXTMARKERS
  6905. // A shared marker spans multiple linked documents. It is
  6906. // implemented as a meta-marker-object controlling multiple normal
  6907. // markers.
  6908. var SharedTextMarker = function (markers, primary) {
  6909. this.markers = markers;
  6910. this.primary = primary;
  6911. for (var i = 0; i < markers.length; ++i) {
  6912. markers[i].parent = this;
  6913. }
  6914. };
  6915. SharedTextMarker.prototype.clear = function () {
  6916. if (this.explicitlyCleared) {
  6917. return
  6918. }
  6919. this.explicitlyCleared = true;
  6920. for (var i = 0; i < this.markers.length; ++i) {
  6921. this.markers[i].clear();
  6922. }
  6923. signalLater(this, "clear");
  6924. };
  6925. SharedTextMarker.prototype.find = function (side, lineObj) {
  6926. return this.primary.find(side, lineObj)
  6927. };
  6928. eventMixin(SharedTextMarker);
  6929. function markTextShared(doc, from, to, options, type) {
  6930. options = copyObj(options);
  6931. options.shared = false;
  6932. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  6933. var widget = options.widgetNode;
  6934. linkedDocs(doc, function (doc) {
  6935. if (widget) {
  6936. options.widgetNode = widget.cloneNode(true);
  6937. }
  6938. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  6939. for (var i = 0; i < doc.linked.length; ++i) {
  6940. if (doc.linked[i].isParent) {
  6941. return
  6942. }
  6943. }
  6944. primary = lst(markers);
  6945. });
  6946. return new SharedTextMarker(markers, primary)
  6947. }
  6948. function findSharedMarkers(doc) {
  6949. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) {
  6950. return m.parent;
  6951. })
  6952. }
  6953. function copySharedMarkers(doc, markers) {
  6954. for (var i = 0; i < markers.length; i++) {
  6955. var marker = markers[i], pos = marker.find();
  6956. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  6957. if (cmp(mFrom, mTo)) {
  6958. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  6959. marker.markers.push(subMark);
  6960. subMark.parent = marker;
  6961. }
  6962. }
  6963. }
  6964. function detachSharedMarkers(markers) {
  6965. var loop = function (i) {
  6966. var marker = markers[i], linked = [marker.primary.doc];
  6967. linkedDocs(marker.primary.doc, function (d) {
  6968. return linked.push(d);
  6969. });
  6970. for (var j = 0; j < marker.markers.length; j++) {
  6971. var subMarker = marker.markers[j];
  6972. if (indexOf(linked, subMarker.doc) == -1) {
  6973. subMarker.parent = null;
  6974. marker.markers.splice(j--, 1);
  6975. }
  6976. }
  6977. };
  6978. for (var i = 0; i < markers.length; i++) loop(i);
  6979. }
  6980. var nextDocId = 0;
  6981. var Doc = function (text, mode, firstLine, lineSep, direction) {
  6982. if (!(this instanceof Doc)) {
  6983. return new Doc(text, mode, firstLine, lineSep, direction)
  6984. }
  6985. if (firstLine == null) {
  6986. firstLine = 0;
  6987. }
  6988. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6989. this.first = firstLine;
  6990. this.scrollTop = this.scrollLeft = 0;
  6991. this.cantEdit = false;
  6992. this.cleanGeneration = 1;
  6993. this.modeFrontier = this.highlightFrontier = firstLine;
  6994. var start = Pos(firstLine, 0);
  6995. this.sel = simpleSelection(start);
  6996. this.history = new History(null);
  6997. this.id = ++nextDocId;
  6998. this.modeOption = mode;
  6999. this.lineSep = lineSep;
  7000. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  7001. this.extend = false;
  7002. if (typeof text == "string") {
  7003. text = this.splitLines(text);
  7004. }
  7005. updateDoc(this, {from: start, to: start, text: text});
  7006. setSelection(this, simpleSelection(start), sel_dontScroll);
  7007. };
  7008. Doc.prototype = createObj(BranchChunk.prototype, {
  7009. constructor: Doc,
  7010. // Iterate over the document. Supports two forms -- with only one
  7011. // argument, it calls that for each line in the document. With
  7012. // three, it iterates over the range given by the first two (with
  7013. // the second being non-inclusive).
  7014. iter: function (from, to, op) {
  7015. if (op) {
  7016. this.iterN(from - this.first, to - from, op);
  7017. } else {
  7018. this.iterN(this.first, this.first + this.size, from);
  7019. }
  7020. },
  7021. // Non-public interface for adding and removing lines.
  7022. insert: function (at, lines) {
  7023. var height = 0;
  7024. for (var i = 0; i < lines.length; ++i) {
  7025. height += lines[i].height;
  7026. }
  7027. this.insertInner(at - this.first, lines, height);
  7028. },
  7029. remove: function (at, n) {
  7030. this.removeInner(at - this.first, n);
  7031. },
  7032. // From here, the methods are part of the public interface. Most
  7033. // are also available from CodeMirror (editor) instances.
  7034. getValue: function (lineSep) {
  7035. var lines = getLines(this, this.first, this.first + this.size);
  7036. if (lineSep === false) {
  7037. return lines
  7038. }
  7039. return lines.join(lineSep || this.lineSeparator())
  7040. },
  7041. setValue: docMethodOp(function (code) {
  7042. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  7043. makeChange(this, {
  7044. from: top, to: Pos(last, getLine(this, last).text.length),
  7045. text: this.splitLines(code), origin: "setValue", full: true
  7046. }, true);
  7047. if (this.cm) {
  7048. scrollToCoords(this.cm, 0, 0);
  7049. }
  7050. setSelection(this, simpleSelection(top), sel_dontScroll);
  7051. }),
  7052. replaceRange: function (code, from, to, origin) {
  7053. from = clipPos(this, from);
  7054. to = to ? clipPos(this, to) : from;
  7055. replaceRange(this, code, from, to, origin);
  7056. },
  7057. getRange: function (from, to, lineSep) {
  7058. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  7059. if (lineSep === false) {
  7060. return lines
  7061. }
  7062. return lines.join(lineSep || this.lineSeparator())
  7063. },
  7064. getLine: function (line) {
  7065. var l = this.getLineHandle(line);
  7066. return l && l.text
  7067. },
  7068. getLineHandle: function (line) {
  7069. if (isLine(this, line)) {
  7070. return getLine(this, line)
  7071. }
  7072. },
  7073. getLineNumber: function (line) {
  7074. return lineNo(line)
  7075. },
  7076. getLineHandleVisualStart: function (line) {
  7077. if (typeof line == "number") {
  7078. line = getLine(this, line);
  7079. }
  7080. return visualLine(line)
  7081. },
  7082. lineCount: function () {
  7083. return this.size
  7084. },
  7085. firstLine: function () {
  7086. return this.first
  7087. },
  7088. lastLine: function () {
  7089. return this.first + this.size - 1
  7090. },
  7091. clipPos: function (pos) {
  7092. return clipPos(this, pos)
  7093. },
  7094. getCursor: function (start) {
  7095. var range = this.sel.primary(), pos;
  7096. if (start == null || start == "head") {
  7097. pos = range.head;
  7098. } else if (start == "anchor") {
  7099. pos = range.anchor;
  7100. } else if (start == "end" || start == "to" || start === false) {
  7101. pos = range.to();
  7102. } else {
  7103. pos = range.from();
  7104. }
  7105. return pos
  7106. },
  7107. listSelections: function () {
  7108. return this.sel.ranges
  7109. },
  7110. somethingSelected: function () {
  7111. return this.sel.somethingSelected()
  7112. },
  7113. setCursor: docMethodOp(function (line, ch, options) {
  7114. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  7115. }),
  7116. setSelection: docMethodOp(function (anchor, head, options) {
  7117. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  7118. }),
  7119. extendSelection: docMethodOp(function (head, other, options) {
  7120. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  7121. }),
  7122. extendSelections: docMethodOp(function (heads, options) {
  7123. extendSelections(this, clipPosArray(this, heads), options);
  7124. }),
  7125. extendSelectionsBy: docMethodOp(function (f, options) {
  7126. var heads = map(this.sel.ranges, f);
  7127. extendSelections(this, clipPosArray(this, heads), options);
  7128. }),
  7129. setSelections: docMethodOp(function (ranges, primary, options) {
  7130. if (!ranges.length) {
  7131. return
  7132. }
  7133. var out = [];
  7134. for (var i = 0; i < ranges.length; i++) {
  7135. out[i] = new Range(clipPos(this, ranges[i].anchor),
  7136. clipPos(this, ranges[i].head || ranges[i].anchor));
  7137. }
  7138. if (primary == null) {
  7139. primary = Math.min(ranges.length - 1, this.sel.primIndex);
  7140. }
  7141. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  7142. }),
  7143. addSelection: docMethodOp(function (anchor, head, options) {
  7144. var ranges = this.sel.ranges.slice(0);
  7145. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  7146. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  7147. }),
  7148. getSelection: function (lineSep) {
  7149. var ranges = this.sel.ranges, lines;
  7150. for (var i = 0; i < ranges.length; i++) {
  7151. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  7152. lines = lines ? lines.concat(sel) : sel;
  7153. }
  7154. if (lineSep === false) {
  7155. return lines
  7156. } else {
  7157. return lines.join(lineSep || this.lineSeparator())
  7158. }
  7159. },
  7160. getSelections: function (lineSep) {
  7161. var parts = [], ranges = this.sel.ranges;
  7162. for (var i = 0; i < ranges.length; i++) {
  7163. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  7164. if (lineSep !== false) {
  7165. sel = sel.join(lineSep || this.lineSeparator());
  7166. }
  7167. parts[i] = sel;
  7168. }
  7169. return parts
  7170. },
  7171. replaceSelection: function (code, collapse, origin) {
  7172. var dup = [];
  7173. for (var i = 0; i < this.sel.ranges.length; i++) {
  7174. dup[i] = code;
  7175. }
  7176. this.replaceSelections(dup, collapse, origin || "+input");
  7177. },
  7178. replaceSelections: docMethodOp(function (code, collapse, origin) {
  7179. var changes = [], sel = this.sel;
  7180. for (var i = 0; i < sel.ranges.length; i++) {
  7181. var range = sel.ranges[i];
  7182. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  7183. }
  7184. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  7185. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) {
  7186. makeChange(this, changes[i$1]);
  7187. }
  7188. if (newSel) {
  7189. setSelectionReplaceHistory(this, newSel);
  7190. } else if (this.cm) {
  7191. ensureCursorVisible(this.cm);
  7192. }
  7193. }),
  7194. undo: docMethodOp(function () {
  7195. makeChangeFromHistory(this, "undo");
  7196. }),
  7197. redo: docMethodOp(function () {
  7198. makeChangeFromHistory(this, "redo");
  7199. }),
  7200. undoSelection: docMethodOp(function () {
  7201. makeChangeFromHistory(this, "undo", true);
  7202. }),
  7203. redoSelection: docMethodOp(function () {
  7204. makeChangeFromHistory(this, "redo", true);
  7205. }),
  7206. setExtending: function (val) {
  7207. this.extend = val;
  7208. },
  7209. getExtending: function () {
  7210. return this.extend
  7211. },
  7212. historySize: function () {
  7213. var hist = this.history, done = 0, undone = 0;
  7214. for (var i = 0; i < hist.done.length; i++) {
  7215. if (!hist.done[i].ranges) {
  7216. ++done;
  7217. }
  7218. }
  7219. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) {
  7220. if (!hist.undone[i$1].ranges) {
  7221. ++undone;
  7222. }
  7223. }
  7224. return {undo: done, redo: undone}
  7225. },
  7226. clearHistory: function () {
  7227. var this$1 = this;
  7228. this.history = new History(this.history);
  7229. linkedDocs(this, function (doc) {
  7230. return doc.history = this$1.history;
  7231. }, true);
  7232. },
  7233. markClean: function () {
  7234. this.cleanGeneration = this.changeGeneration(true);
  7235. },
  7236. changeGeneration: function (forceSplit) {
  7237. if (forceSplit) {
  7238. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  7239. }
  7240. return this.history.generation
  7241. },
  7242. isClean: function (gen) {
  7243. return this.history.generation == (gen || this.cleanGeneration)
  7244. },
  7245. getHistory: function () {
  7246. return {
  7247. done: copyHistoryArray(this.history.done),
  7248. undone: copyHistoryArray(this.history.undone)
  7249. }
  7250. },
  7251. setHistory: function (histData) {
  7252. var hist = this.history = new History(this.history);
  7253. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  7254. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  7255. },
  7256. setGutterMarker: docMethodOp(function (line, gutterID, value) {
  7257. return changeLine(this, line, "gutter", function (line) {
  7258. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  7259. markers[gutterID] = value;
  7260. if (!value && isEmpty(markers)) {
  7261. line.gutterMarkers = null;
  7262. }
  7263. return true
  7264. })
  7265. }),
  7266. clearGutter: docMethodOp(function (gutterID) {
  7267. var this$1 = this;
  7268. this.iter(function (line) {
  7269. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  7270. changeLine(this$1, line, "gutter", function () {
  7271. line.gutterMarkers[gutterID] = null;
  7272. if (isEmpty(line.gutterMarkers)) {
  7273. line.gutterMarkers = null;
  7274. }
  7275. return true
  7276. });
  7277. }
  7278. });
  7279. }),
  7280. lineInfo: function (line) {
  7281. var n;
  7282. if (typeof line == "number") {
  7283. if (!isLine(this, line)) {
  7284. return null
  7285. }
  7286. n = line;
  7287. line = getLine(this, line);
  7288. if (!line) {
  7289. return null
  7290. }
  7291. } else {
  7292. n = lineNo(line);
  7293. if (n == null) {
  7294. return null
  7295. }
  7296. }
  7297. return {
  7298. line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  7299. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  7300. widgets: line.widgets
  7301. }
  7302. },
  7303. addLineClass: docMethodOp(function (handle, where, cls) {
  7304. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  7305. var prop = where == "text" ? "textClass"
  7306. : where == "background" ? "bgClass"
  7307. : where == "gutter" ? "gutterClass" : "wrapClass";
  7308. if (!line[prop]) {
  7309. line[prop] = cls;
  7310. } else if (classTest(cls).test(line[prop])) {
  7311. return false
  7312. } else {
  7313. line[prop] += " " + cls;
  7314. }
  7315. return true
  7316. })
  7317. }),
  7318. removeLineClass: docMethodOp(function (handle, where, cls) {
  7319. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  7320. var prop = where == "text" ? "textClass"
  7321. : where == "background" ? "bgClass"
  7322. : where == "gutter" ? "gutterClass" : "wrapClass";
  7323. var cur = line[prop];
  7324. if (!cur) {
  7325. return false
  7326. } else if (cls == null) {
  7327. line[prop] = null;
  7328. } else {
  7329. var found = cur.match(classTest(cls));
  7330. if (!found) {
  7331. return false
  7332. }
  7333. var end = found.index + found[0].length;
  7334. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  7335. }
  7336. return true
  7337. })
  7338. }),
  7339. addLineWidget: docMethodOp(function (handle, node, options) {
  7340. return addLineWidget(this, handle, node, options)
  7341. }),
  7342. removeLineWidget: function (widget) {
  7343. widget.clear();
  7344. },
  7345. markText: function (from, to, options) {
  7346. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  7347. },
  7348. setBookmark: function (pos, options) {
  7349. var realOpts = {
  7350. replacedWith: options && (options.nodeType == null ? options.widget : options),
  7351. insertLeft: options && options.insertLeft,
  7352. clearWhenEmpty: false, shared: options && options.shared,
  7353. handleMouseEvents: options && options.handleMouseEvents
  7354. };
  7355. pos = clipPos(this, pos);
  7356. return markText(this, pos, pos, realOpts, "bookmark")
  7357. },
  7358. findMarksAt: function (pos) {
  7359. pos = clipPos(this, pos);
  7360. var markers = [], spans = getLine(this, pos.line).markedSpans;
  7361. if (spans) {
  7362. for (var i = 0; i < spans.length; ++i) {
  7363. var span = spans[i];
  7364. if ((span.from == null || span.from <= pos.ch) &&
  7365. (span.to == null || span.to >= pos.ch)) {
  7366. markers.push(span.marker.parent || span.marker);
  7367. }
  7368. }
  7369. }
  7370. return markers
  7371. },
  7372. findMarks: function (from, to, filter) {
  7373. from = clipPos(this, from);
  7374. to = clipPos(this, to);
  7375. var found = [], lineNo = from.line;
  7376. this.iter(from.line, to.line + 1, function (line) {
  7377. var spans = line.markedSpans;
  7378. if (spans) {
  7379. for (var i = 0; i < spans.length; i++) {
  7380. var span = spans[i];
  7381. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  7382. span.from == null && lineNo != from.line ||
  7383. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  7384. (!filter || filter(span.marker))) {
  7385. found.push(span.marker.parent || span.marker);
  7386. }
  7387. }
  7388. }
  7389. ++lineNo;
  7390. });
  7391. return found
  7392. },
  7393. getAllMarks: function () {
  7394. var markers = [];
  7395. this.iter(function (line) {
  7396. var sps = line.markedSpans;
  7397. if (sps) {
  7398. for (var i = 0; i < sps.length; ++i) {
  7399. if (sps[i].from != null) {
  7400. markers.push(sps[i].marker);
  7401. }
  7402. }
  7403. }
  7404. });
  7405. return markers
  7406. },
  7407. posFromIndex: function (off) {
  7408. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  7409. this.iter(function (line) {
  7410. var sz = line.text.length + sepSize;
  7411. if (sz > off) {
  7412. ch = off;
  7413. return true
  7414. }
  7415. off -= sz;
  7416. ++lineNo;
  7417. });
  7418. return clipPos(this, Pos(lineNo, ch))
  7419. },
  7420. indexFromPos: function (coords) {
  7421. coords = clipPos(this, coords);
  7422. var index = coords.ch;
  7423. if (coords.line < this.first || coords.ch < 0) {
  7424. return 0
  7425. }
  7426. var sepSize = this.lineSeparator().length;
  7427. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  7428. index += line.text.length + sepSize;
  7429. });
  7430. return index
  7431. },
  7432. copy: function (copyHistory) {
  7433. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  7434. this.modeOption, this.first, this.lineSep, this.direction);
  7435. doc.scrollTop = this.scrollTop;
  7436. doc.scrollLeft = this.scrollLeft;
  7437. doc.sel = this.sel;
  7438. doc.extend = false;
  7439. if (copyHistory) {
  7440. doc.history.undoDepth = this.history.undoDepth;
  7441. doc.setHistory(this.getHistory());
  7442. }
  7443. return doc
  7444. },
  7445. linkedDoc: function (options) {
  7446. if (!options) {
  7447. options = {};
  7448. }
  7449. var from = this.first, to = this.first + this.size;
  7450. if (options.from != null && options.from > from) {
  7451. from = options.from;
  7452. }
  7453. if (options.to != null && options.to < to) {
  7454. to = options.to;
  7455. }
  7456. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  7457. if (options.sharedHist) {
  7458. copy.history = this.history
  7459. ;
  7460. }
  7461. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  7462. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  7463. copySharedMarkers(copy, findSharedMarkers(this));
  7464. return copy
  7465. },
  7466. unlinkDoc: function (other) {
  7467. if (other instanceof CodeMirror) {
  7468. other = other.doc;
  7469. }
  7470. if (this.linked) {
  7471. for (var i = 0; i < this.linked.length; ++i) {
  7472. var link = this.linked[i];
  7473. if (link.doc != other) {
  7474. continue
  7475. }
  7476. this.linked.splice(i, 1);
  7477. other.unlinkDoc(this);
  7478. detachSharedMarkers(findSharedMarkers(this));
  7479. break
  7480. }
  7481. }
  7482. // If the histories were shared, split them again
  7483. if (other.history == this.history) {
  7484. var splitIds = [other.id];
  7485. linkedDocs(other, function (doc) {
  7486. return splitIds.push(doc.id);
  7487. }, true);
  7488. other.history = new History(null);
  7489. other.history.done = copyHistoryArray(this.history.done, splitIds);
  7490. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  7491. }
  7492. },
  7493. iterLinkedDocs: function (f) {
  7494. linkedDocs(this, f);
  7495. },
  7496. getMode: function () {
  7497. return this.mode
  7498. },
  7499. getEditor: function () {
  7500. return this.cm
  7501. },
  7502. splitLines: function (str) {
  7503. if (this.lineSep) {
  7504. return str.split(this.lineSep)
  7505. }
  7506. return splitLinesAuto(str)
  7507. },
  7508. lineSeparator: function () {
  7509. return this.lineSep || "\n"
  7510. },
  7511. setDirection: docMethodOp(function (dir) {
  7512. if (dir != "rtl") {
  7513. dir = "ltr";
  7514. }
  7515. if (dir == this.direction) {
  7516. return
  7517. }
  7518. this.direction = dir;
  7519. this.iter(function (line) {
  7520. return line.order = null;
  7521. });
  7522. if (this.cm) {
  7523. directionChanged(this.cm);
  7524. }
  7525. })
  7526. });
  7527. // Public alias.
  7528. Doc.prototype.eachLine = Doc.prototype.iter;
  7529. // Kludge to work around strange IE behavior where it'll sometimes
  7530. // re-fire a series of drag-related events right after the drop (#1551)
  7531. var lastDrop = 0;
  7532. function onDrop(e) {
  7533. var cm = this;
  7534. clearDragCursor(cm);
  7535. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
  7536. return
  7537. }
  7538. e_preventDefault(e);
  7539. if (ie) {
  7540. lastDrop = +new Date;
  7541. }
  7542. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  7543. if (!pos || cm.isReadOnly()) {
  7544. return
  7545. }
  7546. // Might be a file drop, in which case we simply extract the text
  7547. // and insert it.
  7548. if (files && files.length && window.FileReader && window.File) {
  7549. var n = files.length, text = Array(n), read = 0;
  7550. var markAsReadAndPasteIfAllFilesAreRead = function () {
  7551. if (++read == n) {
  7552. operation(cm, function () {
  7553. pos = clipPos(cm.doc, pos);
  7554. var change = {
  7555. from: pos, to: pos,
  7556. text: cm.doc.splitLines(
  7557. text.filter(function (t) {
  7558. return t != null;
  7559. }).join(cm.doc.lineSeparator())),
  7560. origin: "paste"
  7561. };
  7562. makeChange(cm.doc, change);
  7563. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  7564. })();
  7565. }
  7566. };
  7567. var readTextFromFile = function (file, i) {
  7568. if (cm.options.allowDropFileTypes &&
  7569. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  7570. markAsReadAndPasteIfAllFilesAreRead();
  7571. return
  7572. }
  7573. var reader = new FileReader;
  7574. reader.onerror = function () {
  7575. return markAsReadAndPasteIfAllFilesAreRead();
  7576. };
  7577. reader.onload = function () {
  7578. var content = reader.result;
  7579. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  7580. markAsReadAndPasteIfAllFilesAreRead();
  7581. return
  7582. }
  7583. text[i] = content;
  7584. markAsReadAndPasteIfAllFilesAreRead();
  7585. };
  7586. reader.readAsText(file);
  7587. };
  7588. for (var i = 0; i < files.length; i++) {
  7589. readTextFromFile(files[i], i);
  7590. }
  7591. } else { // Normal drop
  7592. // Don't do a replace if the drop happened inside of the selected text.
  7593. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  7594. cm.state.draggingText(e);
  7595. // Ensure the editor is re-focused
  7596. setTimeout(function () {
  7597. return cm.display.input.focus();
  7598. }, 20);
  7599. return
  7600. }
  7601. try {
  7602. var text$1 = e.dataTransfer.getData("Text");
  7603. if (text$1) {
  7604. var selected;
  7605. if (cm.state.draggingText && !cm.state.draggingText.copy) {
  7606. selected = cm.listSelections();
  7607. }
  7608. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  7609. if (selected) {
  7610. for (var i$1 = 0; i$1 < selected.length; ++i$1) {
  7611. replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag");
  7612. }
  7613. }
  7614. cm.replaceSelection(text$1, "around", "paste");
  7615. cm.display.input.focus();
  7616. }
  7617. } catch (e$1) {
  7618. }
  7619. }
  7620. }
  7621. function onDragStart(cm, e) {
  7622. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) {
  7623. e_stop(e);
  7624. return
  7625. }
  7626. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
  7627. return
  7628. }
  7629. e.dataTransfer.setData("Text", cm.getSelection());
  7630. e.dataTransfer.effectAllowed = "copyMove";
  7631. // Use dummy image instead of default browsers image.
  7632. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  7633. if (e.dataTransfer.setDragImage && !safari) {
  7634. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  7635. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  7636. if (presto) {
  7637. img.width = img.height = 1;
  7638. cm.display.wrapper.appendChild(img);
  7639. // Force a relayout, or Opera won't use our image for some obscure reason
  7640. img._top = img.offsetTop;
  7641. }
  7642. e.dataTransfer.setDragImage(img, 0, 0);
  7643. if (presto) {
  7644. img.parentNode.removeChild(img);
  7645. }
  7646. }
  7647. }
  7648. function onDragOver(cm, e) {
  7649. var pos = posFromMouse(cm, e);
  7650. if (!pos) {
  7651. return
  7652. }
  7653. var frag = document.createDocumentFragment();
  7654. drawSelectionCursor(cm, pos, frag);
  7655. if (!cm.display.dragCursor) {
  7656. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  7657. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  7658. }
  7659. removeChildrenAndAdd(cm.display.dragCursor, frag);
  7660. }
  7661. function clearDragCursor(cm) {
  7662. if (cm.display.dragCursor) {
  7663. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  7664. cm.display.dragCursor = null;
  7665. }
  7666. }
  7667. // These must be handled carefully, because naively registering a
  7668. // handler for each editor will cause the editors to never be
  7669. // garbage collected.
  7670. function forEachCodeMirror(f) {
  7671. if (!document.getElementsByClassName) {
  7672. return
  7673. }
  7674. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  7675. for (var i = 0; i < byClass.length; i++) {
  7676. var cm = byClass[i].CodeMirror;
  7677. if (cm) {
  7678. editors.push(cm);
  7679. }
  7680. }
  7681. if (editors.length) {
  7682. editors[0].operation(function () {
  7683. for (var i = 0; i < editors.length; i++) {
  7684. f(editors[i]);
  7685. }
  7686. });
  7687. }
  7688. }
  7689. var globalsRegistered = false;
  7690. function ensureGlobalHandlers() {
  7691. if (globalsRegistered) {
  7692. return
  7693. }
  7694. registerGlobalHandlers();
  7695. globalsRegistered = true;
  7696. }
  7697. function registerGlobalHandlers() {
  7698. // When the window resizes, we need to refresh active editors.
  7699. var resizeTimer;
  7700. on(window, "resize", function () {
  7701. if (resizeTimer == null) {
  7702. resizeTimer = setTimeout(function () {
  7703. resizeTimer = null;
  7704. forEachCodeMirror(onResize);
  7705. }, 100);
  7706. }
  7707. });
  7708. // When the window loses focus, we want to show the editor as blurred
  7709. on(window, "blur", function () {
  7710. return forEachCodeMirror(onBlur);
  7711. });
  7712. }
  7713. // Called when the window resizes
  7714. function onResize(cm) {
  7715. var d = cm.display;
  7716. // Might be a text scaling operation, clear size caches.
  7717. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  7718. d.scrollbarsClipped = false;
  7719. cm.setSize();
  7720. }
  7721. var keyNames = {
  7722. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7723. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7724. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7725. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  7726. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  7727. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7728. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7729. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7730. };
  7731. // Number keys
  7732. for (var i = 0; i < 10; i++) {
  7733. keyNames[i + 48] = keyNames[i + 96] = String(i);
  7734. }
  7735. // Alphabetic keys
  7736. for (var i$1 = 65; i$1 <= 90; i$1++) {
  7737. keyNames[i$1] = String.fromCharCode(i$1);
  7738. }
  7739. // Function keys
  7740. for (var i$2 = 1; i$2 <= 12; i$2++) {
  7741. keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2;
  7742. }
  7743. var keyMap = {};
  7744. keyMap.basic = {
  7745. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  7746. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  7747. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  7748. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  7749. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  7750. "Esc": "singleSelection"
  7751. };
  7752. // Note that the save and find-related commands aren't defined by
  7753. // default. User code or addons can define them. Unknown commands
  7754. // are simply ignored.
  7755. keyMap.pcDefault = {
  7756. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  7757. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  7758. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  7759. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  7760. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  7761. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  7762. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  7763. "fallthrough": "basic"
  7764. };
  7765. // Very basic readline/emacs-style bindings, which are standard on Mac.
  7766. keyMap.emacsy = {
  7767. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  7768. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  7769. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  7770. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  7771. "Ctrl-O": "openLine"
  7772. };
  7773. keyMap.macDefault = {
  7774. "Cmd-A": "selectAll",
  7775. "Cmd-D": "deleteLine",
  7776. "Cmd-Z": "undo",
  7777. "Shift-Cmd-Z": "redo",
  7778. "Cmd-Y": "redo",
  7779. "Cmd-Home": "goDocStart",
  7780. "Cmd-Up": "goDocStart",
  7781. "Cmd-End": "goDocEnd",
  7782. "Cmd-Down": "goDocEnd",
  7783. "Alt-Left": "goGroupLeft",
  7784. "Alt-Right": "goGroupRight",
  7785. "Cmd-Left": "goLineLeft",
  7786. "Cmd-Right": "goLineRight",
  7787. "Alt-Backspace": "delGroupBefore",
  7788. "Ctrl-Alt-Backspace": "delGroupAfter",
  7789. "Alt-Delete": "delGroupAfter",
  7790. "Cmd-S": "save",
  7791. "Cmd-F": "find",
  7792. "Cmd-G": "findNext",
  7793. "Shift-Cmd-G": "findPrev",
  7794. "Cmd-Alt-F": "replace",
  7795. "Shift-Cmd-Alt-F": "replaceAll",
  7796. "Cmd-[": "indentLess",
  7797. "Cmd-]": "indentMore",
  7798. "Cmd-Backspace": "delWrappedLineLeft",
  7799. "Cmd-Delete": "delWrappedLineRight",
  7800. "Cmd-U": "undoSelection",
  7801. "Shift-Cmd-U": "redoSelection",
  7802. "Ctrl-Up": "goDocStart",
  7803. "Ctrl-Down": "goDocEnd",
  7804. "fallthrough": ["basic", "emacsy"]
  7805. };
  7806. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  7807. // KEYMAP DISPATCH
  7808. function normalizeKeyName(name) {
  7809. var parts = name.split(/-(?!$)/);
  7810. name = parts[parts.length - 1];
  7811. var alt, ctrl, shift, cmd;
  7812. for (var i = 0; i < parts.length - 1; i++) {
  7813. var mod = parts[i];
  7814. if (/^(cmd|meta|m)$/i.test(mod)) {
  7815. cmd = true;
  7816. } else if (/^a(lt)?$/i.test(mod)) {
  7817. alt = true;
  7818. } else if (/^(c|ctrl|control)$/i.test(mod)) {
  7819. ctrl = true;
  7820. } else if (/^s(hift)?$/i.test(mod)) {
  7821. shift = true;
  7822. } else {
  7823. throw new Error("Unrecognized modifier name: " + mod)
  7824. }
  7825. }
  7826. if (alt) {
  7827. name = "Alt-" + name;
  7828. }
  7829. if (ctrl) {
  7830. name = "Ctrl-" + name;
  7831. }
  7832. if (cmd) {
  7833. name = "Cmd-" + name;
  7834. }
  7835. if (shift) {
  7836. name = "Shift-" + name;
  7837. }
  7838. return name
  7839. }
  7840. // This is a kludge to keep keymaps mostly working as raw objects
  7841. // (backwards compatibility) while at the same time support features
  7842. // like normalization and multi-stroke key bindings. It compiles a
  7843. // new normalized keymap, and then updates the old object to reflect
  7844. // this.
  7845. function normalizeKeyMap(keymap) {
  7846. var copy = {};
  7847. for (var keyname in keymap) {
  7848. if (keymap.hasOwnProperty(keyname)) {
  7849. var value = keymap[keyname];
  7850. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) {
  7851. continue
  7852. }
  7853. if (value == "...") {
  7854. delete keymap[keyname];
  7855. continue
  7856. }
  7857. var keys = map(keyname.split(" "), normalizeKeyName);
  7858. for (var i = 0; i < keys.length; i++) {
  7859. var val = (void 0), name = (void 0);
  7860. if (i == keys.length - 1) {
  7861. name = keys.join(" ");
  7862. val = value;
  7863. } else {
  7864. name = keys.slice(0, i + 1).join(" ");
  7865. val = "...";
  7866. }
  7867. var prev = copy[name];
  7868. if (!prev) {
  7869. copy[name] = val;
  7870. } else if (prev != val) {
  7871. throw new Error("Inconsistent bindings for " + name)
  7872. }
  7873. }
  7874. delete keymap[keyname];
  7875. }
  7876. }
  7877. for (var prop in copy) {
  7878. keymap[prop] = copy[prop];
  7879. }
  7880. return keymap
  7881. }
  7882. function lookupKey(key, map, handle, context) {
  7883. map = getKeyMap(map);
  7884. var found = map.call ? map.call(key, context) : map[key];
  7885. if (found === false) {
  7886. return "nothing"
  7887. }
  7888. if (found === "...") {
  7889. return "multi"
  7890. }
  7891. if (found != null && handle(found)) {
  7892. return "handled"
  7893. }
  7894. if (map.fallthrough) {
  7895. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") {
  7896. return lookupKey(key, map.fallthrough, handle, context)
  7897. }
  7898. for (var i = 0; i < map.fallthrough.length; i++) {
  7899. var result = lookupKey(key, map.fallthrough[i], handle, context);
  7900. if (result) {
  7901. return result
  7902. }
  7903. }
  7904. }
  7905. }
  7906. // Modifier key presses don't count as 'real' key presses for the
  7907. // purpose of keymap fallthrough.
  7908. function isModifierKey(value) {
  7909. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  7910. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  7911. }
  7912. function addModifierNames(name, event, noShift) {
  7913. var base = name;
  7914. if (event.altKey && base != "Alt") {
  7915. name = "Alt-" + name;
  7916. }
  7917. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") {
  7918. name = "Ctrl-" + name;
  7919. }
  7920. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") {
  7921. name = "Cmd-" + name;
  7922. }
  7923. if (!noShift && event.shiftKey && base != "Shift") {
  7924. name = "Shift-" + name;
  7925. }
  7926. return name
  7927. }
  7928. // Look up the name of a key as indicated by an event object.
  7929. function keyName(event, noShift) {
  7930. if (presto && event.keyCode == 34 && event["char"]) {
  7931. return false
  7932. }
  7933. var name = keyNames[event.keyCode];
  7934. if (name == null || event.altGraphKey) {
  7935. return false
  7936. }
  7937. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  7938. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  7939. if (event.keyCode == 3 && event.code) {
  7940. name = event.code;
  7941. }
  7942. return addModifierNames(name, event, noShift)
  7943. }
  7944. function getKeyMap(val) {
  7945. return typeof val == "string" ? keyMap[val] : val
  7946. }
  7947. // Helper for deleting text near the selection(s), used to implement
  7948. // backspace, delete, and similar functionality.
  7949. function deleteNearSelection(cm, compute) {
  7950. var ranges = cm.doc.sel.ranges, kill = [];
  7951. // Build up a set of ranges to kill first, merging overlapping
  7952. // ranges.
  7953. for (var i = 0; i < ranges.length; i++) {
  7954. var toKill = compute(ranges[i]);
  7955. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  7956. var replaced = kill.pop();
  7957. if (cmp(replaced.from, toKill.from) < 0) {
  7958. toKill.from = replaced.from;
  7959. break
  7960. }
  7961. }
  7962. kill.push(toKill);
  7963. }
  7964. // Next, remove those actual ranges.
  7965. runInOp(cm, function () {
  7966. for (var i = kill.length - 1; i >= 0; i--) {
  7967. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  7968. }
  7969. ensureCursorVisible(cm);
  7970. });
  7971. }
  7972. function moveCharLogically(line, ch, dir) {
  7973. var target = skipExtendingChars(line.text, ch + dir, dir);
  7974. return target < 0 || target > line.text.length ? null : target
  7975. }
  7976. function moveLogically(line, start, dir) {
  7977. var ch = moveCharLogically(line, start.ch, dir);
  7978. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  7979. }
  7980. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  7981. if (visually) {
  7982. if (cm.doc.direction == "rtl") {
  7983. dir = -dir;
  7984. }
  7985. var order = getOrder(lineObj, cm.doc.direction);
  7986. if (order) {
  7987. var part = dir < 0 ? lst(order) : order[0];
  7988. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  7989. var sticky = moveInStorageOrder ? "after" : "before";
  7990. var ch;
  7991. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  7992. // it could be that the last bidi part is not on the last visual line,
  7993. // since visual lines contain content order-consecutive chunks.
  7994. // Thus, in rtl, we are looking for the first (content-order) character
  7995. // in the rtl chunk that is on the last line (that is, the same line
  7996. // as the last (content-order) character).
  7997. if (part.level > 0 || cm.doc.direction == "rtl") {
  7998. var prep = prepareMeasureForLine(cm, lineObj);
  7999. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  8000. var targetTop = measureCharPrepared(cm, prep, ch).top;
  8001. ch = findFirst(function (ch) {
  8002. return measureCharPrepared(cm, prep, ch).top == targetTop;
  8003. }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  8004. if (sticky == "before") {
  8005. ch = moveCharLogically(lineObj, ch, 1);
  8006. }
  8007. } else {
  8008. ch = dir < 0 ? part.to : part.from;
  8009. }
  8010. return new Pos(lineNo, ch, sticky)
  8011. }
  8012. }
  8013. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  8014. }
  8015. function moveVisually(cm, line, start, dir) {
  8016. var bidi = getOrder(line, cm.doc.direction);
  8017. if (!bidi) {
  8018. return moveLogically(line, start, dir)
  8019. }
  8020. if (start.ch >= line.text.length) {
  8021. start.ch = line.text.length;
  8022. start.sticky = "before";
  8023. } else if (start.ch <= 0) {
  8024. start.ch = 0;
  8025. start.sticky = "after";
  8026. }
  8027. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  8028. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  8029. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  8030. // nothing interesting happens.
  8031. return moveLogically(line, start, dir)
  8032. }
  8033. var mv = function (pos, dir) {
  8034. return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir);
  8035. };
  8036. var prep;
  8037. var getWrappedLineExtent = function (ch) {
  8038. if (!cm.options.lineWrapping) {
  8039. return {begin: 0, end: line.text.length}
  8040. }
  8041. prep = prep || prepareMeasureForLine(cm, line);
  8042. return wrappedLineExtentChar(cm, line, prep, ch)
  8043. };
  8044. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  8045. if (cm.doc.direction == "rtl" || part.level == 1) {
  8046. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  8047. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  8048. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  8049. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  8050. var sticky = moveInStorageOrder ? "before" : "after";
  8051. return new Pos(start.line, ch, sticky)
  8052. }
  8053. }
  8054. // Case 3: Could not move within this bidi part in this visual line, so leave
  8055. // the current bidi part
  8056. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  8057. var getRes = function (ch, moveInStorageOrder) {
  8058. return moveInStorageOrder
  8059. ? new Pos(start.line, mv(ch, 1), "before")
  8060. : new Pos(start.line, ch, "after");
  8061. };
  8062. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  8063. var part = bidi[partPos];
  8064. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  8065. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  8066. if (part.from <= ch && ch < part.to) {
  8067. return getRes(ch, moveInStorageOrder)
  8068. }
  8069. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  8070. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) {
  8071. return getRes(ch, moveInStorageOrder)
  8072. }
  8073. }
  8074. };
  8075. // Case 3a: Look for other bidi parts on the same visual line
  8076. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  8077. if (res) {
  8078. return res
  8079. }
  8080. // Case 3b: Look for other bidi parts on the next visual line
  8081. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  8082. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  8083. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  8084. if (res) {
  8085. return res
  8086. }
  8087. }
  8088. // Case 4: Nowhere to move
  8089. return null
  8090. }
  8091. // Commands are parameter-less actions that can be performed on an
  8092. // editor, mostly used for keybindings.
  8093. var commands = {
  8094. selectAll: selectAll,
  8095. singleSelection: function (cm) {
  8096. return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  8097. },
  8098. killLine: function (cm) {
  8099. return deleteNearSelection(cm, function (range) {
  8100. if (range.empty()) {
  8101. var len = getLine(cm.doc, range.head.line).text.length;
  8102. if (range.head.ch == len && range.head.line < cm.lastLine()) {
  8103. return {from: range.head, to: Pos(range.head.line + 1, 0)}
  8104. } else {
  8105. return {from: range.head, to: Pos(range.head.line, len)}
  8106. }
  8107. } else {
  8108. return {from: range.from(), to: range.to()}
  8109. }
  8110. });
  8111. },
  8112. deleteLine: function (cm) {
  8113. return deleteNearSelection(cm, function (range) {
  8114. return ({
  8115. from: Pos(range.from().line, 0),
  8116. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  8117. });
  8118. });
  8119. },
  8120. delLineLeft: function (cm) {
  8121. return deleteNearSelection(cm, function (range) {
  8122. return ({
  8123. from: Pos(range.from().line, 0), to: range.from()
  8124. });
  8125. });
  8126. },
  8127. delWrappedLineLeft: function (cm) {
  8128. return deleteNearSelection(cm, function (range) {
  8129. var top = cm.charCoords(range.head, "div").top + 5;
  8130. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  8131. return {from: leftPos, to: range.from()}
  8132. });
  8133. },
  8134. delWrappedLineRight: function (cm) {
  8135. return deleteNearSelection(cm, function (range) {
  8136. var top = cm.charCoords(range.head, "div").top + 5;
  8137. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  8138. return {from: range.from(), to: rightPos}
  8139. });
  8140. },
  8141. undo: function (cm) {
  8142. return cm.undo();
  8143. },
  8144. redo: function (cm) {
  8145. return cm.redo();
  8146. },
  8147. undoSelection: function (cm) {
  8148. return cm.undoSelection();
  8149. },
  8150. redoSelection: function (cm) {
  8151. return cm.redoSelection();
  8152. },
  8153. goDocStart: function (cm) {
  8154. return cm.extendSelection(Pos(cm.firstLine(), 0));
  8155. },
  8156. goDocEnd: function (cm) {
  8157. return cm.extendSelection(Pos(cm.lastLine()));
  8158. },
  8159. goLineStart: function (cm) {
  8160. return cm.extendSelectionsBy(function (range) {
  8161. return lineStart(cm, range.head.line);
  8162. },
  8163. {origin: "+move", bias: 1}
  8164. );
  8165. },
  8166. goLineStartSmart: function (cm) {
  8167. return cm.extendSelectionsBy(function (range) {
  8168. return lineStartSmart(cm, range.head);
  8169. },
  8170. {origin: "+move", bias: 1}
  8171. );
  8172. },
  8173. goLineEnd: function (cm) {
  8174. return cm.extendSelectionsBy(function (range) {
  8175. return lineEnd(cm, range.head.line);
  8176. },
  8177. {origin: "+move", bias: -1}
  8178. );
  8179. },
  8180. goLineRight: function (cm) {
  8181. return cm.extendSelectionsBy(function (range) {
  8182. var top = cm.cursorCoords(range.head, "div").top + 5;
  8183. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  8184. }, sel_move);
  8185. },
  8186. goLineLeft: function (cm) {
  8187. return cm.extendSelectionsBy(function (range) {
  8188. var top = cm.cursorCoords(range.head, "div").top + 5;
  8189. return cm.coordsChar({left: 0, top: top}, "div")
  8190. }, sel_move);
  8191. },
  8192. goLineLeftSmart: function (cm) {
  8193. return cm.extendSelectionsBy(function (range) {
  8194. var top = cm.cursorCoords(range.head, "div").top + 5;
  8195. var pos = cm.coordsChar({left: 0, top: top}, "div");
  8196. if (pos.ch < cm.getLine(pos.line).search(/\S/)) {
  8197. return lineStartSmart(cm, range.head)
  8198. }
  8199. return pos
  8200. }, sel_move);
  8201. },
  8202. goLineUp: function (cm) {
  8203. return cm.moveV(-1, "line");
  8204. },
  8205. goLineDown: function (cm) {
  8206. return cm.moveV(1, "line");
  8207. },
  8208. goPageUp: function (cm) {
  8209. return cm.moveV(-1, "page");
  8210. },
  8211. goPageDown: function (cm) {
  8212. return cm.moveV(1, "page");
  8213. },
  8214. goCharLeft: function (cm) {
  8215. return cm.moveH(-1, "char");
  8216. },
  8217. goCharRight: function (cm) {
  8218. return cm.moveH(1, "char");
  8219. },
  8220. goColumnLeft: function (cm) {
  8221. return cm.moveH(-1, "column");
  8222. },
  8223. goColumnRight: function (cm) {
  8224. return cm.moveH(1, "column");
  8225. },
  8226. goWordLeft: function (cm) {
  8227. return cm.moveH(-1, "word");
  8228. },
  8229. goGroupRight: function (cm) {
  8230. return cm.moveH(1, "group");
  8231. },
  8232. goGroupLeft: function (cm) {
  8233. return cm.moveH(-1, "group");
  8234. },
  8235. goWordRight: function (cm) {
  8236. return cm.moveH(1, "word");
  8237. },
  8238. delCharBefore: function (cm) {
  8239. return cm.deleteH(-1, "codepoint");
  8240. },
  8241. delCharAfter: function (cm) {
  8242. return cm.deleteH(1, "char");
  8243. },
  8244. delWordBefore: function (cm) {
  8245. return cm.deleteH(-1, "word");
  8246. },
  8247. delWordAfter: function (cm) {
  8248. return cm.deleteH(1, "word");
  8249. },
  8250. delGroupBefore: function (cm) {
  8251. return cm.deleteH(-1, "group");
  8252. },
  8253. delGroupAfter: function (cm) {
  8254. return cm.deleteH(1, "group");
  8255. },
  8256. indentAuto: function (cm) {
  8257. return cm.indentSelection("smart");
  8258. },
  8259. indentMore: function (cm) {
  8260. return cm.indentSelection("add");
  8261. },
  8262. indentLess: function (cm) {
  8263. return cm.indentSelection("subtract");
  8264. },
  8265. insertTab: function (cm) {
  8266. return cm.replaceSelection("\t");
  8267. },
  8268. insertSoftTab: function (cm) {
  8269. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  8270. for (var i = 0; i < ranges.length; i++) {
  8271. var pos = ranges[i].from();
  8272. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  8273. spaces.push(spaceStr(tabSize - col % tabSize));
  8274. }
  8275. cm.replaceSelections(spaces);
  8276. },
  8277. defaultTab: function (cm) {
  8278. if (cm.somethingSelected()) {
  8279. cm.indentSelection("add");
  8280. } else {
  8281. cm.execCommand("insertTab");
  8282. }
  8283. },
  8284. // Swap the two chars left and right of each selection's head.
  8285. // Move cursor behind the two swapped characters afterwards.
  8286. //
  8287. // Doesn't consider line feeds a character.
  8288. // Doesn't scan more than one line above to find a character.
  8289. // Doesn't do anything on an empty line.
  8290. // Doesn't do anything with non-empty selections.
  8291. transposeChars: function (cm) {
  8292. return runInOp(cm, function () {
  8293. var ranges = cm.listSelections(), newSel = [];
  8294. for (var i = 0; i < ranges.length; i++) {
  8295. if (!ranges[i].empty()) {
  8296. continue
  8297. }
  8298. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  8299. if (line) {
  8300. if (cur.ch == line.length) {
  8301. cur = new Pos(cur.line, cur.ch - 1);
  8302. }
  8303. if (cur.ch > 0) {
  8304. cur = new Pos(cur.line, cur.ch + 1);
  8305. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  8306. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  8307. } else if (cur.line > cm.doc.first) {
  8308. var prev = getLine(cm.doc, cur.line - 1).text;
  8309. if (prev) {
  8310. cur = new Pos(cur.line, 1);
  8311. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  8312. prev.charAt(prev.length - 1),
  8313. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  8314. }
  8315. }
  8316. }
  8317. newSel.push(new Range(cur, cur));
  8318. }
  8319. cm.setSelections(newSel);
  8320. });
  8321. },
  8322. newlineAndIndent: function (cm) {
  8323. return runInOp(cm, function () {
  8324. var sels = cm.listSelections();
  8325. for (var i = sels.length - 1; i >= 0; i--) {
  8326. cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input");
  8327. }
  8328. sels = cm.listSelections();
  8329. for (var i$1 = 0; i$1 < sels.length; i$1++) {
  8330. cm.indentLine(sels[i$1].from().line, null, true);
  8331. }
  8332. ensureCursorVisible(cm);
  8333. });
  8334. },
  8335. openLine: function (cm) {
  8336. return cm.replaceSelection("\n", "start");
  8337. },
  8338. toggleOverwrite: function (cm) {
  8339. return cm.toggleOverwrite();
  8340. }
  8341. };
  8342. function lineStart(cm, lineN) {
  8343. var line = getLine(cm.doc, lineN);
  8344. var visual = visualLine(line);
  8345. if (visual != line) {
  8346. lineN = lineNo(visual);
  8347. }
  8348. return endOfLine(true, cm, visual, lineN, 1)
  8349. }
  8350. function lineEnd(cm, lineN) {
  8351. var line = getLine(cm.doc, lineN);
  8352. var visual = visualLineEnd(line);
  8353. if (visual != line) {
  8354. lineN = lineNo(visual);
  8355. }
  8356. return endOfLine(true, cm, line, lineN, -1)
  8357. }
  8358. function lineStartSmart(cm, pos) {
  8359. var start = lineStart(cm, pos.line);
  8360. var line = getLine(cm.doc, start.line);
  8361. var order = getOrder(line, cm.doc.direction);
  8362. if (!order || order[0].level == 0) {
  8363. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  8364. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  8365. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  8366. }
  8367. return start
  8368. }
  8369. // Run a handler that was bound to a key.
  8370. function doHandleBinding(cm, bound, dropShift) {
  8371. if (typeof bound == "string") {
  8372. bound = commands[bound];
  8373. if (!bound) {
  8374. return false
  8375. }
  8376. }
  8377. // Ensure previous input has been read, so that the handler sees a
  8378. // consistent view of the document
  8379. cm.display.input.ensurePolled();
  8380. var prevShift = cm.display.shift, done = false;
  8381. try {
  8382. if (cm.isReadOnly()) {
  8383. cm.state.suppressEdits = true;
  8384. }
  8385. if (dropShift) {
  8386. cm.display.shift = false;
  8387. }
  8388. done = bound(cm) != Pass;
  8389. } finally {
  8390. cm.display.shift = prevShift;
  8391. cm.state.suppressEdits = false;
  8392. }
  8393. return done
  8394. }
  8395. function lookupKeyForEditor(cm, name, handle) {
  8396. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  8397. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  8398. if (result) {
  8399. return result
  8400. }
  8401. }
  8402. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  8403. || lookupKey(name, cm.options.keyMap, handle, cm)
  8404. }
  8405. // Note that, despite the name, this function is also used to check
  8406. // for bound mouse clicks.
  8407. var stopSeq = new Delayed;
  8408. function dispatchKey(cm, name, e, handle) {
  8409. var seq = cm.state.keySeq;
  8410. if (seq) {
  8411. if (isModifierKey(name)) {
  8412. return "handled"
  8413. }
  8414. if (/\'$/.test(name)) {
  8415. cm.state.keySeq = null;
  8416. } else {
  8417. stopSeq.set(50, function () {
  8418. if (cm.state.keySeq == seq) {
  8419. cm.state.keySeq = null;
  8420. cm.display.input.reset();
  8421. }
  8422. });
  8423. }
  8424. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) {
  8425. return true
  8426. }
  8427. }
  8428. return dispatchKeyInner(cm, name, e, handle)
  8429. }
  8430. function dispatchKeyInner(cm, name, e, handle) {
  8431. var result = lookupKeyForEditor(cm, name, handle);
  8432. if (result == "multi") {
  8433. cm.state.keySeq = name;
  8434. }
  8435. if (result == "handled") {
  8436. signalLater(cm, "keyHandled", cm, name, e);
  8437. }
  8438. if (result == "handled" || result == "multi") {
  8439. e_preventDefault(e);
  8440. restartBlink(cm);
  8441. }
  8442. return !!result
  8443. }
  8444. // Handle a key from the keydown event.
  8445. function handleKeyBinding(cm, e) {
  8446. var name = keyName(e, true);
  8447. if (!name) {
  8448. return false
  8449. }
  8450. if (e.shiftKey && !cm.state.keySeq) {
  8451. // First try to resolve full name (including 'Shift-'). Failing
  8452. // that, see if there is a cursor-motion command (starting with
  8453. // 'go') bound to the keyname without 'Shift-'.
  8454. return dispatchKey(cm, "Shift-" + name, e, function (b) {
  8455. return doHandleBinding(cm, b, true);
  8456. })
  8457. || dispatchKey(cm, name, e, function (b) {
  8458. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) {
  8459. return doHandleBinding(cm, b)
  8460. }
  8461. })
  8462. } else {
  8463. return dispatchKey(cm, name, e, function (b) {
  8464. return doHandleBinding(cm, b);
  8465. })
  8466. }
  8467. }
  8468. // Handle a key from the keypress event
  8469. function handleCharBinding(cm, e, ch) {
  8470. return dispatchKey(cm, "'" + ch + "'", e, function (b) {
  8471. return doHandleBinding(cm, b, true);
  8472. })
  8473. }
  8474. var lastStoppedKey = null;
  8475. function onKeyDown(e) {
  8476. var cm = this;
  8477. if (e.target && e.target != cm.display.input.getField()) {
  8478. return
  8479. }
  8480. cm.curOp.focus = activeElt();
  8481. if (signalDOMEvent(cm, e)) {
  8482. return
  8483. }
  8484. // IE does strange things with escape.
  8485. if (ie && ie_version < 11 && e.keyCode == 27) {
  8486. e.returnValue = false;
  8487. }
  8488. var code = e.keyCode;
  8489. cm.display.shift = code == 16 || e.shiftKey;
  8490. var handled = handleKeyBinding(cm, e);
  8491. if (presto) {
  8492. lastStoppedKey = handled ? code : null;
  8493. // Opera has no cut event... we try to at least catch the key combo
  8494. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) {
  8495. cm.replaceSelection("", null, "cut");
  8496. }
  8497. }
  8498. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) {
  8499. document.execCommand("cut");
  8500. }
  8501. // Turn mouse into crosshair when Alt is held on Mac.
  8502. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {
  8503. showCrossHair(cm);
  8504. }
  8505. }
  8506. function showCrossHair(cm) {
  8507. var lineDiv = cm.display.lineDiv;
  8508. addClass(lineDiv, "CodeMirror-crosshair");
  8509. function up(e) {
  8510. if (e.keyCode == 18 || !e.altKey) {
  8511. rmClass(lineDiv, "CodeMirror-crosshair");
  8512. off(document, "keyup", up);
  8513. off(document, "mouseover", up);
  8514. }
  8515. }
  8516. on(document, "keyup", up);
  8517. on(document, "mouseover", up);
  8518. }
  8519. function onKeyUp(e) {
  8520. if (e.keyCode == 16) {
  8521. this.doc.sel.shift = false;
  8522. }
  8523. signalDOMEvent(this, e);
  8524. }
  8525. function onKeyPress(e) {
  8526. var cm = this;
  8527. if (e.target && e.target != cm.display.input.getField()) {
  8528. return
  8529. }
  8530. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) {
  8531. return
  8532. }
  8533. var keyCode = e.keyCode, charCode = e.charCode;
  8534. if (presto && keyCode == lastStoppedKey) {
  8535. lastStoppedKey = null;
  8536. e_preventDefault(e);
  8537. return
  8538. }
  8539. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) {
  8540. return
  8541. }
  8542. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  8543. // Some browsers fire keypress events for backspace
  8544. if (ch == "\x08") {
  8545. return
  8546. }
  8547. if (handleCharBinding(cm, e, ch)) {
  8548. return
  8549. }
  8550. cm.display.input.onKeyPress(e);
  8551. }
  8552. var DOUBLECLICK_DELAY = 400;
  8553. var PastClick = function (time, pos, button) {
  8554. this.time = time;
  8555. this.pos = pos;
  8556. this.button = button;
  8557. };
  8558. PastClick.prototype.compare = function (time, pos, button) {
  8559. return this.time + DOUBLECLICK_DELAY > time &&
  8560. cmp(pos, this.pos) == 0 && button == this.button
  8561. };
  8562. var lastClick, lastDoubleClick;
  8563. function clickRepeat(pos, button) {
  8564. var now = +new Date;
  8565. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  8566. lastClick = lastDoubleClick = null;
  8567. return "triple"
  8568. } else if (lastClick && lastClick.compare(now, pos, button)) {
  8569. lastDoubleClick = new PastClick(now, pos, button);
  8570. lastClick = null;
  8571. return "double"
  8572. } else {
  8573. lastClick = new PastClick(now, pos, button);
  8574. lastDoubleClick = null;
  8575. return "single"
  8576. }
  8577. }
  8578. // A mouse down can be a single click, double click, triple click,
  8579. // start of selection drag, start of text drag, new cursor
  8580. // (ctrl-click), rectangle drag (alt-drag), or xwin
  8581. // middle-click-paste. Or it might be a click on something we should
  8582. // not interfere with, such as a scrollbar or widget.
  8583. function onMouseDown(e) {
  8584. var cm = this, display = cm.display;
  8585. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) {
  8586. return
  8587. }
  8588. display.input.ensurePolled();
  8589. display.shift = e.shiftKey;
  8590. if (eventInWidget(display, e)) {
  8591. if (!webkit) {
  8592. // Briefly turn off draggability, to allow widgets to do
  8593. // normal dragging things.
  8594. display.scroller.draggable = false;
  8595. setTimeout(function () {
  8596. return display.scroller.draggable = true;
  8597. }, 100);
  8598. }
  8599. return
  8600. }
  8601. if (clickInGutter(cm, e)) {
  8602. return
  8603. }
  8604. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  8605. window.focus();
  8606. // #3261: make sure, that we're not starting a second selection
  8607. if (button == 1 && cm.state.selectingText) {
  8608. cm.state.selectingText(e);
  8609. }
  8610. if (pos && handleMappedButton(cm, button, pos, repeat, e)) {
  8611. return
  8612. }
  8613. if (button == 1) {
  8614. if (pos) {
  8615. leftButtonDown(cm, pos, repeat, e);
  8616. } else if (e_target(e) == display.scroller) {
  8617. e_preventDefault(e);
  8618. }
  8619. } else if (button == 2) {
  8620. if (pos) {
  8621. extendSelection(cm.doc, pos);
  8622. }
  8623. setTimeout(function () {
  8624. return display.input.focus();
  8625. }, 20);
  8626. } else if (button == 3) {
  8627. if (captureRightClick) {
  8628. cm.display.input.onContextMenu(e);
  8629. } else {
  8630. delayBlurEvent(cm);
  8631. }
  8632. }
  8633. }
  8634. function handleMappedButton(cm, button, pos, repeat, event) {
  8635. var name = "Click";
  8636. if (repeat == "double") {
  8637. name = "Double" + name;
  8638. } else if (repeat == "triple") {
  8639. name = "Triple" + name;
  8640. }
  8641. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  8642. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  8643. if (typeof bound == "string") {
  8644. bound = commands[bound];
  8645. }
  8646. if (!bound) {
  8647. return false
  8648. }
  8649. var done = false;
  8650. try {
  8651. if (cm.isReadOnly()) {
  8652. cm.state.suppressEdits = true;
  8653. }
  8654. done = bound(cm, pos) != Pass;
  8655. } finally {
  8656. cm.state.suppressEdits = false;
  8657. }
  8658. return done
  8659. })
  8660. }
  8661. function configureMouse(cm, repeat, event) {
  8662. var option = cm.getOption("configureMouse");
  8663. var value = option ? option(cm, repeat, event) : {};
  8664. if (value.unit == null) {
  8665. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  8666. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  8667. }
  8668. if (value.extend == null || cm.doc.extend) {
  8669. value.extend = cm.doc.extend || event.shiftKey;
  8670. }
  8671. if (value.addNew == null) {
  8672. value.addNew = mac ? event.metaKey : event.ctrlKey;
  8673. }
  8674. if (value.moveOnDrag == null) {
  8675. value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey);
  8676. }
  8677. return value
  8678. }
  8679. function leftButtonDown(cm, pos, repeat, event) {
  8680. if (ie) {
  8681. setTimeout(bind(ensureFocus, cm), 0);
  8682. } else {
  8683. cm.curOp.focus = activeElt();
  8684. }
  8685. var behavior = configureMouse(cm, repeat, event);
  8686. var sel = cm.doc.sel, contained;
  8687. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  8688. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  8689. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  8690. (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) {
  8691. leftButtonStartDrag(cm, event, pos, behavior);
  8692. } else {
  8693. leftButtonSelect(cm, event, pos, behavior);
  8694. }
  8695. }
  8696. // Start a text drag. When it ends, see if any dragging actually
  8697. // happen, and treat as a click if it didn't.
  8698. function leftButtonStartDrag(cm, event, pos, behavior) {
  8699. var display = cm.display, moved = false;
  8700. var dragEnd = operation(cm, function (e) {
  8701. if (webkit) {
  8702. display.scroller.draggable = false;
  8703. }
  8704. cm.state.draggingText = false;
  8705. if (cm.state.delayingBlurEvent) {
  8706. if (cm.hasFocus()) {
  8707. cm.state.delayingBlurEvent = false;
  8708. } else {
  8709. delayBlurEvent(cm);
  8710. }
  8711. }
  8712. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  8713. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  8714. off(display.scroller, "dragstart", dragStart);
  8715. off(display.scroller, "drop", dragEnd);
  8716. if (!moved) {
  8717. e_preventDefault(e);
  8718. if (!behavior.addNew) {
  8719. extendSelection(cm.doc, pos, null, null, behavior.extend);
  8720. }
  8721. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  8722. if ((webkit && !safari) || ie && ie_version == 9) {
  8723. setTimeout(function () {
  8724. display.wrapper.ownerDocument.body.focus({preventScroll: true});
  8725. display.input.focus();
  8726. }, 20);
  8727. } else {
  8728. display.input.focus();
  8729. }
  8730. }
  8731. });
  8732. var mouseMove = function (e2) {
  8733. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  8734. };
  8735. var dragStart = function () {
  8736. return moved = true;
  8737. };
  8738. // Let the drag handler handle this.
  8739. if (webkit) {
  8740. display.scroller.draggable = true;
  8741. }
  8742. cm.state.draggingText = dragEnd;
  8743. dragEnd.copy = !behavior.moveOnDrag;
  8744. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  8745. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  8746. on(display.scroller, "dragstart", dragStart);
  8747. on(display.scroller, "drop", dragEnd);
  8748. cm.state.delayingBlurEvent = true;
  8749. setTimeout(function () {
  8750. return display.input.focus();
  8751. }, 20);
  8752. // IE's approach to draggable
  8753. if (display.scroller.dragDrop) {
  8754. display.scroller.dragDrop();
  8755. }
  8756. }
  8757. function rangeForUnit(cm, pos, unit) {
  8758. if (unit == "char") {
  8759. return new Range(pos, pos)
  8760. }
  8761. if (unit == "word") {
  8762. return cm.findWordAt(pos)
  8763. }
  8764. if (unit == "line") {
  8765. return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)))
  8766. }
  8767. var result = unit(cm, pos);
  8768. return new Range(result.from, result.to)
  8769. }
  8770. // Normal selection, as opposed to text dragging.
  8771. function leftButtonSelect(cm, event, start, behavior) {
  8772. if (ie) {
  8773. delayBlurEvent(cm);
  8774. }
  8775. var display = cm.display, doc = cm.doc;
  8776. e_preventDefault(event);
  8777. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  8778. if (behavior.addNew && !behavior.extend) {
  8779. ourIndex = doc.sel.contains(start);
  8780. if (ourIndex > -1) {
  8781. ourRange = ranges[ourIndex];
  8782. } else {
  8783. ourRange = new Range(start, start);
  8784. }
  8785. } else {
  8786. ourRange = doc.sel.primary();
  8787. ourIndex = doc.sel.primIndex;
  8788. }
  8789. if (behavior.unit == "rectangle") {
  8790. if (!behavior.addNew) {
  8791. ourRange = new Range(start, start);
  8792. }
  8793. start = posFromMouse(cm, event, true, true);
  8794. ourIndex = -1;
  8795. } else {
  8796. var range = rangeForUnit(cm, start, behavior.unit);
  8797. if (behavior.extend) {
  8798. ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend);
  8799. } else {
  8800. ourRange = range;
  8801. }
  8802. }
  8803. if (!behavior.addNew) {
  8804. ourIndex = 0;
  8805. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  8806. startSel = doc.sel;
  8807. } else if (ourIndex == -1) {
  8808. ourIndex = ranges.length;
  8809. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  8810. {scroll: false, origin: "*mouse"});
  8811. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  8812. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  8813. {scroll: false, origin: "*mouse"});
  8814. startSel = doc.sel;
  8815. } else {
  8816. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  8817. }
  8818. var lastPos = start;
  8819. function extendTo(pos) {
  8820. if (cmp(lastPos, pos) == 0) {
  8821. return
  8822. }
  8823. lastPos = pos;
  8824. if (behavior.unit == "rectangle") {
  8825. var ranges = [], tabSize = cm.options.tabSize;
  8826. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  8827. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  8828. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  8829. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  8830. line <= end; line++) {
  8831. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  8832. if (left == right) {
  8833. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  8834. } else if (text.length > leftPos) {
  8835. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  8836. }
  8837. }
  8838. if (!ranges.length) {
  8839. ranges.push(new Range(start, start));
  8840. }
  8841. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  8842. {origin: "*mouse", scroll: false});
  8843. cm.scrollIntoView(pos);
  8844. } else {
  8845. var oldRange = ourRange;
  8846. var range = rangeForUnit(cm, pos, behavior.unit);
  8847. var anchor = oldRange.anchor, head;
  8848. if (cmp(range.anchor, anchor) > 0) {
  8849. head = range.head;
  8850. anchor = minPos(oldRange.from(), range.anchor);
  8851. } else {
  8852. head = range.anchor;
  8853. anchor = maxPos(oldRange.to(), range.head);
  8854. }
  8855. var ranges$1 = startSel.ranges.slice(0);
  8856. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  8857. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  8858. }
  8859. }
  8860. var editorSize = display.wrapper.getBoundingClientRect();
  8861. // Used to ensure timeout re-tries don't fire when another extend
  8862. // happened in the meantime (clearTimeout isn't reliable -- at
  8863. // least on Chrome, the timeouts still happen even when cleared,
  8864. // if the clear happens after their scheduled firing time).
  8865. var counter = 0;
  8866. function extend(e) {
  8867. var curCount = ++counter;
  8868. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  8869. if (!cur) {
  8870. return
  8871. }
  8872. if (cmp(cur, lastPos) != 0) {
  8873. cm.curOp.focus = activeElt();
  8874. extendTo(cur);
  8875. var visible = visibleLines(display, doc);
  8876. if (cur.line >= visible.to || cur.line < visible.from) {
  8877. setTimeout(operation(cm, function () {
  8878. if (counter == curCount) {
  8879. extend(e);
  8880. }
  8881. }), 150);
  8882. }
  8883. } else {
  8884. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  8885. if (outside) {
  8886. setTimeout(operation(cm, function () {
  8887. if (counter != curCount) {
  8888. return
  8889. }
  8890. display.scroller.scrollTop += outside;
  8891. extend(e);
  8892. }), 50);
  8893. }
  8894. }
  8895. }
  8896. function done(e) {
  8897. cm.state.selectingText = false;
  8898. counter = Infinity;
  8899. // If e is null or undefined we interpret this as someone trying
  8900. // to explicitly cancel the selection rather than the user
  8901. // letting go of the mouse button.
  8902. if (e) {
  8903. e_preventDefault(e);
  8904. display.input.focus();
  8905. }
  8906. off(display.wrapper.ownerDocument, "mousemove", move);
  8907. off(display.wrapper.ownerDocument, "mouseup", up);
  8908. doc.history.lastSelOrigin = null;
  8909. }
  8910. var move = operation(cm, function (e) {
  8911. if (e.buttons === 0 || !e_button(e)) {
  8912. done(e);
  8913. } else {
  8914. extend(e);
  8915. }
  8916. });
  8917. var up = operation(cm, done);
  8918. cm.state.selectingText = up;
  8919. on(display.wrapper.ownerDocument, "mousemove", move);
  8920. on(display.wrapper.ownerDocument, "mouseup", up);
  8921. }
  8922. // Used when mouse-selecting to adjust the anchor to the proper side
  8923. // of a bidi jump depending on the visual position of the head.
  8924. function bidiSimplify(cm, range) {
  8925. var anchor = range.anchor;
  8926. var head = range.head;
  8927. var anchorLine = getLine(cm.doc, anchor.line);
  8928. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) {
  8929. return range
  8930. }
  8931. var order = getOrder(anchorLine);
  8932. if (!order) {
  8933. return range
  8934. }
  8935. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  8936. if (part.from != anchor.ch && part.to != anchor.ch) {
  8937. return range
  8938. }
  8939. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  8940. if (boundary == 0 || boundary == order.length) {
  8941. return range
  8942. }
  8943. // Compute the relative visual position of the head compared to the
  8944. // anchor (<0 is to the left, >0 to the right)
  8945. var leftSide;
  8946. if (head.line != anchor.line) {
  8947. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  8948. } else {
  8949. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  8950. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  8951. if (headIndex == boundary - 1 || headIndex == boundary) {
  8952. leftSide = dir < 0;
  8953. } else {
  8954. leftSide = dir > 0;
  8955. }
  8956. }
  8957. var usePart = order[boundary + (leftSide ? -1 : 0)];
  8958. var from = leftSide == (usePart.level == 1);
  8959. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  8960. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  8961. }
  8962. // Determines whether an event happened in the gutter, and fires the
  8963. // handlers for the corresponding event.
  8964. function gutterEvent(cm, e, type, prevent) {
  8965. var mX, mY;
  8966. if (e.touches) {
  8967. mX = e.touches[0].clientX;
  8968. mY = e.touches[0].clientY;
  8969. } else {
  8970. try {
  8971. mX = e.clientX;
  8972. mY = e.clientY;
  8973. } catch (e$1) {
  8974. return false
  8975. }
  8976. }
  8977. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) {
  8978. return false
  8979. }
  8980. if (prevent) {
  8981. e_preventDefault(e);
  8982. }
  8983. var display = cm.display;
  8984. var lineBox = display.lineDiv.getBoundingClientRect();
  8985. if (mY > lineBox.bottom || !hasHandler(cm, type)) {
  8986. return e_defaultPrevented(e)
  8987. }
  8988. mY -= lineBox.top - display.viewOffset;
  8989. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  8990. var g = display.gutters.childNodes[i];
  8991. if (g && g.getBoundingClientRect().right >= mX) {
  8992. var line = lineAtHeight(cm.doc, mY);
  8993. var gutter = cm.display.gutterSpecs[i];
  8994. signal(cm, type, cm, line, gutter.className, e);
  8995. return e_defaultPrevented(e)
  8996. }
  8997. }
  8998. }
  8999. function clickInGutter(cm, e) {
  9000. return gutterEvent(cm, e, "gutterClick", true)
  9001. }
  9002. // CONTEXT MENU HANDLING
  9003. // To make the context menu work, we need to briefly unhide the
  9004. // textarea (making it as unobtrusive as possible) to let the
  9005. // right-click take effect on it.
  9006. function onContextMenu(cm, e) {
  9007. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) {
  9008. return
  9009. }
  9010. if (signalDOMEvent(cm, e, "contextmenu")) {
  9011. return
  9012. }
  9013. if (!captureRightClick) {
  9014. cm.display.input.onContextMenu(e);
  9015. }
  9016. }
  9017. function contextMenuInGutter(cm, e) {
  9018. if (!hasHandler(cm, "gutterContextMenu")) {
  9019. return false
  9020. }
  9021. return gutterEvent(cm, e, "gutterContextMenu", false)
  9022. }
  9023. function themeChanged(cm) {
  9024. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  9025. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  9026. clearCaches(cm);
  9027. }
  9028. var Init = {
  9029. toString: function () {
  9030. return "CodeMirror.Init"
  9031. }
  9032. };
  9033. var defaults = {};
  9034. var optionHandlers = {};
  9035. function defineOptions(CodeMirror) {
  9036. var optionHandlers = CodeMirror.optionHandlers;
  9037. function option(name, deflt, handle, notOnInit) {
  9038. CodeMirror.defaults[name] = deflt;
  9039. if (handle) {
  9040. optionHandlers[name] =
  9041. notOnInit ? function (cm, val, old) {
  9042. if (old != Init) {
  9043. handle(cm, val, old);
  9044. }
  9045. } : handle;
  9046. }
  9047. }
  9048. CodeMirror.defineOption = option;
  9049. // Passed to option handlers when there is no old value.
  9050. CodeMirror.Init = Init;
  9051. // These two are, on init, called from the constructor because they
  9052. // have to be initialized before the editor can start at all.
  9053. option("value", "", function (cm, val) {
  9054. return cm.setValue(val);
  9055. }, true);
  9056. option("mode", null, function (cm, val) {
  9057. cm.doc.modeOption = val;
  9058. loadMode(cm);
  9059. }, true);
  9060. option("indentUnit", 2, loadMode, true);
  9061. option("indentWithTabs", false);
  9062. option("smartIndent", true);
  9063. option("tabSize", 4, function (cm) {
  9064. resetModeState(cm);
  9065. clearCaches(cm);
  9066. regChange(cm);
  9067. }, true);
  9068. option("lineSeparator", null, function (cm, val) {
  9069. cm.doc.lineSep = val;
  9070. if (!val) {
  9071. return
  9072. }
  9073. var newBreaks = [], lineNo = cm.doc.first;
  9074. cm.doc.iter(function (line) {
  9075. for (var pos = 0; ;) {
  9076. var found = line.text.indexOf(val, pos);
  9077. if (found == -1) {
  9078. break
  9079. }
  9080. pos = found + val.length;
  9081. newBreaks.push(Pos(lineNo, found));
  9082. }
  9083. lineNo++;
  9084. });
  9085. for (var i = newBreaks.length - 1; i >= 0; i--) {
  9086. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length));
  9087. }
  9088. });
  9089. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  9090. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  9091. if (old != Init) {
  9092. cm.refresh();
  9093. }
  9094. });
  9095. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) {
  9096. return cm.refresh();
  9097. }, true);
  9098. option("electricChars", true);
  9099. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  9100. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  9101. }, true);
  9102. option("spellcheck", false, function (cm, val) {
  9103. return cm.getInputField().spellcheck = val;
  9104. }, true);
  9105. option("autocorrect", false, function (cm, val) {
  9106. return cm.getInputField().autocorrect = val;
  9107. }, true);
  9108. option("autocapitalize", false, function (cm, val) {
  9109. return cm.getInputField().autocapitalize = val;
  9110. }, true);
  9111. option("rtlMoveVisually", !windows);
  9112. option("wholeLineUpdateBefore", true);
  9113. option("theme", "default", function (cm) {
  9114. themeChanged(cm);
  9115. updateGutters(cm);
  9116. }, true);
  9117. option("keyMap", "default", function (cm, val, old) {
  9118. var next = getKeyMap(val);
  9119. var prev = old != Init && getKeyMap(old);
  9120. if (prev && prev.detach) {
  9121. prev.detach(cm, next);
  9122. }
  9123. if (next.attach) {
  9124. next.attach(cm, prev || null);
  9125. }
  9126. });
  9127. option("extraKeys", null);
  9128. option("configureMouse", null);
  9129. option("lineWrapping", false, wrappingChanged, true);
  9130. option("gutters", [], function (cm, val) {
  9131. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  9132. updateGutters(cm);
  9133. }, true);
  9134. option("fixedGutter", true, function (cm, val) {
  9135. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  9136. cm.refresh();
  9137. }, true);
  9138. option("coverGutterNextToScrollbar", false, function (cm) {
  9139. return updateScrollbars(cm);
  9140. }, true);
  9141. option("scrollbarStyle", "native", function (cm) {
  9142. initScrollbars(cm);
  9143. updateScrollbars(cm);
  9144. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  9145. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  9146. }, true);
  9147. option("lineNumbers", false, function (cm, val) {
  9148. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  9149. updateGutters(cm);
  9150. }, true);
  9151. option("firstLineNumber", 1, updateGutters, true);
  9152. option("lineNumberFormatter", function (integer) {
  9153. return integer;
  9154. }, updateGutters, true);
  9155. option("showCursorWhenSelecting", false, updateSelection, true);
  9156. option("resetSelectionOnContextMenu", true);
  9157. option("lineWiseCopyCut", true);
  9158. option("pasteLinesPerSelection", true);
  9159. option("selectionsMayTouch", false);
  9160. option("readOnly", false, function (cm, val) {
  9161. if (val == "nocursor") {
  9162. onBlur(cm);
  9163. cm.display.input.blur();
  9164. }
  9165. cm.display.input.readOnlyChanged(val);
  9166. });
  9167. option("screenReaderLabel", null, function (cm, val) {
  9168. val = (val === '') ? null : val;
  9169. cm.display.input.screenReaderLabelChanged(val);
  9170. });
  9171. option("disableInput", false, function (cm, val) {
  9172. if (!val) {
  9173. cm.display.input.reset();
  9174. }
  9175. }, true);
  9176. option("dragDrop", true, dragDropChanged);
  9177. option("allowDropFileTypes", null);
  9178. option("cursorBlinkRate", 530);
  9179. option("cursorScrollMargin", 0);
  9180. option("cursorHeight", 1, updateSelection, true);
  9181. option("singleCursorHeightPerLine", true, updateSelection, true);
  9182. option("workTime", 100);
  9183. option("workDelay", 100);
  9184. option("flattenSpans", true, resetModeState, true);
  9185. option("addModeClass", false, resetModeState, true);
  9186. option("pollInterval", 100);
  9187. option("undoDepth", 200, function (cm, val) {
  9188. return cm.doc.history.undoDepth = val;
  9189. });
  9190. option("historyEventDelay", 1250);
  9191. option("viewportMargin", 10, function (cm) {
  9192. return cm.refresh();
  9193. }, true);
  9194. option("maxHighlightLength", 10000, resetModeState, true);
  9195. option("moveInputWithCursor", true, function (cm, val) {
  9196. if (!val) {
  9197. cm.display.input.resetPosition();
  9198. }
  9199. });
  9200. option("tabindex", null, function (cm, val) {
  9201. return cm.display.input.getField().tabIndex = val || "";
  9202. });
  9203. option("autofocus", null);
  9204. option("direction", "ltr", function (cm, val) {
  9205. return cm.doc.setDirection(val);
  9206. }, true);
  9207. option("phrases", null);
  9208. }
  9209. function dragDropChanged(cm, value, old) {
  9210. var wasOn = old && old != Init;
  9211. if (!value != !wasOn) {
  9212. var funcs = cm.display.dragFunctions;
  9213. var toggle = value ? on : off;
  9214. toggle(cm.display.scroller, "dragstart", funcs.start);
  9215. toggle(cm.display.scroller, "dragenter", funcs.enter);
  9216. toggle(cm.display.scroller, "dragover", funcs.over);
  9217. toggle(cm.display.scroller, "dragleave", funcs.leave);
  9218. toggle(cm.display.scroller, "drop", funcs.drop);
  9219. }
  9220. }
  9221. function wrappingChanged(cm) {
  9222. if (cm.options.lineWrapping) {
  9223. addClass(cm.display.wrapper, "CodeMirror-wrap");
  9224. cm.display.sizer.style.minWidth = "";
  9225. cm.display.sizerWidth = null;
  9226. } else {
  9227. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  9228. findMaxLine(cm);
  9229. }
  9230. estimateLineHeights(cm);
  9231. regChange(cm);
  9232. clearCaches(cm);
  9233. setTimeout(function () {
  9234. return updateScrollbars(cm);
  9235. }, 100);
  9236. }
  9237. // A CodeMirror instance represents an editor. This is the object
  9238. // that user code is usually dealing with.
  9239. function CodeMirror(place, options) {
  9240. var this$1 = this;
  9241. if (!(this instanceof CodeMirror)) {
  9242. return new CodeMirror(place, options)
  9243. }
  9244. this.options = options = options ? copyObj(options) : {};
  9245. // Determine effective options based on given values and defaults.
  9246. copyObj(defaults, options, false);
  9247. var doc = options.value;
  9248. if (typeof doc == "string") {
  9249. doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction);
  9250. } else if (options.mode) {
  9251. doc.modeOption = options.mode;
  9252. }
  9253. this.doc = doc;
  9254. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  9255. var display = this.display = new Display(place, doc, input, options);
  9256. display.wrapper.CodeMirror = this;
  9257. themeChanged(this);
  9258. if (options.lineWrapping) {
  9259. this.display.wrapper.className += " CodeMirror-wrap";
  9260. }
  9261. initScrollbars(this);
  9262. this.state = {
  9263. keyMaps: [], // stores maps added by addKeyMap
  9264. overlays: [], // highlighting overlays, as added by addOverlay
  9265. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  9266. overwrite: false,
  9267. delayingBlurEvent: false,
  9268. focused: false,
  9269. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  9270. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  9271. selectingText: false,
  9272. draggingText: false,
  9273. highlight: new Delayed(), // stores highlight worker timeout
  9274. keySeq: null, // Unfinished key sequence
  9275. specialChars: null
  9276. };
  9277. if (options.autofocus && !mobile) {
  9278. display.input.focus();
  9279. }
  9280. // Override magic textarea content restore that IE sometimes does
  9281. // on our hidden textarea on reload
  9282. if (ie && ie_version < 11) {
  9283. setTimeout(function () {
  9284. return this$1.display.input.reset(true);
  9285. }, 20);
  9286. }
  9287. registerEventHandlers(this);
  9288. ensureGlobalHandlers();
  9289. startOperation(this);
  9290. this.curOp.forceUpdate = true;
  9291. attachDoc(this, doc);
  9292. if ((options.autofocus && !mobile) || this.hasFocus()) {
  9293. setTimeout(function () {
  9294. if (this$1.hasFocus() && !this$1.state.focused) {
  9295. onFocus(this$1);
  9296. }
  9297. }, 20);
  9298. } else {
  9299. onBlur(this);
  9300. }
  9301. for (var opt in optionHandlers) {
  9302. if (optionHandlers.hasOwnProperty(opt)) {
  9303. optionHandlers[opt](this, options[opt], Init);
  9304. }
  9305. }
  9306. maybeUpdateLineNumberWidth(this);
  9307. if (options.finishInit) {
  9308. options.finishInit(this);
  9309. }
  9310. for (var i = 0; i < initHooks.length; ++i) {
  9311. initHooks[i](this);
  9312. }
  9313. endOperation(this);
  9314. // Suppress optimizelegibility in Webkit, since it breaks text
  9315. // measuring on line wrapping boundaries.
  9316. if (webkit && options.lineWrapping &&
  9317. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") {
  9318. display.lineDiv.style.textRendering = "auto";
  9319. }
  9320. }
  9321. // The default configuration options.
  9322. CodeMirror.defaults = defaults;
  9323. // Functions to run when options are changed.
  9324. CodeMirror.optionHandlers = optionHandlers;
  9325. // Attach the necessary event handlers when initializing the editor
  9326. function registerEventHandlers(cm) {
  9327. var d = cm.display;
  9328. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  9329. // Older IE's will not fire a second mousedown for a double click
  9330. if (ie && ie_version < 11) {
  9331. on(d.scroller, "dblclick", operation(cm, function (e) {
  9332. if (signalDOMEvent(cm, e)) {
  9333. return
  9334. }
  9335. var pos = posFromMouse(cm, e);
  9336. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) {
  9337. return
  9338. }
  9339. e_preventDefault(e);
  9340. var word = cm.findWordAt(pos);
  9341. extendSelection(cm.doc, word.anchor, word.head);
  9342. }));
  9343. } else {
  9344. on(d.scroller, "dblclick", function (e) {
  9345. return signalDOMEvent(cm, e) || e_preventDefault(e);
  9346. });
  9347. }
  9348. // Some browsers fire contextmenu *after* opening the menu, at
  9349. // which point we can't mess with it anymore. Context menu is
  9350. // handled in onMouseDown for these browsers.
  9351. on(d.scroller, "contextmenu", function (e) {
  9352. return onContextMenu(cm, e);
  9353. });
  9354. on(d.input.getField(), "contextmenu", function (e) {
  9355. if (!d.scroller.contains(e.target)) {
  9356. onContextMenu(cm, e);
  9357. }
  9358. });
  9359. // Used to suppress mouse event handling when a touch happens
  9360. var touchFinished, prevTouch = {end: 0};
  9361. function finishTouch() {
  9362. if (d.activeTouch) {
  9363. touchFinished = setTimeout(function () {
  9364. return d.activeTouch = null;
  9365. }, 1000);
  9366. prevTouch = d.activeTouch;
  9367. prevTouch.end = +new Date;
  9368. }
  9369. }
  9370. function isMouseLikeTouchEvent(e) {
  9371. if (e.touches.length != 1) {
  9372. return false
  9373. }
  9374. var touch = e.touches[0];
  9375. return touch.radiusX <= 1 && touch.radiusY <= 1
  9376. }
  9377. function farAway(touch, other) {
  9378. if (other.left == null) {
  9379. return true
  9380. }
  9381. var dx = other.left - touch.left, dy = other.top - touch.top;
  9382. return dx * dx + dy * dy > 20 * 20
  9383. }
  9384. on(d.scroller, "touchstart", function (e) {
  9385. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  9386. d.input.ensurePolled();
  9387. clearTimeout(touchFinished);
  9388. var now = +new Date;
  9389. d.activeTouch = {
  9390. start: now, moved: false,
  9391. prev: now - prevTouch.end <= 300 ? prevTouch : null
  9392. };
  9393. if (e.touches.length == 1) {
  9394. d.activeTouch.left = e.touches[0].pageX;
  9395. d.activeTouch.top = e.touches[0].pageY;
  9396. }
  9397. }
  9398. });
  9399. on(d.scroller, "touchmove", function () {
  9400. if (d.activeTouch) {
  9401. d.activeTouch.moved = true;
  9402. }
  9403. });
  9404. on(d.scroller, "touchend", function (e) {
  9405. var touch = d.activeTouch;
  9406. if (touch && !eventInWidget(d, e) && touch.left != null &&
  9407. !touch.moved && new Date - touch.start < 300) {
  9408. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  9409. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  9410. {
  9411. range = new Range(pos, pos);
  9412. } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  9413. {
  9414. range = cm.findWordAt(pos);
  9415. } else // Triple tap
  9416. {
  9417. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  9418. }
  9419. cm.setSelection(range.anchor, range.head);
  9420. cm.focus();
  9421. e_preventDefault(e);
  9422. }
  9423. finishTouch();
  9424. });
  9425. on(d.scroller, "touchcancel", finishTouch);
  9426. // Sync scrolling between fake scrollbars and real scrollable
  9427. // area, ensure viewport is updated when scrolling.
  9428. on(d.scroller, "scroll", function () {
  9429. if (d.scroller.clientHeight) {
  9430. updateScrollTop(cm, d.scroller.scrollTop);
  9431. setScrollLeft(cm, d.scroller.scrollLeft, true);
  9432. signal(cm, "scroll", cm);
  9433. }
  9434. });
  9435. // Listen to wheel events in order to try and update the viewport on time.
  9436. on(d.scroller, "mousewheel", function (e) {
  9437. return onScrollWheel(cm, e);
  9438. });
  9439. on(d.scroller, "DOMMouseScroll", function (e) {
  9440. return onScrollWheel(cm, e);
  9441. });
  9442. // Prevent wrapper from ever scrolling
  9443. on(d.wrapper, "scroll", function () {
  9444. return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0;
  9445. });
  9446. d.dragFunctions = {
  9447. enter: function (e) {
  9448. if (!signalDOMEvent(cm, e)) {
  9449. e_stop(e);
  9450. }
  9451. },
  9452. over: function (e) {
  9453. if (!signalDOMEvent(cm, e)) {
  9454. onDragOver(cm, e);
  9455. e_stop(e);
  9456. }
  9457. },
  9458. start: function (e) {
  9459. return onDragStart(cm, e);
  9460. },
  9461. drop: operation(cm, onDrop),
  9462. leave: function (e) {
  9463. if (!signalDOMEvent(cm, e)) {
  9464. clearDragCursor(cm);
  9465. }
  9466. }
  9467. };
  9468. var inp = d.input.getField();
  9469. on(inp, "keyup", function (e) {
  9470. return onKeyUp.call(cm, e);
  9471. });
  9472. on(inp, "keydown", operation(cm, onKeyDown));
  9473. on(inp, "keypress", operation(cm, onKeyPress));
  9474. on(inp, "focus", function (e) {
  9475. return onFocus(cm, e);
  9476. });
  9477. on(inp, "blur", function (e) {
  9478. return onBlur(cm, e);
  9479. });
  9480. }
  9481. var initHooks = [];
  9482. CodeMirror.defineInitHook = function (f) {
  9483. return initHooks.push(f);
  9484. };
  9485. // Indent the given line. The how parameter can be "smart",
  9486. // "add"/null, "subtract", or "prev". When aggressive is false
  9487. // (typically set to true for forced single-line indents), empty
  9488. // lines are not indented, and places where the mode returns Pass
  9489. // are left alone.
  9490. function indentLine(cm, n, how, aggressive) {
  9491. var doc = cm.doc, state;
  9492. if (how == null) {
  9493. how = "add";
  9494. }
  9495. if (how == "smart") {
  9496. // Fall back to "prev" when the mode doesn't have an indentation
  9497. // method.
  9498. if (!doc.mode.indent) {
  9499. how = "prev";
  9500. } else {
  9501. state = getContextBefore(cm, n).state;
  9502. }
  9503. }
  9504. var tabSize = cm.options.tabSize;
  9505. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  9506. if (line.stateAfter) {
  9507. line.stateAfter = null;
  9508. }
  9509. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  9510. if (!aggressive && !/\S/.test(line.text)) {
  9511. indentation = 0;
  9512. how = "not";
  9513. } else if (how == "smart") {
  9514. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  9515. if (indentation == Pass || indentation > 150) {
  9516. if (!aggressive) {
  9517. return
  9518. }
  9519. how = "prev";
  9520. }
  9521. }
  9522. if (how == "prev") {
  9523. if (n > doc.first) {
  9524. indentation = countColumn(getLine(doc, n - 1).text, null, tabSize);
  9525. } else {
  9526. indentation = 0;
  9527. }
  9528. } else if (how == "add") {
  9529. indentation = curSpace + cm.options.indentUnit;
  9530. } else if (how == "subtract") {
  9531. indentation = curSpace - cm.options.indentUnit;
  9532. } else if (typeof how == "number") {
  9533. indentation = curSpace + how;
  9534. }
  9535. indentation = Math.max(0, indentation);
  9536. var indentString = "", pos = 0;
  9537. if (cm.options.indentWithTabs) {
  9538. for (var i = Math.floor(indentation / tabSize); i; --i) {
  9539. pos += tabSize;
  9540. indentString += "\t";
  9541. }
  9542. }
  9543. if (pos < indentation) {
  9544. indentString += spaceStr(indentation - pos);
  9545. }
  9546. if (indentString != curSpaceString) {
  9547. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  9548. line.stateAfter = null;
  9549. return true
  9550. } else {
  9551. // Ensure that, if the cursor was in the whitespace at the start
  9552. // of the line, it is moved to the end of that space.
  9553. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  9554. var range = doc.sel.ranges[i$1];
  9555. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  9556. var pos$1 = Pos(n, curSpaceString.length);
  9557. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  9558. break
  9559. }
  9560. }
  9561. }
  9562. }
  9563. // This will be set to a {lineWise: bool, text: [string]} object, so
  9564. // that, when pasting, we know what kind of selections the copied
  9565. // text was made out of.
  9566. var lastCopied = null;
  9567. function setLastCopied(newLastCopied) {
  9568. lastCopied = newLastCopied;
  9569. }
  9570. function applyTextInput(cm, inserted, deleted, sel, origin) {
  9571. var doc = cm.doc;
  9572. cm.display.shift = false;
  9573. if (!sel) {
  9574. sel = doc.sel;
  9575. }
  9576. var recent = +new Date - 200;
  9577. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  9578. var textLines = splitLinesAuto(inserted), multiPaste = null;
  9579. // When pasting N lines into N selections, insert one line per selection
  9580. if (paste && sel.ranges.length > 1) {
  9581. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  9582. if (sel.ranges.length % lastCopied.text.length == 0) {
  9583. multiPaste = [];
  9584. for (var i = 0; i < lastCopied.text.length; i++) {
  9585. multiPaste.push(doc.splitLines(lastCopied.text[i]));
  9586. }
  9587. }
  9588. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  9589. multiPaste = map(textLines, function (l) {
  9590. return [l];
  9591. });
  9592. }
  9593. }
  9594. var updateInput = cm.curOp.updateInput;
  9595. // Normal behavior is to insert the new text into every selection
  9596. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  9597. var range = sel.ranges[i$1];
  9598. var from = range.from(), to = range.to();
  9599. if (range.empty()) {
  9600. if (deleted && deleted > 0) // Handle deletion
  9601. {
  9602. from = Pos(from.line, from.ch - deleted);
  9603. } else if (cm.state.overwrite && !paste) // Handle overwrite
  9604. {
  9605. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  9606. } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) {
  9607. from = to = Pos(from.line, 0);
  9608. }
  9609. }
  9610. var changeEvent = {
  9611. from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  9612. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")
  9613. };
  9614. makeChange(cm.doc, changeEvent);
  9615. signalLater(cm, "inputRead", cm, changeEvent);
  9616. }
  9617. if (inserted && !paste) {
  9618. triggerElectric(cm, inserted);
  9619. }
  9620. ensureCursorVisible(cm);
  9621. if (cm.curOp.updateInput < 2) {
  9622. cm.curOp.updateInput = updateInput;
  9623. }
  9624. cm.curOp.typing = true;
  9625. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  9626. }
  9627. function handlePaste(e, cm) {
  9628. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  9629. if (pasted) {
  9630. e.preventDefault();
  9631. if (!cm.isReadOnly() && !cm.options.disableInput) {
  9632. runInOp(cm, function () {
  9633. return applyTextInput(cm, pasted, 0, null, "paste");
  9634. });
  9635. }
  9636. return true
  9637. }
  9638. }
  9639. function triggerElectric(cm, inserted) {
  9640. // When an 'electric' character is inserted, immediately trigger a reindent
  9641. if (!cm.options.electricChars || !cm.options.smartIndent) {
  9642. return
  9643. }
  9644. var sel = cm.doc.sel;
  9645. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  9646. var range = sel.ranges[i];
  9647. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) {
  9648. continue
  9649. }
  9650. var mode = cm.getModeAt(range.head);
  9651. var indented = false;
  9652. if (mode.electricChars) {
  9653. for (var j = 0; j < mode.electricChars.length; j++) {
  9654. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  9655. indented = indentLine(cm, range.head.line, "smart");
  9656. break
  9657. }
  9658. }
  9659. } else if (mode.electricInput) {
  9660. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) {
  9661. indented = indentLine(cm, range.head.line, "smart");
  9662. }
  9663. }
  9664. if (indented) {
  9665. signalLater(cm, "electricInput", cm, range.head.line);
  9666. }
  9667. }
  9668. }
  9669. function copyableRanges(cm) {
  9670. var text = [], ranges = [];
  9671. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  9672. var line = cm.doc.sel.ranges[i].head.line;
  9673. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  9674. ranges.push(lineRange);
  9675. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  9676. }
  9677. return {text: text, ranges: ranges}
  9678. }
  9679. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  9680. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  9681. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  9682. field.setAttribute("spellcheck", !!spellcheck);
  9683. }
  9684. function hiddenTextarea() {
  9685. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  9686. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  9687. // The textarea is kept positioned near the cursor to prevent the
  9688. // fact that it'll be scrolled into view on input from scrolling
  9689. // our fake cursor out of view. On webkit, when wrap=off, paste is
  9690. // very slow. So make the area wide instead.
  9691. if (webkit) {
  9692. te.style.width = "1000px";
  9693. } else {
  9694. te.setAttribute("wrap", "off");
  9695. }
  9696. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  9697. if (ios) {
  9698. te.style.border = "1px solid black";
  9699. }
  9700. disableBrowserMagic(te);
  9701. return div
  9702. }
  9703. // The publicly visible API. Note that methodOp(f) means
  9704. // 'wrap f in an operation, performed on its `this` parameter'.
  9705. // This is not the complete set of editor methods. Most of the
  9706. // methods defined on the Doc type are also injected into
  9707. // CodeMirror.prototype, for backwards compatibility and
  9708. // convenience.
  9709. function addEditorMethods(CodeMirror) {
  9710. var optionHandlers = CodeMirror.optionHandlers;
  9711. var helpers = CodeMirror.helpers = {};
  9712. CodeMirror.prototype = {
  9713. constructor: CodeMirror,
  9714. focus: function () {
  9715. window.focus();
  9716. this.display.input.focus();
  9717. },
  9718. setOption: function (option, value) {
  9719. var options = this.options, old = options[option];
  9720. if (options[option] == value && option != "mode") {
  9721. return
  9722. }
  9723. options[option] = value;
  9724. if (optionHandlers.hasOwnProperty(option)) {
  9725. operation(this, optionHandlers[option])(this, value, old);
  9726. }
  9727. signal(this, "optionChange", this, option);
  9728. },
  9729. getOption: function (option) {
  9730. return this.options[option]
  9731. },
  9732. getDoc: function () {
  9733. return this.doc
  9734. },
  9735. addKeyMap: function (map, bottom) {
  9736. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  9737. },
  9738. removeKeyMap: function (map) {
  9739. var maps = this.state.keyMaps;
  9740. for (var i = 0; i < maps.length; ++i) {
  9741. if (maps[i] == map || maps[i].name == map) {
  9742. maps.splice(i, 1);
  9743. return true
  9744. }
  9745. }
  9746. },
  9747. addOverlay: methodOp(function (spec, options) {
  9748. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  9749. if (mode.startState) {
  9750. throw new Error("Overlays may not be stateful.")
  9751. }
  9752. insertSorted(this.state.overlays,
  9753. {
  9754. mode: mode, modeSpec: spec, opaque: options && options.opaque,
  9755. priority: (options && options.priority) || 0
  9756. },
  9757. function (overlay) {
  9758. return overlay.priority;
  9759. });
  9760. this.state.modeGen++;
  9761. regChange(this);
  9762. }),
  9763. removeOverlay: methodOp(function (spec) {
  9764. var overlays = this.state.overlays;
  9765. for (var i = 0; i < overlays.length; ++i) {
  9766. var cur = overlays[i].modeSpec;
  9767. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  9768. overlays.splice(i, 1);
  9769. this.state.modeGen++;
  9770. regChange(this);
  9771. return
  9772. }
  9773. }
  9774. }),
  9775. indentLine: methodOp(function (n, dir, aggressive) {
  9776. if (typeof dir != "string" && typeof dir != "number") {
  9777. if (dir == null) {
  9778. dir = this.options.smartIndent ? "smart" : "prev";
  9779. } else {
  9780. dir = dir ? "add" : "subtract";
  9781. }
  9782. }
  9783. if (isLine(this.doc, n)) {
  9784. indentLine(this, n, dir, aggressive);
  9785. }
  9786. }),
  9787. indentSelection: methodOp(function (how) {
  9788. var ranges = this.doc.sel.ranges, end = -1;
  9789. for (var i = 0; i < ranges.length; i++) {
  9790. var range = ranges[i];
  9791. if (!range.empty()) {
  9792. var from = range.from(), to = range.to();
  9793. var start = Math.max(end, from.line);
  9794. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  9795. for (var j = start; j < end; ++j) {
  9796. indentLine(this, j, how);
  9797. }
  9798. var newRanges = this.doc.sel.ranges;
  9799. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) {
  9800. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  9801. }
  9802. } else if (range.head.line > end) {
  9803. indentLine(this, range.head.line, how, true);
  9804. end = range.head.line;
  9805. if (i == this.doc.sel.primIndex) {
  9806. ensureCursorVisible(this);
  9807. }
  9808. }
  9809. }
  9810. }),
  9811. // Fetch the parser token for a given character. Useful for hacks
  9812. // that want to inspect the mode state (say, for completion).
  9813. getTokenAt: function (pos, precise) {
  9814. return takeToken(this, pos, precise)
  9815. },
  9816. getLineTokens: function (line, precise) {
  9817. return takeToken(this, Pos(line), precise, true)
  9818. },
  9819. getTokenTypeAt: function (pos) {
  9820. pos = clipPos(this.doc, pos);
  9821. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  9822. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  9823. var type;
  9824. if (ch == 0) {
  9825. type = styles[2];
  9826. } else {
  9827. for (; ;) {
  9828. var mid = (before + after) >> 1;
  9829. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) {
  9830. after = mid;
  9831. } else if (styles[mid * 2 + 1] < ch) {
  9832. before = mid + 1;
  9833. } else {
  9834. type = styles[mid * 2 + 2];
  9835. break
  9836. }
  9837. }
  9838. }
  9839. var cut = type ? type.indexOf("overlay ") : -1;
  9840. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  9841. },
  9842. getModeAt: function (pos) {
  9843. var mode = this.doc.mode;
  9844. if (!mode.innerMode) {
  9845. return mode
  9846. }
  9847. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  9848. },
  9849. getHelper: function (pos, type) {
  9850. return this.getHelpers(pos, type)[0]
  9851. },
  9852. getHelpers: function (pos, type) {
  9853. var found = [];
  9854. if (!helpers.hasOwnProperty(type)) {
  9855. return found
  9856. }
  9857. var help = helpers[type], mode = this.getModeAt(pos);
  9858. if (typeof mode[type] == "string") {
  9859. if (help[mode[type]]) {
  9860. found.push(help[mode[type]]);
  9861. }
  9862. } else if (mode[type]) {
  9863. for (var i = 0; i < mode[type].length; i++) {
  9864. var val = help[mode[type][i]];
  9865. if (val) {
  9866. found.push(val);
  9867. }
  9868. }
  9869. } else if (mode.helperType && help[mode.helperType]) {
  9870. found.push(help[mode.helperType]);
  9871. } else if (help[mode.name]) {
  9872. found.push(help[mode.name]);
  9873. }
  9874. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  9875. var cur = help._global[i$1];
  9876. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) {
  9877. found.push(cur.val);
  9878. }
  9879. }
  9880. return found
  9881. },
  9882. getStateAfter: function (line, precise) {
  9883. var doc = this.doc;
  9884. line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line);
  9885. return getContextBefore(this, line + 1, precise).state
  9886. },
  9887. cursorCoords: function (start, mode) {
  9888. var pos, range = this.doc.sel.primary();
  9889. if (start == null) {
  9890. pos = range.head;
  9891. } else if (typeof start == "object") {
  9892. pos = clipPos(this.doc, start);
  9893. } else {
  9894. pos = start ? range.from() : range.to();
  9895. }
  9896. return cursorCoords(this, pos, mode || "page")
  9897. },
  9898. charCoords: function (pos, mode) {
  9899. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  9900. },
  9901. coordsChar: function (coords, mode) {
  9902. coords = fromCoordSystem(this, coords, mode || "page");
  9903. return coordsChar(this, coords.left, coords.top)
  9904. },
  9905. lineAtHeight: function (height, mode) {
  9906. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  9907. return lineAtHeight(this.doc, height + this.display.viewOffset)
  9908. },
  9909. heightAtLine: function (line, mode, includeWidgets) {
  9910. var end = false, lineObj;
  9911. if (typeof line == "number") {
  9912. var last = this.doc.first + this.doc.size - 1;
  9913. if (line < this.doc.first) {
  9914. line = this.doc.first;
  9915. } else if (line > last) {
  9916. line = last;
  9917. end = true;
  9918. }
  9919. lineObj = getLine(this.doc, line);
  9920. } else {
  9921. lineObj = line;
  9922. }
  9923. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  9924. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  9925. },
  9926. defaultTextHeight: function () {
  9927. return textHeight(this.display)
  9928. },
  9929. defaultCharWidth: function () {
  9930. return charWidth(this.display)
  9931. },
  9932. getViewport: function () {
  9933. return {from: this.display.viewFrom, to: this.display.viewTo}
  9934. },
  9935. addWidget: function (pos, node, scroll, vert, horiz) {
  9936. var display = this.display;
  9937. pos = cursorCoords(this, clipPos(this.doc, pos));
  9938. var top = pos.bottom, left = pos.left;
  9939. node.style.position = "absolute";
  9940. node.setAttribute("cm-ignore-events", "true");
  9941. this.display.input.setUneditable(node);
  9942. display.sizer.appendChild(node);
  9943. if (vert == "over") {
  9944. top = pos.top;
  9945. } else if (vert == "above" || vert == "near") {
  9946. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  9947. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  9948. // Default to positioning above (if specified and possible); otherwise default to positioning below
  9949. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {
  9950. top = pos.top - node.offsetHeight;
  9951. } else if (pos.bottom + node.offsetHeight <= vspace) {
  9952. top = pos.bottom;
  9953. }
  9954. if (left + node.offsetWidth > hspace) {
  9955. left = hspace - node.offsetWidth;
  9956. }
  9957. }
  9958. node.style.top = top + "px";
  9959. node.style.left = node.style.right = "";
  9960. if (horiz == "right") {
  9961. left = display.sizer.clientWidth - node.offsetWidth;
  9962. node.style.right = "0px";
  9963. } else {
  9964. if (horiz == "left") {
  9965. left = 0;
  9966. } else if (horiz == "middle") {
  9967. left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  9968. }
  9969. node.style.left = left + "px";
  9970. }
  9971. if (scroll) {
  9972. scrollIntoView(this, {
  9973. left: left,
  9974. top: top,
  9975. right: left + node.offsetWidth,
  9976. bottom: top + node.offsetHeight
  9977. });
  9978. }
  9979. },
  9980. triggerOnKeyDown: methodOp(onKeyDown),
  9981. triggerOnKeyPress: methodOp(onKeyPress),
  9982. triggerOnKeyUp: onKeyUp,
  9983. triggerOnMouseDown: methodOp(onMouseDown),
  9984. execCommand: function (cmd) {
  9985. if (commands.hasOwnProperty(cmd)) {
  9986. return commands[cmd].call(null, this)
  9987. }
  9988. },
  9989. triggerElectric: methodOp(function (text) {
  9990. triggerElectric(this, text);
  9991. }),
  9992. findPosH: function (from, amount, unit, visually) {
  9993. var dir = 1;
  9994. if (amount < 0) {
  9995. dir = -1;
  9996. amount = -amount;
  9997. }
  9998. var cur = clipPos(this.doc, from);
  9999. for (var i = 0; i < amount; ++i) {
  10000. cur = findPosH(this.doc, cur, dir, unit, visually);
  10001. if (cur.hitSide) {
  10002. break
  10003. }
  10004. }
  10005. return cur
  10006. },
  10007. moveH: methodOp(function (dir, unit) {
  10008. var this$1 = this;
  10009. this.extendSelectionsBy(function (range) {
  10010. if (this$1.display.shift || this$1.doc.extend || range.empty()) {
  10011. return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually)
  10012. } else {
  10013. return dir < 0 ? range.from() : range.to()
  10014. }
  10015. }, sel_move);
  10016. }),
  10017. deleteH: methodOp(function (dir, unit) {
  10018. var sel = this.doc.sel, doc = this.doc;
  10019. if (sel.somethingSelected()) {
  10020. doc.replaceSelection("", null, "+delete");
  10021. } else {
  10022. deleteNearSelection(this, function (range) {
  10023. var other = findPosH(doc, range.head, dir, unit, false);
  10024. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  10025. });
  10026. }
  10027. }),
  10028. findPosV: function (from, amount, unit, goalColumn) {
  10029. var dir = 1, x = goalColumn;
  10030. if (amount < 0) {
  10031. dir = -1;
  10032. amount = -amount;
  10033. }
  10034. var cur = clipPos(this.doc, from);
  10035. for (var i = 0; i < amount; ++i) {
  10036. var coords = cursorCoords(this, cur, "div");
  10037. if (x == null) {
  10038. x = coords.left;
  10039. } else {
  10040. coords.left = x;
  10041. }
  10042. cur = findPosV(this, coords, dir, unit);
  10043. if (cur.hitSide) {
  10044. break
  10045. }
  10046. }
  10047. return cur
  10048. },
  10049. moveV: methodOp(function (dir, unit) {
  10050. var this$1 = this;
  10051. var doc = this.doc, goals = [];
  10052. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  10053. doc.extendSelectionsBy(function (range) {
  10054. if (collapse) {
  10055. return dir < 0 ? range.from() : range.to()
  10056. }
  10057. var headPos = cursorCoords(this$1, range.head, "div");
  10058. if (range.goalColumn != null) {
  10059. headPos.left = range.goalColumn;
  10060. }
  10061. goals.push(headPos.left);
  10062. var pos = findPosV(this$1, headPos, dir, unit);
  10063. if (unit == "page" && range == doc.sel.primary()) {
  10064. addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top);
  10065. }
  10066. return pos
  10067. }, sel_move);
  10068. if (goals.length) {
  10069. for (var i = 0; i < doc.sel.ranges.length; i++) {
  10070. doc.sel.ranges[i].goalColumn = goals[i];
  10071. }
  10072. }
  10073. }),
  10074. // Find the word at the given position (as returned by coordsChar).
  10075. findWordAt: function (pos) {
  10076. var doc = this.doc, line = getLine(doc, pos.line).text;
  10077. var start = pos.ch, end = pos.ch;
  10078. if (line) {
  10079. var helper = this.getHelper(pos, "wordChars");
  10080. if ((pos.sticky == "before" || end == line.length) && start) {
  10081. --start;
  10082. } else {
  10083. ++end;
  10084. }
  10085. var startChar = line.charAt(start);
  10086. var check = isWordChar(startChar, helper)
  10087. ? function (ch) {
  10088. return isWordChar(ch, helper);
  10089. }
  10090. : /\s/.test(startChar) ? function (ch) {
  10091. return /\s/.test(ch);
  10092. }
  10093. : function (ch) {
  10094. return (!/\s/.test(ch) && !isWordChar(ch));
  10095. };
  10096. while (start > 0 && check(line.charAt(start - 1))) {
  10097. --start;
  10098. }
  10099. while (end < line.length && check(line.charAt(end))) {
  10100. ++end;
  10101. }
  10102. }
  10103. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  10104. },
  10105. toggleOverwrite: function (value) {
  10106. if (value != null && value == this.state.overwrite) {
  10107. return
  10108. }
  10109. if (this.state.overwrite = !this.state.overwrite) {
  10110. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  10111. } else {
  10112. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  10113. }
  10114. signal(this, "overwriteToggle", this, this.state.overwrite);
  10115. },
  10116. hasFocus: function () {
  10117. return this.display.input.getField() == activeElt()
  10118. },
  10119. isReadOnly: function () {
  10120. return !!(this.options.readOnly || this.doc.cantEdit)
  10121. },
  10122. scrollTo: methodOp(function (x, y) {
  10123. scrollToCoords(this, x, y);
  10124. }),
  10125. getScrollInfo: function () {
  10126. var scroller = this.display.scroller;
  10127. return {
  10128. left: scroller.scrollLeft, top: scroller.scrollTop,
  10129. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  10130. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  10131. clientHeight: displayHeight(this), clientWidth: displayWidth(this)
  10132. }
  10133. },
  10134. scrollIntoView: methodOp(function (range, margin) {
  10135. if (range == null) {
  10136. range = {from: this.doc.sel.primary().head, to: null};
  10137. if (margin == null) {
  10138. margin = this.options.cursorScrollMargin;
  10139. }
  10140. } else if (typeof range == "number") {
  10141. range = {from: Pos(range, 0), to: null};
  10142. } else if (range.from == null) {
  10143. range = {from: range, to: null};
  10144. }
  10145. if (!range.to) {
  10146. range.to = range.from;
  10147. }
  10148. range.margin = margin || 0;
  10149. if (range.from.line != null) {
  10150. scrollToRange(this, range);
  10151. } else {
  10152. scrollToCoordsRange(this, range.from, range.to, range.margin);
  10153. }
  10154. }),
  10155. setSize: methodOp(function (width, height) {
  10156. var this$1 = this;
  10157. var interpret = function (val) {
  10158. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  10159. };
  10160. if (width != null) {
  10161. this.display.wrapper.style.width = interpret(width);
  10162. }
  10163. if (height != null) {
  10164. this.display.wrapper.style.height = interpret(height);
  10165. }
  10166. if (this.options.lineWrapping) {
  10167. clearLineMeasurementCache(this);
  10168. }
  10169. var lineNo = this.display.viewFrom;
  10170. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  10171. if (line.widgets) {
  10172. for (var i = 0; i < line.widgets.length; i++) {
  10173. if (line.widgets[i].noHScroll) {
  10174. regLineChange(this$1, lineNo, "widget");
  10175. break
  10176. }
  10177. }
  10178. }
  10179. ++lineNo;
  10180. });
  10181. this.curOp.forceUpdate = true;
  10182. signal(this, "refresh", this);
  10183. }),
  10184. operation: function (f) {
  10185. return runInOp(this, f)
  10186. },
  10187. startOperation: function () {
  10188. return startOperation(this)
  10189. },
  10190. endOperation: function () {
  10191. return endOperation(this)
  10192. },
  10193. refresh: methodOp(function () {
  10194. var oldHeight = this.display.cachedTextHeight;
  10195. regChange(this);
  10196. this.curOp.forceUpdate = true;
  10197. clearCaches(this);
  10198. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  10199. updateGutterSpace(this.display);
  10200. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping) {
  10201. estimateLineHeights(this);
  10202. }
  10203. signal(this, "refresh", this);
  10204. }),
  10205. swapDoc: methodOp(function (doc) {
  10206. var old = this.doc;
  10207. old.cm = null;
  10208. // Cancel the current text selection if any (#5821)
  10209. if (this.state.selectingText) {
  10210. this.state.selectingText();
  10211. }
  10212. attachDoc(this, doc);
  10213. clearCaches(this);
  10214. this.display.input.reset();
  10215. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  10216. this.curOp.forceScroll = true;
  10217. signalLater(this, "swapDoc", this, old);
  10218. return old
  10219. }),
  10220. phrase: function (phraseText) {
  10221. var phrases = this.options.phrases;
  10222. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  10223. },
  10224. getInputField: function () {
  10225. return this.display.input.getField()
  10226. },
  10227. getWrapperElement: function () {
  10228. return this.display.wrapper
  10229. },
  10230. getScrollerElement: function () {
  10231. return this.display.scroller
  10232. },
  10233. getGutterElement: function () {
  10234. return this.display.gutters
  10235. }
  10236. };
  10237. eventMixin(CodeMirror);
  10238. CodeMirror.registerHelper = function (type, name, value) {
  10239. if (!helpers.hasOwnProperty(type)) {
  10240. helpers[type] = CodeMirror[type] = {_global: []};
  10241. }
  10242. helpers[type][name] = value;
  10243. };
  10244. CodeMirror.registerGlobalHelper = function (type, name, predicate, value) {
  10245. CodeMirror.registerHelper(type, name, value);
  10246. helpers[type]._global.push({pred: predicate, val: value});
  10247. };
  10248. }
  10249. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  10250. // right), unit can be "codepoint", "char", "column" (like char, but
  10251. // doesn't cross line boundaries), "word" (across next word), or
  10252. // "group" (to the start of next group of word or
  10253. // non-word-non-whitespace chars). The visually param controls
  10254. // whether, in right-to-left text, direction 1 means to move towards
  10255. // the next index in the string, or towards the character to the right
  10256. // of the current position. The resulting position will have a
  10257. // hitSide=true property if it reached the end of the document.
  10258. function findPosH(doc, pos, dir, unit, visually) {
  10259. var oldPos = pos;
  10260. var origDir = dir;
  10261. var lineObj = getLine(doc, pos.line);
  10262. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  10263. function findNextLine() {
  10264. var l = pos.line + lineDir;
  10265. if (l < doc.first || l >= doc.first + doc.size) {
  10266. return false
  10267. }
  10268. pos = new Pos(l, pos.ch, pos.sticky);
  10269. return lineObj = getLine(doc, l)
  10270. }
  10271. function moveOnce(boundToLine) {
  10272. var next;
  10273. if (unit == "codepoint") {
  10274. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  10275. if (isNaN(ch)) {
  10276. next = null;
  10277. } else {
  10278. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  10279. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  10280. }
  10281. } else if (visually) {
  10282. next = moveVisually(doc.cm, lineObj, pos, dir);
  10283. } else {
  10284. next = moveLogically(lineObj, pos, dir);
  10285. }
  10286. if (next == null) {
  10287. if (!boundToLine && findNextLine()) {
  10288. pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir);
  10289. } else {
  10290. return false
  10291. }
  10292. } else {
  10293. pos = next;
  10294. }
  10295. return true
  10296. }
  10297. if (unit == "char" || unit == "codepoint") {
  10298. moveOnce();
  10299. } else if (unit == "column") {
  10300. moveOnce(true);
  10301. } else if (unit == "word" || unit == "group") {
  10302. var sawType = null, group = unit == "group";
  10303. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  10304. for (var first = true; ; first = false) {
  10305. if (dir < 0 && !moveOnce(!first)) {
  10306. break
  10307. }
  10308. var cur = lineObj.text.charAt(pos.ch) || "\n";
  10309. var type = isWordChar(cur, helper) ? "w"
  10310. : group && cur == "\n" ? "n"
  10311. : !group || /\s/.test(cur) ? null
  10312. : "p";
  10313. if (group && !first && !type) {
  10314. type = "s";
  10315. }
  10316. if (sawType && sawType != type) {
  10317. if (dir < 0) {
  10318. dir = 1;
  10319. moveOnce();
  10320. pos.sticky = "after";
  10321. }
  10322. break
  10323. }
  10324. if (type) {
  10325. sawType = type;
  10326. }
  10327. if (dir > 0 && !moveOnce(!first)) {
  10328. break
  10329. }
  10330. }
  10331. }
  10332. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  10333. if (equalCursorPos(oldPos, result)) {
  10334. result.hitSide = true;
  10335. }
  10336. return result
  10337. }
  10338. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  10339. // "page" or "line". The resulting position will have a hitSide=true
  10340. // property if it reached the end of the document.
  10341. function findPosV(cm, pos, dir, unit) {
  10342. var doc = cm.doc, x = pos.left, y;
  10343. if (unit == "page") {
  10344. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  10345. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  10346. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  10347. } else if (unit == "line") {
  10348. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  10349. }
  10350. var target;
  10351. for (; ;) {
  10352. target = coordsChar(cm, x, y);
  10353. if (!target.outside) {
  10354. break
  10355. }
  10356. if (dir < 0 ? y <= 0 : y >= doc.height) {
  10357. target.hitSide = true;
  10358. break
  10359. }
  10360. y += dir * 5;
  10361. }
  10362. return target
  10363. }
  10364. // CONTENTEDITABLE INPUT STYLE
  10365. var ContentEditableInput = function (cm) {
  10366. this.cm = cm;
  10367. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  10368. this.polling = new Delayed();
  10369. this.composing = null;
  10370. this.gracePeriod = false;
  10371. this.readDOMTimeout = null;
  10372. };
  10373. ContentEditableInput.prototype.init = function (display) {
  10374. var this$1 = this;
  10375. var input = this, cm = input.cm;
  10376. var div = input.div = display.lineDiv;
  10377. div.contentEditable = true;
  10378. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  10379. function belongsToInput(e) {
  10380. for (var t = e.target; t; t = t.parentNode) {
  10381. if (t == div) {
  10382. return true
  10383. }
  10384. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) {
  10385. break
  10386. }
  10387. }
  10388. return false
  10389. }
  10390. on(div, "paste", function (e) {
  10391. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) {
  10392. return
  10393. }
  10394. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  10395. if (ie_version <= 11) {
  10396. setTimeout(operation(cm, function () {
  10397. return this$1.updateFromDOM();
  10398. }), 20);
  10399. }
  10400. });
  10401. on(div, "compositionstart", function (e) {
  10402. this$1.composing = {data: e.data, done: false};
  10403. });
  10404. on(div, "compositionupdate", function (e) {
  10405. if (!this$1.composing) {
  10406. this$1.composing = {data: e.data, done: false};
  10407. }
  10408. });
  10409. on(div, "compositionend", function (e) {
  10410. if (this$1.composing) {
  10411. if (e.data != this$1.composing.data) {
  10412. this$1.readFromDOMSoon();
  10413. }
  10414. this$1.composing.done = true;
  10415. }
  10416. });
  10417. on(div, "touchstart", function () {
  10418. return input.forceCompositionEnd();
  10419. });
  10420. on(div, "input", function () {
  10421. if (!this$1.composing) {
  10422. this$1.readFromDOMSoon();
  10423. }
  10424. });
  10425. function onCopyCut(e) {
  10426. if (!belongsToInput(e) || signalDOMEvent(cm, e)) {
  10427. return
  10428. }
  10429. if (cm.somethingSelected()) {
  10430. setLastCopied({lineWise: false, text: cm.getSelections()});
  10431. if (e.type == "cut") {
  10432. cm.replaceSelection("", null, "cut");
  10433. }
  10434. } else if (!cm.options.lineWiseCopyCut) {
  10435. return
  10436. } else {
  10437. var ranges = copyableRanges(cm);
  10438. setLastCopied({lineWise: true, text: ranges.text});
  10439. if (e.type == "cut") {
  10440. cm.operation(function () {
  10441. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  10442. cm.replaceSelection("", null, "cut");
  10443. });
  10444. }
  10445. }
  10446. if (e.clipboardData) {
  10447. e.clipboardData.clearData();
  10448. var content = lastCopied.text.join("\n");
  10449. // iOS exposes the clipboard API, but seems to discard content inserted into it
  10450. e.clipboardData.setData("Text", content);
  10451. if (e.clipboardData.getData("Text") == content) {
  10452. e.preventDefault();
  10453. return
  10454. }
  10455. }
  10456. // Old-fashioned briefly-focus-a-textarea hack
  10457. var kludge = hiddenTextarea(), te = kludge.firstChild;
  10458. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  10459. te.value = lastCopied.text.join("\n");
  10460. var hadFocus = document.activeElement;
  10461. selectInput(te);
  10462. setTimeout(function () {
  10463. cm.display.lineSpace.removeChild(kludge);
  10464. hadFocus.focus();
  10465. if (hadFocus == div) {
  10466. input.showPrimarySelection();
  10467. }
  10468. }, 50);
  10469. }
  10470. on(div, "copy", onCopyCut);
  10471. on(div, "cut", onCopyCut);
  10472. };
  10473. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  10474. // Label for screenreaders, accessibility
  10475. if (label) {
  10476. this.div.setAttribute('aria-label', label);
  10477. } else {
  10478. this.div.removeAttribute('aria-label');
  10479. }
  10480. };
  10481. ContentEditableInput.prototype.prepareSelection = function () {
  10482. var result = prepareSelection(this.cm, false);
  10483. result.focus = document.activeElement == this.div;
  10484. return result
  10485. };
  10486. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  10487. if (!info || !this.cm.display.view.length) {
  10488. return
  10489. }
  10490. if (info.focus || takeFocus) {
  10491. this.showPrimarySelection();
  10492. }
  10493. this.showMultipleSelections(info);
  10494. };
  10495. ContentEditableInput.prototype.getSelection = function () {
  10496. return this.cm.display.wrapper.ownerDocument.getSelection()
  10497. };
  10498. ContentEditableInput.prototype.showPrimarySelection = function () {
  10499. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  10500. var from = prim.from(), to = prim.to();
  10501. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  10502. sel.removeAllRanges();
  10503. return
  10504. }
  10505. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  10506. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  10507. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  10508. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  10509. cmp(maxPos(curAnchor, curFocus), to) == 0) {
  10510. return
  10511. }
  10512. var view = cm.display.view;
  10513. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  10514. {node: view[0].measure.map[2], offset: 0};
  10515. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  10516. if (!end) {
  10517. var measure = view[view.length - 1].measure;
  10518. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  10519. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  10520. }
  10521. if (!start || !end) {
  10522. sel.removeAllRanges();
  10523. return
  10524. }
  10525. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  10526. try {
  10527. rng = range(start.node, start.offset, end.offset, end.node);
  10528. } catch (e) {
  10529. } // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  10530. if (rng) {
  10531. if (!gecko && cm.state.focused) {
  10532. sel.collapse(start.node, start.offset);
  10533. if (!rng.collapsed) {
  10534. sel.removeAllRanges();
  10535. sel.addRange(rng);
  10536. }
  10537. } else {
  10538. sel.removeAllRanges();
  10539. sel.addRange(rng);
  10540. }
  10541. if (old && sel.anchorNode == null) {
  10542. sel.addRange(old);
  10543. } else if (gecko) {
  10544. this.startGracePeriod();
  10545. }
  10546. }
  10547. this.rememberSelection();
  10548. };
  10549. ContentEditableInput.prototype.startGracePeriod = function () {
  10550. var this$1 = this;
  10551. clearTimeout(this.gracePeriod);
  10552. this.gracePeriod = setTimeout(function () {
  10553. this$1.gracePeriod = false;
  10554. if (this$1.selectionChanged()) {
  10555. this$1.cm.operation(function () {
  10556. return this$1.cm.curOp.selectionChanged = true;
  10557. });
  10558. }
  10559. }, 20);
  10560. };
  10561. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  10562. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  10563. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  10564. };
  10565. ContentEditableInput.prototype.rememberSelection = function () {
  10566. var sel = this.getSelection();
  10567. this.lastAnchorNode = sel.anchorNode;
  10568. this.lastAnchorOffset = sel.anchorOffset;
  10569. this.lastFocusNode = sel.focusNode;
  10570. this.lastFocusOffset = sel.focusOffset;
  10571. };
  10572. ContentEditableInput.prototype.selectionInEditor = function () {
  10573. var sel = this.getSelection();
  10574. if (!sel.rangeCount) {
  10575. return false
  10576. }
  10577. var node = sel.getRangeAt(0).commonAncestorContainer;
  10578. return contains(this.div, node)
  10579. };
  10580. ContentEditableInput.prototype.focus = function () {
  10581. if (this.cm.options.readOnly != "nocursor") {
  10582. if (!this.selectionInEditor() || document.activeElement != this.div) {
  10583. this.showSelection(this.prepareSelection(), true);
  10584. }
  10585. this.div.focus();
  10586. }
  10587. };
  10588. ContentEditableInput.prototype.blur = function () {
  10589. this.div.blur();
  10590. };
  10591. ContentEditableInput.prototype.getField = function () {
  10592. return this.div
  10593. };
  10594. ContentEditableInput.prototype.supportsTouch = function () {
  10595. return true
  10596. };
  10597. ContentEditableInput.prototype.receivedFocus = function () {
  10598. var input = this;
  10599. if (this.selectionInEditor()) {
  10600. this.pollSelection();
  10601. } else {
  10602. runInOp(this.cm, function () {
  10603. return input.cm.curOp.selectionChanged = true;
  10604. });
  10605. }
  10606. function poll() {
  10607. if (input.cm.state.focused) {
  10608. input.pollSelection();
  10609. input.polling.set(input.cm.options.pollInterval, poll);
  10610. }
  10611. }
  10612. this.polling.set(this.cm.options.pollInterval, poll);
  10613. };
  10614. ContentEditableInput.prototype.selectionChanged = function () {
  10615. var sel = this.getSelection();
  10616. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  10617. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  10618. };
  10619. ContentEditableInput.prototype.pollSelection = function () {
  10620. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) {
  10621. return
  10622. }
  10623. var sel = this.getSelection(), cm = this.cm;
  10624. // On Android Chrome (version 56, at least), backspacing into an
  10625. // uneditable block element will put the cursor in that element,
  10626. // and then, because it's not editable, hide the virtual keyboard.
  10627. // Because Android doesn't allow us to actually detect backspace
  10628. // presses in a sane way, this code checks for when that happens
  10629. // and simulates a backspace press in this case.
  10630. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  10631. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  10632. this.blur();
  10633. this.focus();
  10634. return
  10635. }
  10636. if (this.composing) {
  10637. return
  10638. }
  10639. this.rememberSelection();
  10640. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  10641. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  10642. if (anchor && head) {
  10643. runInOp(cm, function () {
  10644. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  10645. if (anchor.bad || head.bad) {
  10646. cm.curOp.selectionChanged = true;
  10647. }
  10648. });
  10649. }
  10650. };
  10651. ContentEditableInput.prototype.pollContent = function () {
  10652. if (this.readDOMTimeout != null) {
  10653. clearTimeout(this.readDOMTimeout);
  10654. this.readDOMTimeout = null;
  10655. }
  10656. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  10657. var from = sel.from(), to = sel.to();
  10658. if (from.ch == 0 && from.line > cm.firstLine()) {
  10659. from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length);
  10660. }
  10661. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) {
  10662. to = Pos(to.line + 1, 0);
  10663. }
  10664. if (from.line < display.viewFrom || to.line > display.viewTo - 1) {
  10665. return false
  10666. }
  10667. var fromIndex, fromLine, fromNode;
  10668. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  10669. fromLine = lineNo(display.view[0].line);
  10670. fromNode = display.view[0].node;
  10671. } else {
  10672. fromLine = lineNo(display.view[fromIndex].line);
  10673. fromNode = display.view[fromIndex - 1].node.nextSibling;
  10674. }
  10675. var toIndex = findViewIndex(cm, to.line);
  10676. var toLine, toNode;
  10677. if (toIndex == display.view.length - 1) {
  10678. toLine = display.viewTo - 1;
  10679. toNode = display.lineDiv.lastChild;
  10680. } else {
  10681. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  10682. toNode = display.view[toIndex + 1].node.previousSibling;
  10683. }
  10684. if (!fromNode) {
  10685. return false
  10686. }
  10687. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  10688. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  10689. while (newText.length > 1 && oldText.length > 1) {
  10690. if (lst(newText) == lst(oldText)) {
  10691. newText.pop();
  10692. oldText.pop();
  10693. toLine--;
  10694. } else if (newText[0] == oldText[0]) {
  10695. newText.shift();
  10696. oldText.shift();
  10697. fromLine++;
  10698. } else {
  10699. break
  10700. }
  10701. }
  10702. var cutFront = 0, cutEnd = 0;
  10703. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  10704. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {
  10705. ++cutFront;
  10706. }
  10707. var newBot = lst(newText), oldBot = lst(oldText);
  10708. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  10709. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  10710. while (cutEnd < maxCutEnd &&
  10711. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  10712. ++cutEnd;
  10713. }
  10714. // Try to move start of change to start of selection if ambiguous
  10715. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  10716. while (cutFront && cutFront > from.ch &&
  10717. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  10718. cutFront--;
  10719. cutEnd++;
  10720. }
  10721. }
  10722. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  10723. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  10724. var chFrom = Pos(fromLine, cutFront);
  10725. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  10726. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  10727. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  10728. return true
  10729. }
  10730. };
  10731. ContentEditableInput.prototype.ensurePolled = function () {
  10732. this.forceCompositionEnd();
  10733. };
  10734. ContentEditableInput.prototype.reset = function () {
  10735. this.forceCompositionEnd();
  10736. };
  10737. ContentEditableInput.prototype.forceCompositionEnd = function () {
  10738. if (!this.composing) {
  10739. return
  10740. }
  10741. clearTimeout(this.readDOMTimeout);
  10742. this.composing = null;
  10743. this.updateFromDOM();
  10744. this.div.blur();
  10745. this.div.focus();
  10746. };
  10747. ContentEditableInput.prototype.readFromDOMSoon = function () {
  10748. var this$1 = this;
  10749. if (this.readDOMTimeout != null) {
  10750. return
  10751. }
  10752. this.readDOMTimeout = setTimeout(function () {
  10753. this$1.readDOMTimeout = null;
  10754. if (this$1.composing) {
  10755. if (this$1.composing.done) {
  10756. this$1.composing = null;
  10757. } else {
  10758. return
  10759. }
  10760. }
  10761. this$1.updateFromDOM();
  10762. }, 80);
  10763. };
  10764. ContentEditableInput.prototype.updateFromDOM = function () {
  10765. var this$1 = this;
  10766. if (this.cm.isReadOnly() || !this.pollContent()) {
  10767. runInOp(this.cm, function () {
  10768. return regChange(this$1.cm);
  10769. });
  10770. }
  10771. };
  10772. ContentEditableInput.prototype.setUneditable = function (node) {
  10773. node.contentEditable = "false";
  10774. };
  10775. ContentEditableInput.prototype.onKeyPress = function (e) {
  10776. if (e.charCode == 0 || this.composing) {
  10777. return
  10778. }
  10779. e.preventDefault();
  10780. if (!this.cm.isReadOnly()) {
  10781. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  10782. }
  10783. };
  10784. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  10785. this.div.contentEditable = String(val != "nocursor");
  10786. };
  10787. ContentEditableInput.prototype.onContextMenu = function () {
  10788. };
  10789. ContentEditableInput.prototype.resetPosition = function () {
  10790. };
  10791. ContentEditableInput.prototype.needsContentAttribute = true;
  10792. function posToDOM(cm, pos) {
  10793. var view = findViewForLine(cm, pos.line);
  10794. if (!view || view.hidden) {
  10795. return null
  10796. }
  10797. var line = getLine(cm.doc, pos.line);
  10798. var info = mapFromLineView(view, line, pos.line);
  10799. var order = getOrder(line, cm.doc.direction), side = "left";
  10800. if (order) {
  10801. var partPos = getBidiPartAt(order, pos.ch);
  10802. side = partPos % 2 ? "right" : "left";
  10803. }
  10804. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  10805. result.offset = result.collapse == "right" ? result.end : result.start;
  10806. return result
  10807. }
  10808. function isInGutter(node) {
  10809. for (var scan = node; scan; scan = scan.parentNode) {
  10810. if (/CodeMirror-gutter-wrapper/.test(scan.className)) {
  10811. return true
  10812. }
  10813. }
  10814. return false
  10815. }
  10816. function badPos(pos, bad) {
  10817. if (bad) {
  10818. pos.bad = true;
  10819. }
  10820. return pos
  10821. }
  10822. function domTextBetween(cm, from, to, fromLine, toLine) {
  10823. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  10824. function recognizeMarker(id) {
  10825. return function (marker) {
  10826. return marker.id == id;
  10827. }
  10828. }
  10829. function close() {
  10830. if (closing) {
  10831. text += lineSep;
  10832. if (extraLinebreak) {
  10833. text += lineSep;
  10834. }
  10835. closing = extraLinebreak = false;
  10836. }
  10837. }
  10838. function addText(str) {
  10839. if (str) {
  10840. close();
  10841. text += str;
  10842. }
  10843. }
  10844. function walk(node) {
  10845. if (node.nodeType == 1) {
  10846. var cmText = node.getAttribute("cm-text");
  10847. if (cmText) {
  10848. addText(cmText);
  10849. return
  10850. }
  10851. var markerID = node.getAttribute("cm-marker"), range;
  10852. if (markerID) {
  10853. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  10854. if (found.length && (range = found[0].find(0))) {
  10855. addText(getBetween(cm.doc, range.from, range.to).join(lineSep));
  10856. }
  10857. return
  10858. }
  10859. if (node.getAttribute("contenteditable") == "false") {
  10860. return
  10861. }
  10862. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  10863. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) {
  10864. return
  10865. }
  10866. if (isBlock) {
  10867. close();
  10868. }
  10869. for (var i = 0; i < node.childNodes.length; i++) {
  10870. walk(node.childNodes[i]);
  10871. }
  10872. if (/^(pre|p)$/i.test(node.nodeName)) {
  10873. extraLinebreak = true;
  10874. }
  10875. if (isBlock) {
  10876. closing = true;
  10877. }
  10878. } else if (node.nodeType == 3) {
  10879. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  10880. }
  10881. }
  10882. for (; ;) {
  10883. walk(from);
  10884. if (from == to) {
  10885. break
  10886. }
  10887. from = from.nextSibling;
  10888. extraLinebreak = false;
  10889. }
  10890. return text
  10891. }
  10892. function domToPos(cm, node, offset) {
  10893. var lineNode;
  10894. if (node == cm.display.lineDiv) {
  10895. lineNode = cm.display.lineDiv.childNodes[offset];
  10896. if (!lineNode) {
  10897. return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true)
  10898. }
  10899. node = null;
  10900. offset = 0;
  10901. } else {
  10902. for (lineNode = node; ; lineNode = lineNode.parentNode) {
  10903. if (!lineNode || lineNode == cm.display.lineDiv) {
  10904. return null
  10905. }
  10906. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) {
  10907. break
  10908. }
  10909. }
  10910. }
  10911. for (var i = 0; i < cm.display.view.length; i++) {
  10912. var lineView = cm.display.view[i];
  10913. if (lineView.node == lineNode) {
  10914. return locateNodeInLineView(lineView, node, offset)
  10915. }
  10916. }
  10917. }
  10918. function locateNodeInLineView(lineView, node, offset) {
  10919. var wrapper = lineView.text.firstChild, bad = false;
  10920. if (!node || !contains(wrapper, node)) {
  10921. return badPos(Pos(lineNo(lineView.line), 0), true)
  10922. }
  10923. if (node == wrapper) {
  10924. bad = true;
  10925. node = wrapper.childNodes[offset];
  10926. offset = 0;
  10927. if (!node) {
  10928. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  10929. return badPos(Pos(lineNo(line), line.text.length), bad)
  10930. }
  10931. }
  10932. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  10933. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  10934. textNode = node.firstChild;
  10935. if (offset) {
  10936. offset = textNode.nodeValue.length;
  10937. }
  10938. }
  10939. while (topNode.parentNode != wrapper) {
  10940. topNode = topNode.parentNode;
  10941. }
  10942. var measure = lineView.measure, maps = measure.maps;
  10943. function find(textNode, topNode, offset) {
  10944. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  10945. var map = i < 0 ? measure.map : maps[i];
  10946. for (var j = 0; j < map.length; j += 3) {
  10947. var curNode = map[j + 2];
  10948. if (curNode == textNode || curNode == topNode) {
  10949. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  10950. var ch = map[j] + offset;
  10951. if (offset < 0 || curNode != textNode) {
  10952. ch = map[j + (offset ? 1 : 0)];
  10953. }
  10954. return Pos(line, ch)
  10955. }
  10956. }
  10957. }
  10958. }
  10959. var found = find(textNode, topNode, offset);
  10960. if (found) {
  10961. return badPos(found, bad)
  10962. }
  10963. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  10964. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  10965. found = find(after, after.firstChild, 0);
  10966. if (found) {
  10967. return badPos(Pos(found.line, found.ch - dist), bad)
  10968. } else {
  10969. dist += after.textContent.length;
  10970. }
  10971. }
  10972. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  10973. found = find(before, before.firstChild, -1);
  10974. if (found) {
  10975. return badPos(Pos(found.line, found.ch + dist$1), bad)
  10976. } else {
  10977. dist$1 += before.textContent.length;
  10978. }
  10979. }
  10980. }
  10981. // TEXTAREA INPUT STYLE
  10982. var TextareaInput = function (cm) {
  10983. this.cm = cm;
  10984. // See input.poll and input.reset
  10985. this.prevInput = "";
  10986. // Flag that indicates whether we expect input to appear real soon
  10987. // now (after some event like 'keypress' or 'input') and are
  10988. // polling intensively.
  10989. this.pollingFast = false;
  10990. // Self-resetting timeout for the poller
  10991. this.polling = new Delayed();
  10992. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  10993. this.hasSelection = false;
  10994. this.composing = null;
  10995. };
  10996. TextareaInput.prototype.init = function (display) {
  10997. var this$1 = this;
  10998. var input = this, cm = this.cm;
  10999. this.createField(display);
  11000. var te = this.textarea;
  11001. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  11002. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  11003. if (ios) {
  11004. te.style.width = "0px";
  11005. }
  11006. on(te, "input", function () {
  11007. if (ie && ie_version >= 9 && this$1.hasSelection) {
  11008. this$1.hasSelection = null;
  11009. }
  11010. input.poll();
  11011. });
  11012. on(te, "paste", function (e) {
  11013. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) {
  11014. return
  11015. }
  11016. cm.state.pasteIncoming = +new Date;
  11017. input.fastPoll();
  11018. });
  11019. function prepareCopyCut(e) {
  11020. if (signalDOMEvent(cm, e)) {
  11021. return
  11022. }
  11023. if (cm.somethingSelected()) {
  11024. setLastCopied({lineWise: false, text: cm.getSelections()});
  11025. } else if (!cm.options.lineWiseCopyCut) {
  11026. return
  11027. } else {
  11028. var ranges = copyableRanges(cm);
  11029. setLastCopied({lineWise: true, text: ranges.text});
  11030. if (e.type == "cut") {
  11031. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  11032. } else {
  11033. input.prevInput = "";
  11034. te.value = ranges.text.join("\n");
  11035. selectInput(te);
  11036. }
  11037. }
  11038. if (e.type == "cut") {
  11039. cm.state.cutIncoming = +new Date;
  11040. }
  11041. }
  11042. on(te, "cut", prepareCopyCut);
  11043. on(te, "copy", prepareCopyCut);
  11044. on(display.scroller, "paste", function (e) {
  11045. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) {
  11046. return
  11047. }
  11048. if (!te.dispatchEvent) {
  11049. cm.state.pasteIncoming = +new Date;
  11050. input.focus();
  11051. return
  11052. }
  11053. // Pass the `paste` event to the textarea so it's handled by its event listener.
  11054. var event = new Event("paste");
  11055. event.clipboardData = e.clipboardData;
  11056. te.dispatchEvent(event);
  11057. });
  11058. // Prevent normal selection in the editor (we handle our own)
  11059. on(display.lineSpace, "selectstart", function (e) {
  11060. if (!eventInWidget(display, e)) {
  11061. e_preventDefault(e);
  11062. }
  11063. });
  11064. on(te, "compositionstart", function () {
  11065. var start = cm.getCursor("from");
  11066. if (input.composing) {
  11067. input.composing.range.clear();
  11068. }
  11069. input.composing = {
  11070. start: start,
  11071. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  11072. };
  11073. });
  11074. on(te, "compositionend", function () {
  11075. if (input.composing) {
  11076. input.poll();
  11077. input.composing.range.clear();
  11078. input.composing = null;
  11079. }
  11080. });
  11081. };
  11082. TextareaInput.prototype.createField = function (_display) {
  11083. // Wraps and hides input textarea
  11084. this.wrapper = hiddenTextarea();
  11085. // The semihidden textarea that is focused when the editor is
  11086. // focused, and receives input.
  11087. this.textarea = this.wrapper.firstChild;
  11088. };
  11089. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  11090. // Label for screenreaders, accessibility
  11091. if (label) {
  11092. this.textarea.setAttribute('aria-label', label);
  11093. } else {
  11094. this.textarea.removeAttribute('aria-label');
  11095. }
  11096. };
  11097. TextareaInput.prototype.prepareSelection = function () {
  11098. // Redraw the selection and/or cursor
  11099. var cm = this.cm, display = cm.display, doc = cm.doc;
  11100. var result = prepareSelection(cm);
  11101. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  11102. if (cm.options.moveInputWithCursor) {
  11103. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  11104. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  11105. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  11106. headPos.top + lineOff.top - wrapOff.top));
  11107. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  11108. headPos.left + lineOff.left - wrapOff.left));
  11109. }
  11110. return result
  11111. };
  11112. TextareaInput.prototype.showSelection = function (drawn) {
  11113. var cm = this.cm, display = cm.display;
  11114. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  11115. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  11116. if (drawn.teTop != null) {
  11117. this.wrapper.style.top = drawn.teTop + "px";
  11118. this.wrapper.style.left = drawn.teLeft + "px";
  11119. }
  11120. };
  11121. // Reset the input to correspond to the selection (or to be empty,
  11122. // when not typing and nothing is selected)
  11123. TextareaInput.prototype.reset = function (typing) {
  11124. if (this.contextMenuPending || this.composing) {
  11125. return
  11126. }
  11127. var cm = this.cm;
  11128. if (cm.somethingSelected()) {
  11129. this.prevInput = "";
  11130. var content = cm.getSelection();
  11131. this.textarea.value = content;
  11132. if (cm.state.focused) {
  11133. selectInput(this.textarea);
  11134. }
  11135. if (ie && ie_version >= 9) {
  11136. this.hasSelection = content;
  11137. }
  11138. } else if (!typing) {
  11139. this.prevInput = this.textarea.value = "";
  11140. if (ie && ie_version >= 9) {
  11141. this.hasSelection = null;
  11142. }
  11143. }
  11144. };
  11145. TextareaInput.prototype.getField = function () {
  11146. return this.textarea
  11147. };
  11148. TextareaInput.prototype.supportsTouch = function () {
  11149. return false
  11150. };
  11151. TextareaInput.prototype.focus = function () {
  11152. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  11153. try {
  11154. this.textarea.focus();
  11155. } catch (e) {
  11156. } // IE8 will throw if the textarea is display: none or not in DOM
  11157. }
  11158. };
  11159. TextareaInput.prototype.blur = function () {
  11160. this.textarea.blur();
  11161. };
  11162. TextareaInput.prototype.resetPosition = function () {
  11163. this.wrapper.style.top = this.wrapper.style.left = 0;
  11164. };
  11165. TextareaInput.prototype.receivedFocus = function () {
  11166. this.slowPoll();
  11167. };
  11168. // Poll for input changes, using the normal rate of polling. This
  11169. // runs as long as the editor is focused.
  11170. TextareaInput.prototype.slowPoll = function () {
  11171. var this$1 = this;
  11172. if (this.pollingFast) {
  11173. return
  11174. }
  11175. this.polling.set(this.cm.options.pollInterval, function () {
  11176. this$1.poll();
  11177. if (this$1.cm.state.focused) {
  11178. this$1.slowPoll();
  11179. }
  11180. });
  11181. };
  11182. // When an event has just come in that is likely to add or change
  11183. // something in the input textarea, we poll faster, to ensure that
  11184. // the change appears on the screen quickly.
  11185. TextareaInput.prototype.fastPoll = function () {
  11186. var missed = false, input = this;
  11187. input.pollingFast = true;
  11188. function p() {
  11189. var changed = input.poll();
  11190. if (!changed && !missed) {
  11191. missed = true;
  11192. input.polling.set(60, p);
  11193. } else {
  11194. input.pollingFast = false;
  11195. input.slowPoll();
  11196. }
  11197. }
  11198. input.polling.set(20, p);
  11199. };
  11200. // Read input from the textarea, and update the document to match.
  11201. // When something is selected, it is present in the textarea, and
  11202. // selected (unless it is huge, in which case a placeholder is
  11203. // used). When nothing is selected, the cursor sits after previously
  11204. // seen text (can be empty), which is stored in prevInput (we must
  11205. // not reset the textarea when typing, because that breaks IME).
  11206. TextareaInput.prototype.poll = function () {
  11207. var this$1 = this;
  11208. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  11209. // Since this is called a *lot*, try to bail out as cheaply as
  11210. // possible when it is clear that nothing happened. hasSelection
  11211. // will be the case when there is a lot of text in the textarea,
  11212. // in which case reading its value would be expensive.
  11213. if (this.contextMenuPending || !cm.state.focused ||
  11214. (hasSelection(input) && !prevInput && !this.composing) ||
  11215. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) {
  11216. return false
  11217. }
  11218. var text = input.value;
  11219. // If nothing changed, bail.
  11220. if (text == prevInput && !cm.somethingSelected()) {
  11221. return false
  11222. }
  11223. // Work around nonsensical selection resetting in IE9/10, and
  11224. // inexplicable appearance of private area unicode characters on
  11225. // some key combos in Mac (#2689).
  11226. if (ie && ie_version >= 9 && this.hasSelection === text ||
  11227. mac && /[\uf700-\uf7ff]/.test(text)) {
  11228. cm.display.input.reset();
  11229. return false
  11230. }
  11231. if (cm.doc.sel == cm.display.selForContextMenu) {
  11232. var first = text.charCodeAt(0);
  11233. if (first == 0x200b && !prevInput) {
  11234. prevInput = "\u200b";
  11235. }
  11236. if (first == 0x21da) {
  11237. this.reset();
  11238. return this.cm.execCommand("undo")
  11239. }
  11240. }
  11241. // Find the part of the input that is actually new
  11242. var same = 0, l = Math.min(prevInput.length, text.length);
  11243. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) {
  11244. ++same;
  11245. }
  11246. runInOp(cm, function () {
  11247. applyTextInput(cm, text.slice(same), prevInput.length - same,
  11248. null, this$1.composing ? "*compose" : null);
  11249. // Don't leave long text in the textarea, since it makes further polling slow
  11250. if (text.length > 1000 || text.indexOf("\n") > -1) {
  11251. input.value = this$1.prevInput = "";
  11252. } else {
  11253. this$1.prevInput = text;
  11254. }
  11255. if (this$1.composing) {
  11256. this$1.composing.range.clear();
  11257. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  11258. {className: "CodeMirror-composing"});
  11259. }
  11260. });
  11261. return true
  11262. };
  11263. TextareaInput.prototype.ensurePolled = function () {
  11264. if (this.pollingFast && this.poll()) {
  11265. this.pollingFast = false;
  11266. }
  11267. };
  11268. TextareaInput.prototype.onKeyPress = function () {
  11269. if (ie && ie_version >= 9) {
  11270. this.hasSelection = null;
  11271. }
  11272. this.fastPoll();
  11273. };
  11274. TextareaInput.prototype.onContextMenu = function (e) {
  11275. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  11276. if (input.contextMenuPending) {
  11277. input.contextMenuPending();
  11278. }
  11279. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  11280. if (!pos || presto) {
  11281. return
  11282. } // Opera is difficult.
  11283. // Reset the current text selection only if the click is done outside of the selection
  11284. // and 'resetSelectionOnContextMenu' option is true.
  11285. var reset = cm.options.resetSelectionOnContextMenu;
  11286. if (reset && cm.doc.sel.contains(pos) == -1) {
  11287. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  11288. }
  11289. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  11290. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  11291. input.wrapper.style.cssText = "position: static";
  11292. te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  11293. var oldScrollY;
  11294. if (webkit) {
  11295. oldScrollY = window.scrollY;
  11296. } // Work around Chrome issue (#2712)
  11297. display.input.focus();
  11298. if (webkit) {
  11299. window.scrollTo(null, oldScrollY);
  11300. }
  11301. display.input.reset();
  11302. // Adds "Select all" to context menu in FF
  11303. if (!cm.somethingSelected()) {
  11304. te.value = input.prevInput = " ";
  11305. }
  11306. input.contextMenuPending = rehide;
  11307. display.selForContextMenu = cm.doc.sel;
  11308. clearTimeout(display.detectingSelectAll);
  11309. // Select-all will be greyed out if there's nothing to select, so
  11310. // this adds a zero-width space so that we can later check whether
  11311. // it got selected.
  11312. function prepareSelectAllHack() {
  11313. if (te.selectionStart != null) {
  11314. var selected = cm.somethingSelected();
  11315. var extval = "\u200b" + (selected ? te.value : "");
  11316. te.value = "\u21da"; // Used to catch context-menu undo
  11317. te.value = extval;
  11318. input.prevInput = selected ? "" : "\u200b";
  11319. te.selectionStart = 1;
  11320. te.selectionEnd = extval.length;
  11321. // Re-set this, in case some other handler touched the
  11322. // selection in the meantime.
  11323. display.selForContextMenu = cm.doc.sel;
  11324. }
  11325. }
  11326. function rehide() {
  11327. if (input.contextMenuPending != rehide) {
  11328. return
  11329. }
  11330. input.contextMenuPending = false;
  11331. input.wrapper.style.cssText = oldWrapperCSS;
  11332. te.style.cssText = oldCSS;
  11333. if (ie && ie_version < 9) {
  11334. display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  11335. }
  11336. // Try to detect the user choosing select-all
  11337. if (te.selectionStart != null) {
  11338. if (!ie || (ie && ie_version < 9)) {
  11339. prepareSelectAllHack();
  11340. }
  11341. var i = 0, poll = function () {
  11342. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  11343. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  11344. operation(cm, selectAll)(cm);
  11345. } else if (i++ < 10) {
  11346. display.detectingSelectAll = setTimeout(poll, 500);
  11347. } else {
  11348. display.selForContextMenu = null;
  11349. display.input.reset();
  11350. }
  11351. };
  11352. display.detectingSelectAll = setTimeout(poll, 200);
  11353. }
  11354. }
  11355. if (ie && ie_version >= 9) {
  11356. prepareSelectAllHack();
  11357. }
  11358. if (captureRightClick) {
  11359. e_stop(e);
  11360. var mouseup = function () {
  11361. off(window, "mouseup", mouseup);
  11362. setTimeout(rehide, 20);
  11363. };
  11364. on(window, "mouseup", mouseup);
  11365. } else {
  11366. setTimeout(rehide, 50);
  11367. }
  11368. };
  11369. TextareaInput.prototype.readOnlyChanged = function (val) {
  11370. if (!val) {
  11371. this.reset();
  11372. }
  11373. this.textarea.disabled = val == "nocursor";
  11374. this.textarea.readOnly = !!val;
  11375. };
  11376. TextareaInput.prototype.setUneditable = function () {
  11377. };
  11378. TextareaInput.prototype.needsContentAttribute = false;
  11379. function fromTextArea(textarea, options) {
  11380. options = options ? copyObj(options) : {};
  11381. options.value = textarea.value;
  11382. if (!options.tabindex && textarea.tabIndex) {
  11383. options.tabindex = textarea.tabIndex;
  11384. }
  11385. if (!options.placeholder && textarea.placeholder) {
  11386. options.placeholder = textarea.placeholder;
  11387. }
  11388. // Set autofocus to true if this textarea is focused, or if it has
  11389. // autofocus and no other element is focused.
  11390. if (options.autofocus == null) {
  11391. var hasFocus = activeElt();
  11392. options.autofocus = hasFocus == textarea ||
  11393. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  11394. }
  11395. function save() {
  11396. textarea.value = cm.getValue();
  11397. }
  11398. var realSubmit;
  11399. if (textarea.form) {
  11400. on(textarea.form, "submit", save);
  11401. // Deplorable hack to make the submit method do the right thing.
  11402. if (!options.leaveSubmitMethodAlone) {
  11403. var form = textarea.form;
  11404. realSubmit = form.submit;
  11405. try {
  11406. var wrappedSubmit = form.submit = function () {
  11407. save();
  11408. form.submit = realSubmit;
  11409. form.submit();
  11410. form.submit = wrappedSubmit;
  11411. };
  11412. } catch (e) {
  11413. }
  11414. }
  11415. }
  11416. options.finishInit = function (cm) {
  11417. cm.save = save;
  11418. cm.getTextArea = function () {
  11419. return textarea;
  11420. };
  11421. cm.toTextArea = function () {
  11422. cm.toTextArea = isNaN; // Prevent this from being ran twice
  11423. save();
  11424. textarea.parentNode.removeChild(cm.getWrapperElement());
  11425. textarea.style.display = "";
  11426. if (textarea.form) {
  11427. off(textarea.form, "submit", save);
  11428. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") {
  11429. textarea.form.submit = realSubmit;
  11430. }
  11431. }
  11432. };
  11433. };
  11434. textarea.style.display = "none";
  11435. var cm = CodeMirror(function (node) {
  11436. return textarea.parentNode.insertBefore(node, textarea.nextSibling);
  11437. },
  11438. options);
  11439. return cm
  11440. }
  11441. function addLegacyProps(CodeMirror) {
  11442. CodeMirror.off = off;
  11443. CodeMirror.on = on;
  11444. CodeMirror.wheelEventPixels = wheelEventPixels;
  11445. CodeMirror.Doc = Doc;
  11446. CodeMirror.splitLines = splitLinesAuto;
  11447. CodeMirror.countColumn = countColumn;
  11448. CodeMirror.findColumn = findColumn;
  11449. CodeMirror.isWordChar = isWordCharBasic;
  11450. CodeMirror.Pass = Pass;
  11451. CodeMirror.signal = signal;
  11452. CodeMirror.Line = Line;
  11453. CodeMirror.changeEnd = changeEnd;
  11454. CodeMirror.scrollbarModel = scrollbarModel;
  11455. CodeMirror.Pos = Pos;
  11456. CodeMirror.cmpPos = cmp;
  11457. CodeMirror.modes = modes;
  11458. CodeMirror.mimeModes = mimeModes;
  11459. CodeMirror.resolveMode = resolveMode;
  11460. CodeMirror.getMode = getMode;
  11461. CodeMirror.modeExtensions = modeExtensions;
  11462. CodeMirror.extendMode = extendMode;
  11463. CodeMirror.copyState = copyState;
  11464. CodeMirror.startState = startState;
  11465. CodeMirror.innerMode = innerMode;
  11466. CodeMirror.commands = commands;
  11467. CodeMirror.keyMap = keyMap;
  11468. CodeMirror.keyName = keyName;
  11469. CodeMirror.isModifierKey = isModifierKey;
  11470. CodeMirror.lookupKey = lookupKey;
  11471. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  11472. CodeMirror.StringStream = StringStream;
  11473. CodeMirror.SharedTextMarker = SharedTextMarker;
  11474. CodeMirror.TextMarker = TextMarker;
  11475. CodeMirror.LineWidget = LineWidget;
  11476. CodeMirror.e_preventDefault = e_preventDefault;
  11477. CodeMirror.e_stopPropagation = e_stopPropagation;
  11478. CodeMirror.e_stop = e_stop;
  11479. CodeMirror.addClass = addClass;
  11480. CodeMirror.contains = contains;
  11481. CodeMirror.rmClass = rmClass;
  11482. CodeMirror.keyNames = keyNames;
  11483. }
  11484. // EDITOR CONSTRUCTOR
  11485. defineOptions(CodeMirror);
  11486. addEditorMethods(CodeMirror);
  11487. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  11488. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  11489. for (var prop in Doc.prototype) {
  11490. if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) {
  11491. CodeMirror.prototype[prop] = (function (method) {
  11492. return function () {
  11493. return method.apply(this.doc, arguments)
  11494. }
  11495. })(Doc.prototype[prop]);
  11496. }
  11497. }
  11498. eventMixin(Doc);
  11499. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  11500. // Extra arguments are stored as the mode's dependencies, which is
  11501. // used by (legacy) mechanisms like loadmode.js to automatically
  11502. // load a mode. (Preferred mechanism is the require/define calls.)
  11503. CodeMirror.defineMode = function (name/*, mode, …*/) {
  11504. if (!CodeMirror.defaults.mode && name != "null") {
  11505. CodeMirror.defaults.mode = name;
  11506. }
  11507. defineMode.apply(this, arguments);
  11508. };
  11509. CodeMirror.defineMIME = defineMIME;
  11510. // Minimal default mode.
  11511. CodeMirror.defineMode("null", function () {
  11512. return ({
  11513. token: function (stream) {
  11514. return stream.skipToEnd();
  11515. }
  11516. });
  11517. });
  11518. CodeMirror.defineMIME("text/plain", "null");
  11519. // EXTENSIONS
  11520. CodeMirror.defineExtension = function (name, func) {
  11521. CodeMirror.prototype[name] = func;
  11522. };
  11523. CodeMirror.defineDocExtension = function (name, func) {
  11524. Doc.prototype[name] = func;
  11525. };
  11526. CodeMirror.fromTextArea = fromTextArea;
  11527. addLegacyProps(CodeMirror);
  11528. CodeMirror.version = "5.60.0";
  11529. return CodeMirror;
  11530. })));