codemirror.js 486 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058
  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'
  10. ? (module.exports = factory())
  11. : typeof define === 'function' && define.amd
  12. ? define(factory)
  13. : ((global = global || self), (global.CodeMirror = factory()))
  14. })(this, function () {
  15. 'use strict'
  16. // Kludges for bugs and behavior differences that can't be feature
  17. // detected are enabled based on userAgent etc sniffing.
  18. var userAgent = navigator.userAgent
  19. var platform = navigator.platform
  20. var gecko = /gecko\/\d/i.test(userAgent)
  21. var ie_upto10 = /MSIE \d/.test(userAgent)
  22. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
  23. var edge = /Edge\/(\d+)/.exec(userAgent)
  24. var ie = ie_upto10 || ie_11up || edge
  25. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1])
  26. var webkit = !edge && /WebKit\//.test(userAgent)
  27. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
  28. var chrome = !edge && /Chrome\//.test(userAgent)
  29. var presto = /Opera\//.test(userAgent)
  30. var safari = /Apple Computer/.test(navigator.vendor)
  31. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
  32. var phantom = /PhantomJS/.test(userAgent)
  33. var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2)
  34. var android = /Android/.test(userAgent)
  35. // This is woefully incomplete. Suggestions for alternative methods welcome.
  36. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
  37. var mac = ios || /Mac/.test(platform)
  38. var chromeOS = /\bCrOS\b/.test(userAgent)
  39. var windows = /win/i.test(platform)
  40. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
  41. if (presto_version) {
  42. presto_version = Number(presto_version[1])
  43. }
  44. if (presto_version && presto_version >= 15) {
  45. presto = false
  46. webkit = true
  47. }
  48. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  49. var flipCtrlCmd = mac && (qtwebkit || (presto && (presto_version == null || presto_version < 12.11)))
  50. var captureRightClick = gecko || (ie && ie_version >= 9)
  51. function classTest(cls) {
  52. return new RegExp('(^|\\s)' + cls + '(?:$|\\s)\\s*')
  53. }
  54. var rmClass = function (node, cls) {
  55. var current = node.className
  56. var match = classTest(cls).exec(current)
  57. if (match) {
  58. var after = current.slice(match.index + match[0].length)
  59. node.className = current.slice(0, match.index) + (after ? match[1] + after : '')
  60. }
  61. }
  62. function removeChildren(e) {
  63. for (var count = e.childNodes.length; count > 0; --count) {
  64. e.removeChild(e.firstChild)
  65. }
  66. return e
  67. }
  68. function removeChildrenAndAdd(parent, e) {
  69. return removeChildren(parent).appendChild(e)
  70. }
  71. function elt(tag, content, className, style) {
  72. var e = document.createElement(tag)
  73. if (className) {
  74. e.className = className
  75. }
  76. if (style) {
  77. e.style.cssText = style
  78. }
  79. if (typeof content == 'string') {
  80. e.appendChild(document.createTextNode(content))
  81. } else if (content) {
  82. for (var i = 0; i < content.length; ++i) {
  83. e.appendChild(content[i])
  84. }
  85. }
  86. return e
  87. }
  88. // wrapper for elt, which removes the elt from the accessibility tree
  89. function eltP(tag, content, className, style) {
  90. var e = elt(tag, content, className, style)
  91. e.setAttribute('role', 'presentation')
  92. return e
  93. }
  94. var range
  95. if (document.createRange) {
  96. range = function (node, start, end, endNode) {
  97. var r = document.createRange()
  98. r.setEnd(endNode || node, end)
  99. r.setStart(node, start)
  100. return r
  101. }
  102. } else {
  103. range = function (node, start, end) {
  104. var r = document.body.createTextRange()
  105. try {
  106. r.moveToElementText(node.parentNode)
  107. } catch (e) {
  108. return r
  109. }
  110. r.collapse(true)
  111. r.moveEnd('character', end)
  112. r.moveStart('character', start)
  113. return r
  114. }
  115. }
  116. function contains(parent, child) {
  117. if (child.nodeType == 3) {
  118. // Android browser always returns false when child is a textnode
  119. child = child.parentNode
  120. }
  121. if (parent.contains) {
  122. return parent.contains(child)
  123. }
  124. do {
  125. if (child.nodeType == 11) {
  126. child = child.host
  127. }
  128. if (child == parent) {
  129. return true
  130. }
  131. } while ((child = child.parentNode))
  132. }
  133. function activeElt() {
  134. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  135. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  136. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  137. var activeElement
  138. try {
  139. activeElement = document.activeElement
  140. } catch (e) {
  141. activeElement = document.body || null
  142. }
  143. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) {
  144. activeElement = activeElement.shadowRoot.activeElement
  145. }
  146. return activeElement
  147. }
  148. function addClass(node, cls) {
  149. var current = node.className
  150. if (!classTest(cls).test(current)) {
  151. node.className += (current ? ' ' : '') + cls
  152. }
  153. }
  154. function joinClasses(a, b) {
  155. var as = a.split(' ')
  156. for (var i = 0; i < as.length; i++) {
  157. if (as[i] && !classTest(as[i]).test(b)) {
  158. b += ' ' + as[i]
  159. }
  160. }
  161. return b
  162. }
  163. var selectInput = function (node) {
  164. node.select()
  165. }
  166. if (ios) {
  167. // Mobile Safari apparently has a bug where select() is broken.
  168. selectInput = function (node) {
  169. node.selectionStart = 0
  170. node.selectionEnd = node.value.length
  171. }
  172. } else if (ie) {
  173. // Suppress mysterious IE10 errors
  174. selectInput = function (node) {
  175. try {
  176. node.select()
  177. } catch (_e) {}
  178. }
  179. }
  180. function bind(f) {
  181. var args = Array.prototype.slice.call(arguments, 1)
  182. return function () {
  183. return f.apply(null, args)
  184. }
  185. }
  186. function copyObj(obj, target, overwrite) {
  187. if (!target) {
  188. target = {}
  189. }
  190. for (var prop in obj) {
  191. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) {
  192. target[prop] = obj[prop]
  193. }
  194. }
  195. return target
  196. }
  197. // Counts the column offset in a string, taking tabs into account.
  198. // Used mostly to find indentation.
  199. function countColumn(string, end, tabSize, startIndex, startValue) {
  200. if (end == null) {
  201. end = string.search(/[^\s\u00a0]/)
  202. if (end == -1) {
  203. end = string.length
  204. }
  205. }
  206. for (var i = startIndex || 0, n = startValue || 0; ; ) {
  207. var nextTab = string.indexOf('\t', i)
  208. if (nextTab < 0 || nextTab >= end) {
  209. return n + (end - i)
  210. }
  211. n += nextTab - i
  212. n += tabSize - (n % tabSize)
  213. i = nextTab + 1
  214. }
  215. }
  216. var Delayed = function () {
  217. this.id = null
  218. this.f = null
  219. this.time = 0
  220. this.handler = bind(this.onTimeout, this)
  221. }
  222. Delayed.prototype.onTimeout = function (self) {
  223. self.id = 0
  224. if (self.time <= +new Date()) {
  225. self.f()
  226. } else {
  227. setTimeout(self.handler, self.time - +new Date())
  228. }
  229. }
  230. Delayed.prototype.set = function (ms, f) {
  231. this.f = f
  232. var time = +new Date() + ms
  233. if (!this.id || time < this.time) {
  234. clearTimeout(this.id)
  235. this.id = setTimeout(this.handler, ms)
  236. this.time = time
  237. }
  238. }
  239. function indexOf(array, elt) {
  240. for (var i = 0; i < array.length; ++i) {
  241. if (array[i] == elt) {
  242. return i
  243. }
  244. }
  245. return -1
  246. }
  247. // Number of pixels added to scroller and sizer to hide scrollbar
  248. var scrollerGap = 50
  249. // Returned or thrown by various protocols to signal 'I'm not
  250. // handling this'.
  251. var Pass = {
  252. toString: function () {
  253. return 'CodeMirror.Pass'
  254. },
  255. }
  256. // Reused option objects for setSelection & friends
  257. var sel_dontScroll = { scroll: false },
  258. sel_mouse = { origin: '*mouse' },
  259. sel_move = { origin: '+move' }
  260. // The inverse of countColumn -- find the offset that corresponds to
  261. // a particular column.
  262. function findColumn(string, goal, tabSize) {
  263. for (var pos = 0, col = 0; ; ) {
  264. var nextTab = string.indexOf('\t', pos)
  265. if (nextTab == -1) {
  266. nextTab = string.length
  267. }
  268. var skipped = nextTab - pos
  269. if (nextTab == string.length || col + skipped >= goal) {
  270. return pos + Math.min(skipped, goal - col)
  271. }
  272. col += nextTab - pos
  273. col += tabSize - (col % tabSize)
  274. pos = nextTab + 1
  275. if (col >= goal) {
  276. return pos
  277. }
  278. }
  279. }
  280. var spaceStrs = ['']
  281. function spaceStr(n) {
  282. while (spaceStrs.length <= n) {
  283. spaceStrs.push(lst(spaceStrs) + ' ')
  284. }
  285. return spaceStrs[n]
  286. }
  287. function lst(arr) {
  288. return arr[arr.length - 1]
  289. }
  290. function map(array, f) {
  291. var out = []
  292. for (var i = 0; i < array.length; i++) {
  293. out[i] = f(array[i], i)
  294. }
  295. return out
  296. }
  297. function insertSorted(array, value, score) {
  298. var pos = 0,
  299. priority = score(value)
  300. while (pos < array.length && score(array[pos]) <= priority) {
  301. pos++
  302. }
  303. array.splice(pos, 0, value)
  304. }
  305. function nothing() {}
  306. function createObj(base, props) {
  307. var inst
  308. if (Object.create) {
  309. inst = Object.create(base)
  310. } else {
  311. nothing.prototype = base
  312. inst = new nothing()
  313. }
  314. if (props) {
  315. copyObj(props, inst)
  316. }
  317. return inst
  318. }
  319. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
  320. function isWordCharBasic(ch) {
  321. return /\w/.test(ch) || (ch > '\x80' && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
  322. }
  323. function isWordChar(ch, helper) {
  324. if (!helper) {
  325. return isWordCharBasic(ch)
  326. }
  327. if (helper.source.indexOf('\\w') > -1 && isWordCharBasic(ch)) {
  328. return true
  329. }
  330. return helper.test(ch)
  331. }
  332. function isEmpty(obj) {
  333. for (var n in obj) {
  334. if (obj.hasOwnProperty(n) && obj[n]) {
  335. return false
  336. }
  337. }
  338. return true
  339. }
  340. // Extending unicode characters. A series of a non-extending char +
  341. // any number of extending chars is treated as a single unit as far
  342. // as editing and measuring is concerned. This is not fully correct,
  343. // since some scripts/fonts/browsers also treat other configurations
  344. // of code points as a group.
  345. var extendingChars =
  346. /[\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]/
  347. function isExtendingChar(ch) {
  348. return ch.charCodeAt(0) >= 768 && extendingChars.test(ch)
  349. }
  350. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  351. function skipExtendingChars(str, pos, dir) {
  352. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) {
  353. pos += dir
  354. }
  355. return pos
  356. }
  357. // Returns the value from the range [`from`; `to`] that satisfies
  358. // `pred` and is closest to `from`. Assumes that at least `to`
  359. // satisfies `pred`. Supports `from` being greater than `to`.
  360. function findFirst(pred, from, to) {
  361. // At any point we are certain `to` satisfies `pred`, don't know
  362. // whether `from` does.
  363. var dir = from > to ? -1 : 1
  364. for (;;) {
  365. if (from == to) {
  366. return from
  367. }
  368. var midF = (from + to) / 2,
  369. mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF)
  370. if (mid == from) {
  371. return pred(mid) ? from : to
  372. }
  373. if (pred(mid)) {
  374. to = mid
  375. } else {
  376. from = mid + dir
  377. }
  378. }
  379. }
  380. // BIDI HELPERS
  381. function iterateBidiSections(order, from, to, f) {
  382. if (!order) {
  383. return f(from, to, 'ltr', 0)
  384. }
  385. var found = false
  386. for (var i = 0; i < order.length; ++i) {
  387. var part = order[i]
  388. if ((part.from < to && part.to > from) || (from == to && part.to == from)) {
  389. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? 'rtl' : 'ltr', i)
  390. found = true
  391. }
  392. }
  393. if (!found) {
  394. f(from, to, 'ltr')
  395. }
  396. }
  397. var bidiOther = null
  398. function getBidiPartAt(order, ch, sticky) {
  399. var found
  400. bidiOther = null
  401. for (var i = 0; i < order.length; ++i) {
  402. var cur = order[i]
  403. if (cur.from < ch && cur.to > ch) {
  404. return i
  405. }
  406. if (cur.to == ch) {
  407. if (cur.from != cur.to && sticky == 'before') {
  408. found = i
  409. } else {
  410. bidiOther = i
  411. }
  412. }
  413. if (cur.from == ch) {
  414. if (cur.from != cur.to && sticky != 'before') {
  415. found = i
  416. } else {
  417. bidiOther = i
  418. }
  419. }
  420. }
  421. return found != null ? found : bidiOther
  422. }
  423. // Bidirectional ordering algorithm
  424. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  425. // that this (partially) implements.
  426. // One-char codes used for character types:
  427. // L (L): Left-to-Right
  428. // R (R): Right-to-Left
  429. // r (AL): Right-to-Left Arabic
  430. // 1 (EN): European Number
  431. // + (ES): European Number Separator
  432. // % (ET): European Number Terminator
  433. // n (AN): Arabic Number
  434. // , (CS): Common Number Separator
  435. // m (NSM): Non-Spacing Mark
  436. // b (BN): Boundary Neutral
  437. // s (B): Paragraph Separator
  438. // t (S): Segment Separator
  439. // w (WS): Whitespace
  440. // N (ON): Other Neutrals
  441. // Returns null if characters are ordered as they appear
  442. // (left-to-right), or an array of sections ({from, to, level}
  443. // objects) in the order in which they occur visually.
  444. var bidiOrdering = (function () {
  445. // Character types for codepoints 0 to 0xff
  446. var lowTypes =
  447. 'bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN'
  448. // Character types for codepoints 0x600 to 0x6f9
  449. var arabicTypes =
  450. 'nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111'
  451. function charType(code) {
  452. if (code <= 0xf7) {
  453. return lowTypes.charAt(code)
  454. } else if (0x590 <= code && code <= 0x5f4) {
  455. return 'R'
  456. } else if (0x600 <= code && code <= 0x6f9) {
  457. return arabicTypes.charAt(code - 0x600)
  458. } else if (0x6ee <= code && code <= 0x8ac) {
  459. return 'r'
  460. } else if (0x2000 <= code && code <= 0x200b) {
  461. return 'w'
  462. } else if (code == 0x200c) {
  463. return 'b'
  464. } else {
  465. return 'L'
  466. }
  467. }
  468. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  469. var isNeutral = /[stwN]/,
  470. isStrong = /[LRr]/,
  471. countsAsLeft = /[Lb1n]/,
  472. countsAsNum = /[1n]/
  473. function BidiSpan(level, from, to) {
  474. this.level = level
  475. this.from = from
  476. this.to = to
  477. }
  478. return function (str, direction) {
  479. var outerType = direction == 'ltr' ? 'L' : 'R'
  480. if (str.length == 0 || (direction == 'ltr' && !bidiRE.test(str))) {
  481. return false
  482. }
  483. var len = str.length,
  484. types = []
  485. for (var i = 0; i < len; ++i) {
  486. types.push(charType(str.charCodeAt(i)))
  487. }
  488. // W1. Examine each non-spacing mark (NSM) in the level run, and
  489. // change the type of the NSM to the type of the previous
  490. // character. If the NSM is at the start of the level run, it will
  491. // get the type of sor.
  492. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  493. var type = types[i$1]
  494. if (type == 'm') {
  495. types[i$1] = prev
  496. } else {
  497. prev = type
  498. }
  499. }
  500. // W2. Search backwards from each instance of a European number
  501. // until the first strong type (R, L, AL, or sor) is found. If an
  502. // AL is found, change the type of the European number to Arabic
  503. // number.
  504. // W3. Change all ALs to R.
  505. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  506. var type$1 = types[i$2]
  507. if (type$1 == '1' && cur == 'r') {
  508. types[i$2] = 'n'
  509. } else if (isStrong.test(type$1)) {
  510. cur = type$1
  511. if (type$1 == 'r') {
  512. types[i$2] = 'R'
  513. }
  514. }
  515. }
  516. // W4. A single European separator between two European numbers
  517. // changes to a European number. A single common separator between
  518. // two numbers of the same type changes to that type.
  519. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  520. var type$2 = types[i$3]
  521. if (type$2 == '+' && prev$1 == '1' && types[i$3 + 1] == '1') {
  522. types[i$3] = '1'
  523. } else if (type$2 == ',' && prev$1 == types[i$3 + 1] && (prev$1 == '1' || prev$1 == 'n')) {
  524. types[i$3] = prev$1
  525. }
  526. prev$1 = type$2
  527. }
  528. // W5. A sequence of European terminators adjacent to European
  529. // numbers changes to all European numbers.
  530. // W6. Otherwise, separators and terminators change to Other
  531. // Neutral.
  532. for (var i$4 = 0; i$4 < len; ++i$4) {
  533. var type$3 = types[i$4]
  534. if (type$3 == ',') {
  535. types[i$4] = 'N'
  536. } else if (type$3 == '%') {
  537. var end = void 0
  538. for (end = i$4 + 1; end < len && types[end] == '%'; ++end) {}
  539. var replace = (i$4 && types[i$4 - 1] == '!') || (end < len && types[end] == '1') ? '1' : 'N'
  540. for (var j = i$4; j < end; ++j) {
  541. types[j] = replace
  542. }
  543. i$4 = end - 1
  544. }
  545. }
  546. // W7. Search backwards from each instance of a European number
  547. // until the first strong type (R, L, or sor) is found. If an L is
  548. // found, then change the type of the European number to L.
  549. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  550. var type$4 = types[i$5]
  551. if (cur$1 == 'L' && type$4 == '1') {
  552. types[i$5] = 'L'
  553. } else if (isStrong.test(type$4)) {
  554. cur$1 = type$4
  555. }
  556. }
  557. // N1. A sequence of neutrals takes the direction of the
  558. // surrounding strong text if the text on both sides has the same
  559. // direction. European and Arabic numbers act as if they were R in
  560. // terms of their influence on neutrals. Start-of-level-run (sor)
  561. // and end-of-level-run (eor) are used at level run boundaries.
  562. // N2. Any remaining neutrals take the embedding direction.
  563. for (var i$6 = 0; i$6 < len; ++i$6) {
  564. if (isNeutral.test(types[i$6])) {
  565. var end$1 = void 0
  566. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  567. var before = (i$6 ? types[i$6 - 1] : outerType) == 'L'
  568. var after = (end$1 < len ? types[end$1] : outerType) == 'L'
  569. var replace$1 = before == after ? (before ? 'L' : 'R') : outerType
  570. for (var j$1 = i$6; j$1 < end$1; ++j$1) {
  571. types[j$1] = replace$1
  572. }
  573. i$6 = end$1 - 1
  574. }
  575. }
  576. // Here we depart from the documented algorithm, in order to avoid
  577. // building up an actual levels array. Since there are only three
  578. // levels (0, 1, 2) in an implementation that doesn't take
  579. // explicit embedding into account, we can build up the order on
  580. // the fly, without following the level-based algorithm.
  581. var order = [],
  582. m
  583. for (var i$7 = 0; i$7 < len; ) {
  584. if (countsAsLeft.test(types[i$7])) {
  585. var start = i$7
  586. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  587. order.push(new BidiSpan(0, start, i$7))
  588. } else {
  589. var pos = i$7,
  590. at = order.length,
  591. isRTL = direction == 'rtl' ? 1 : 0
  592. for (++i$7; i$7 < len && types[i$7] != 'L'; ++i$7) {}
  593. for (var j$2 = pos; j$2 < i$7; ) {
  594. if (countsAsNum.test(types[j$2])) {
  595. if (pos < j$2) {
  596. order.splice(at, 0, new BidiSpan(1, pos, j$2))
  597. at += isRTL
  598. }
  599. var nstart = j$2
  600. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  601. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  602. at += isRTL
  603. pos = j$2
  604. } else {
  605. ++j$2
  606. }
  607. }
  608. if (pos < i$7) {
  609. order.splice(at, 0, new BidiSpan(1, pos, i$7))
  610. }
  611. }
  612. }
  613. if (direction == 'ltr') {
  614. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  615. order[0].from = m[0].length
  616. order.unshift(new BidiSpan(0, 0, m[0].length))
  617. }
  618. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  619. lst(order).to -= m[0].length
  620. order.push(new BidiSpan(0, len - m[0].length, len))
  621. }
  622. }
  623. return direction == 'rtl' ? order.reverse() : order
  624. }
  625. })()
  626. // Get the bidi ordering for the given line (and cache it). Returns
  627. // false for lines that are fully left-to-right, and an array of
  628. // BidiSpan objects otherwise.
  629. function getOrder(line, direction) {
  630. var order = line.order
  631. if (order == null) {
  632. order = line.order = bidiOrdering(line.text, direction)
  633. }
  634. return order
  635. }
  636. // EVENT HANDLING
  637. // Lightweight event framework. on/off also work on DOM nodes,
  638. // registering native DOM handlers.
  639. var noHandlers = []
  640. var on = function (emitter, type, f) {
  641. if (emitter.addEventListener) {
  642. emitter.addEventListener(type, f, false)
  643. } else if (emitter.attachEvent) {
  644. emitter.attachEvent('on' + type, f)
  645. } else {
  646. var map = emitter._handlers || (emitter._handlers = {})
  647. map[type] = (map[type] || noHandlers).concat(f)
  648. }
  649. }
  650. function getHandlers(emitter, type) {
  651. return (emitter._handlers && emitter._handlers[type]) || noHandlers
  652. }
  653. function off(emitter, type, f) {
  654. if (emitter.removeEventListener) {
  655. emitter.removeEventListener(type, f, false)
  656. } else if (emitter.detachEvent) {
  657. emitter.detachEvent('on' + type, f)
  658. } else {
  659. var map = emitter._handlers,
  660. arr = map && map[type]
  661. if (arr) {
  662. var index = indexOf(arr, f)
  663. if (index > -1) {
  664. map[type] = arr.slice(0, index).concat(arr.slice(index + 1))
  665. }
  666. }
  667. }
  668. }
  669. function signal(emitter, type /*, values...*/) {
  670. var handlers = getHandlers(emitter, type)
  671. if (!handlers.length) {
  672. return
  673. }
  674. var args = Array.prototype.slice.call(arguments, 2)
  675. for (var i = 0; i < handlers.length; ++i) {
  676. handlers[i].apply(null, args)
  677. }
  678. }
  679. // The DOM events that CodeMirror handles can be overridden by
  680. // registering a (non-DOM) handler on the editor for the event name,
  681. // and preventDefault-ing the event in that handler.
  682. function signalDOMEvent(cm, e, override) {
  683. if (typeof e == 'string') {
  684. e = {
  685. type: e,
  686. preventDefault: function () {
  687. this.defaultPrevented = true
  688. },
  689. }
  690. }
  691. signal(cm, override || e.type, cm, e)
  692. return e_defaultPrevented(e) || e.codemirrorIgnore
  693. }
  694. function signalCursorActivity(cm) {
  695. var arr = cm._handlers && cm._handlers.cursorActivity
  696. if (!arr) {
  697. return
  698. }
  699. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  700. for (var i = 0; i < arr.length; ++i) {
  701. if (indexOf(set, arr[i]) == -1) {
  702. set.push(arr[i])
  703. }
  704. }
  705. }
  706. function hasHandler(emitter, type) {
  707. return getHandlers(emitter, type).length > 0
  708. }
  709. // Add on and off methods to a constructor's prototype, to make
  710. // registering events on such objects more convenient.
  711. function eventMixin(ctor) {
  712. ctor.prototype.on = function (type, f) {
  713. on(this, type, f)
  714. }
  715. ctor.prototype.off = function (type, f) {
  716. off(this, type, f)
  717. }
  718. }
  719. // Due to the fact that we still support jurassic IE versions, some
  720. // compatibility wrappers are needed.
  721. function e_preventDefault(e) {
  722. if (e.preventDefault) {
  723. e.preventDefault()
  724. } else {
  725. e.returnValue = false
  726. }
  727. }
  728. function e_stopPropagation(e) {
  729. if (e.stopPropagation) {
  730. e.stopPropagation()
  731. } else {
  732. e.cancelBubble = true
  733. }
  734. }
  735. function e_defaultPrevented(e) {
  736. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  737. }
  738. function e_stop(e) {
  739. e_preventDefault(e)
  740. e_stopPropagation(e)
  741. }
  742. function e_target(e) {
  743. return e.target || e.srcElement
  744. }
  745. function e_button(e) {
  746. var b = e.which
  747. if (b == null) {
  748. if (e.button & 1) {
  749. b = 1
  750. } else if (e.button & 2) {
  751. b = 3
  752. } else if (e.button & 4) {
  753. b = 2
  754. }
  755. }
  756. if (mac && e.ctrlKey && b == 1) {
  757. b = 3
  758. }
  759. return b
  760. }
  761. // Detect drag-and-drop
  762. var dragAndDrop = (function () {
  763. // There is *some* kind of drag-and-drop support in IE6-8, but I
  764. // couldn't get it to work yet.
  765. if (ie && ie_version < 9) {
  766. return false
  767. }
  768. var div = elt('div')
  769. return 'draggable' in div || 'dragDrop' in div
  770. })()
  771. var zwspSupported
  772. function zeroWidthElement(measure) {
  773. if (zwspSupported == null) {
  774. var test = elt('span', '\u200b')
  775. removeChildrenAndAdd(measure, elt('span', [test, document.createTextNode('x')]))
  776. if (measure.firstChild.offsetHeight != 0) {
  777. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8)
  778. }
  779. }
  780. var node = zwspSupported ? elt('span', '\u200b') : elt('span', '\u00a0', null, 'display: inline-block; width: 1px; margin-right: -1px')
  781. node.setAttribute('cm-text', '')
  782. return node
  783. }
  784. // Feature-detect IE's crummy client rect reporting for bidi text
  785. var badBidiRects
  786. function hasBadBidiRects(measure) {
  787. if (badBidiRects != null) {
  788. return badBidiRects
  789. }
  790. var txt = removeChildrenAndAdd(measure, document.createTextNode('A\u062eA'))
  791. var r0 = range(txt, 0, 1).getBoundingClientRect()
  792. var r1 = range(txt, 1, 2).getBoundingClientRect()
  793. removeChildren(measure)
  794. if (!r0 || r0.left == r0.right) {
  795. return false
  796. } // Safari returns null in some cases (#2780)
  797. return (badBidiRects = r1.right - r0.right < 3)
  798. }
  799. // See if "".split is the broken IE version, if so, provide an
  800. // alternative way to split lines.
  801. var splitLinesAuto =
  802. '\n\nb'.split(/\n/).length != 3
  803. ? function (string) {
  804. var pos = 0,
  805. result = [],
  806. l = string.length
  807. while (pos <= l) {
  808. var nl = string.indexOf('\n', pos)
  809. if (nl == -1) {
  810. nl = string.length
  811. }
  812. var line = string.slice(pos, string.charAt(nl - 1) == '\r' ? nl - 1 : nl)
  813. var rt = line.indexOf('\r')
  814. if (rt != -1) {
  815. result.push(line.slice(0, rt))
  816. pos += rt + 1
  817. } else {
  818. result.push(line)
  819. pos = nl + 1
  820. }
  821. }
  822. return result
  823. }
  824. : function (string) {
  825. return string.split(/\r\n?|\n/)
  826. }
  827. var hasSelection = window.getSelection
  828. ? function (te) {
  829. try {
  830. return te.selectionStart != te.selectionEnd
  831. } catch (e) {
  832. return false
  833. }
  834. }
  835. : function (te) {
  836. var range
  837. try {
  838. range = te.ownerDocument.selection.createRange()
  839. } catch (e) {}
  840. if (!range || range.parentElement() != te) {
  841. return false
  842. }
  843. return range.compareEndPoints('StartToEnd', range) != 0
  844. }
  845. var hasCopyEvent = (function () {
  846. var e = elt('div')
  847. if ('oncopy' in e) {
  848. return true
  849. }
  850. e.setAttribute('oncopy', 'return;')
  851. return typeof e.oncopy == 'function'
  852. })()
  853. var badZoomedRects = null
  854. function hasBadZoomedRects(measure) {
  855. if (badZoomedRects != null) {
  856. return badZoomedRects
  857. }
  858. var node = removeChildrenAndAdd(measure, elt('span', 'x'))
  859. var normal = node.getBoundingClientRect()
  860. var fromRange = range(node, 0, 1).getBoundingClientRect()
  861. return (badZoomedRects = Math.abs(normal.left - fromRange.left) > 1)
  862. }
  863. // Known modes, by name and by MIME
  864. var modes = {},
  865. mimeModes = {}
  866. // Extra arguments are stored as the mode's dependencies, which is
  867. // used by (legacy) mechanisms like loadmode.js to automatically
  868. // load a mode. (Preferred mechanism is the require/define calls.)
  869. function defineMode(name, mode) {
  870. if (arguments.length > 2) {
  871. mode.dependencies = Array.prototype.slice.call(arguments, 2)
  872. }
  873. modes[name] = mode
  874. }
  875. function defineMIME(mime, spec) {
  876. mimeModes[mime] = spec
  877. }
  878. // Given a MIME type, a {name, ...options} config object, or a name
  879. // string, return a mode config object.
  880. function resolveMode(spec) {
  881. if (typeof spec == 'string' && mimeModes.hasOwnProperty(spec)) {
  882. spec = mimeModes[spec]
  883. } else if (spec && typeof spec.name == 'string' && mimeModes.hasOwnProperty(spec.name)) {
  884. var found = mimeModes[spec.name]
  885. if (typeof found == 'string') {
  886. found = { name: found }
  887. }
  888. spec = createObj(found, spec)
  889. spec.name = found.name
  890. } else if (typeof spec == 'string' && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  891. return resolveMode('application/xml')
  892. } else if (typeof spec == 'string' && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  893. return resolveMode('application/json')
  894. }
  895. if (typeof spec == 'string') {
  896. return { name: spec }
  897. } else {
  898. return spec || { name: 'null' }
  899. }
  900. }
  901. // Given a mode spec (anything that resolveMode accepts), find and
  902. // initialize an actual mode object.
  903. function getMode(options, spec) {
  904. spec = resolveMode(spec)
  905. var mfactory = modes[spec.name]
  906. if (!mfactory) {
  907. return getMode(options, 'text/plain')
  908. }
  909. var modeObj = mfactory(options, spec)
  910. if (modeExtensions.hasOwnProperty(spec.name)) {
  911. var exts = modeExtensions[spec.name]
  912. for (var prop in exts) {
  913. if (!exts.hasOwnProperty(prop)) {
  914. continue
  915. }
  916. if (modeObj.hasOwnProperty(prop)) {
  917. modeObj['_' + prop] = modeObj[prop]
  918. }
  919. modeObj[prop] = exts[prop]
  920. }
  921. }
  922. modeObj.name = spec.name
  923. if (spec.helperType) {
  924. modeObj.helperType = spec.helperType
  925. }
  926. if (spec.modeProps) {
  927. for (var prop$1 in spec.modeProps) {
  928. modeObj[prop$1] = spec.modeProps[prop$1]
  929. }
  930. }
  931. return modeObj
  932. }
  933. // This can be used to attach properties to mode objects from
  934. // outside the actual mode definition.
  935. var modeExtensions = {}
  936. function extendMode(mode, properties) {
  937. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  938. copyObj(properties, exts)
  939. }
  940. function copyState(mode, state) {
  941. if (state === true) {
  942. return state
  943. }
  944. if (mode.copyState) {
  945. return mode.copyState(state)
  946. }
  947. var nstate = {}
  948. for (var n in state) {
  949. var val = state[n]
  950. if (val instanceof Array) {
  951. val = val.concat([])
  952. }
  953. nstate[n] = val
  954. }
  955. return nstate
  956. }
  957. // Given a mode and a state (for that mode), find the inner mode and
  958. // state at the position that the state refers to.
  959. function innerMode(mode, state) {
  960. var info
  961. while (mode.innerMode) {
  962. info = mode.innerMode(state)
  963. if (!info || info.mode == mode) {
  964. break
  965. }
  966. state = info.state
  967. mode = info.mode
  968. }
  969. return info || { mode: mode, state: state }
  970. }
  971. function startState(mode, a1, a2) {
  972. return mode.startState ? mode.startState(a1, a2) : true
  973. }
  974. // STRING STREAM
  975. // Fed to the mode parsers, provides helper functions to make
  976. // parsers more succinct.
  977. var StringStream = function (string, tabSize, lineOracle) {
  978. this.pos = this.start = 0
  979. this.string = string
  980. this.tabSize = tabSize || 8
  981. this.lastColumnPos = this.lastColumnValue = 0
  982. this.lineStart = 0
  983. this.lineOracle = lineOracle
  984. }
  985. StringStream.prototype.eol = function () {
  986. return this.pos >= this.string.length
  987. }
  988. StringStream.prototype.sol = function () {
  989. return this.pos == this.lineStart
  990. }
  991. StringStream.prototype.peek = function () {
  992. return this.string.charAt(this.pos) || undefined
  993. }
  994. StringStream.prototype.next = function () {
  995. if (this.pos < this.string.length) {
  996. return this.string.charAt(this.pos++)
  997. }
  998. }
  999. StringStream.prototype.eat = function (match) {
  1000. var ch = this.string.charAt(this.pos)
  1001. var ok
  1002. if (typeof match == 'string') {
  1003. ok = ch == match
  1004. } else {
  1005. ok = ch && (match.test ? match.test(ch) : match(ch))
  1006. }
  1007. if (ok) {
  1008. ++this.pos
  1009. return ch
  1010. }
  1011. }
  1012. StringStream.prototype.eatWhile = function (match) {
  1013. var start = this.pos
  1014. while (this.eat(match)) {}
  1015. return this.pos > start
  1016. }
  1017. StringStream.prototype.eatSpace = function () {
  1018. var start = this.pos
  1019. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) {
  1020. ++this.pos
  1021. }
  1022. return this.pos > start
  1023. }
  1024. StringStream.prototype.skipToEnd = function () {
  1025. this.pos = this.string.length
  1026. }
  1027. StringStream.prototype.skipTo = function (ch) {
  1028. var found = this.string.indexOf(ch, this.pos)
  1029. if (found > -1) {
  1030. this.pos = found
  1031. return true
  1032. }
  1033. }
  1034. StringStream.prototype.backUp = function (n) {
  1035. this.pos -= n
  1036. }
  1037. StringStream.prototype.column = function () {
  1038. if (this.lastColumnPos < this.start) {
  1039. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1040. this.lastColumnPos = this.start
  1041. }
  1042. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1043. }
  1044. StringStream.prototype.indentation = function () {
  1045. return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1046. }
  1047. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1048. if (typeof pattern == 'string') {
  1049. var cased = function (str) {
  1050. return caseInsensitive ? str.toLowerCase() : str
  1051. }
  1052. var substr = this.string.substr(this.pos, pattern.length)
  1053. if (cased(substr) == cased(pattern)) {
  1054. if (consume !== false) {
  1055. this.pos += pattern.length
  1056. }
  1057. return true
  1058. }
  1059. } else {
  1060. var match = this.string.slice(this.pos).match(pattern)
  1061. if (match && match.index > 0) {
  1062. return null
  1063. }
  1064. if (match && consume !== false) {
  1065. this.pos += match[0].length
  1066. }
  1067. return match
  1068. }
  1069. }
  1070. StringStream.prototype.current = function () {
  1071. return this.string.slice(this.start, this.pos)
  1072. }
  1073. StringStream.prototype.hideFirstChars = function (n, inner) {
  1074. this.lineStart += n
  1075. try {
  1076. return inner()
  1077. } finally {
  1078. this.lineStart -= n
  1079. }
  1080. }
  1081. StringStream.prototype.lookAhead = function (n) {
  1082. var oracle = this.lineOracle
  1083. return oracle && oracle.lookAhead(n)
  1084. }
  1085. StringStream.prototype.baseToken = function () {
  1086. var oracle = this.lineOracle
  1087. return oracle && oracle.baseToken(this.pos)
  1088. }
  1089. // Find the line object corresponding to the given line number.
  1090. function getLine(doc, n) {
  1091. n -= doc.first
  1092. if (n < 0 || n >= doc.size) {
  1093. throw new Error('There is no line ' + (n + doc.first) + ' in the document.')
  1094. }
  1095. var chunk = doc
  1096. while (!chunk.lines) {
  1097. for (var i = 0; ; ++i) {
  1098. var child = chunk.children[i],
  1099. sz = child.chunkSize()
  1100. if (n < sz) {
  1101. chunk = child
  1102. break
  1103. }
  1104. n -= sz
  1105. }
  1106. }
  1107. return chunk.lines[n]
  1108. }
  1109. // Get the part of a document between two positions, as an array of
  1110. // strings.
  1111. function getBetween(doc, start, end) {
  1112. var out = [],
  1113. n = start.line
  1114. doc.iter(start.line, end.line + 1, function (line) {
  1115. var text = line.text
  1116. if (n == end.line) {
  1117. text = text.slice(0, end.ch)
  1118. }
  1119. if (n == start.line) {
  1120. text = text.slice(start.ch)
  1121. }
  1122. out.push(text)
  1123. ++n
  1124. })
  1125. return out
  1126. }
  1127. // Get the lines between from and to, as array of strings.
  1128. function getLines(doc, from, to) {
  1129. var out = []
  1130. doc.iter(from, to, function (line) {
  1131. out.push(line.text)
  1132. }) // iter aborts when callback returns truthy value
  1133. return out
  1134. }
  1135. // Update the height of a line, propagating the height change
  1136. // upwards to parent nodes.
  1137. function updateLineHeight(line, height) {
  1138. var diff = height - line.height
  1139. if (diff) {
  1140. for (var n = line; n; n = n.parent) {
  1141. n.height += diff
  1142. }
  1143. }
  1144. }
  1145. // Given a line object, find its line number by walking up through
  1146. // its parent links.
  1147. function lineNo(line) {
  1148. if (line.parent == null) {
  1149. return null
  1150. }
  1151. var cur = line.parent,
  1152. no = indexOf(cur.lines, line)
  1153. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  1154. for (var i = 0; ; ++i) {
  1155. if (chunk.children[i] == cur) {
  1156. break
  1157. }
  1158. no += chunk.children[i].chunkSize()
  1159. }
  1160. }
  1161. return no + cur.first
  1162. }
  1163. // Find the line at the given vertical position, using the height
  1164. // information in the document tree.
  1165. function lineAtHeight(chunk, h) {
  1166. var n = chunk.first
  1167. outer: do {
  1168. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  1169. var child = chunk.children[i$1],
  1170. ch = child.height
  1171. if (h < ch) {
  1172. chunk = child
  1173. continue outer
  1174. }
  1175. h -= ch
  1176. n += child.chunkSize()
  1177. }
  1178. return n
  1179. } while (!chunk.lines)
  1180. var i = 0
  1181. for (; i < chunk.lines.length; ++i) {
  1182. var line = chunk.lines[i],
  1183. lh = line.height
  1184. if (h < lh) {
  1185. break
  1186. }
  1187. h -= lh
  1188. }
  1189. return n + i
  1190. }
  1191. function isLine(doc, l) {
  1192. return l >= doc.first && l < doc.first + doc.size
  1193. }
  1194. function lineNumberFor(options, i) {
  1195. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  1196. }
  1197. // A Pos instance represents a position within the text.
  1198. function Pos(line, ch, sticky) {
  1199. if (sticky === void 0) sticky = null
  1200. if (!(this instanceof Pos)) {
  1201. return new Pos(line, ch, sticky)
  1202. }
  1203. this.line = line
  1204. this.ch = ch
  1205. this.sticky = sticky
  1206. }
  1207. // Compare two positions, return 0 if they are the same, a negative
  1208. // number when a is less, and a positive number otherwise.
  1209. function cmp(a, b) {
  1210. return a.line - b.line || a.ch - b.ch
  1211. }
  1212. function equalCursorPos(a, b) {
  1213. return a.sticky == b.sticky && cmp(a, b) == 0
  1214. }
  1215. function copyPos(x) {
  1216. return Pos(x.line, x.ch)
  1217. }
  1218. function maxPos(a, b) {
  1219. return cmp(a, b) < 0 ? b : a
  1220. }
  1221. function minPos(a, b) {
  1222. return cmp(a, b) < 0 ? a : b
  1223. }
  1224. // Most of the external API clips given positions to make sure they
  1225. // actually exist within the document.
  1226. function clipLine(doc, n) {
  1227. return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))
  1228. }
  1229. function clipPos(doc, pos) {
  1230. if (pos.line < doc.first) {
  1231. return Pos(doc.first, 0)
  1232. }
  1233. var last = doc.first + doc.size - 1
  1234. if (pos.line > last) {
  1235. return Pos(last, getLine(doc, last).text.length)
  1236. }
  1237. return clipToLen(pos, getLine(doc, pos.line).text.length)
  1238. }
  1239. function clipToLen(pos, linelen) {
  1240. var ch = pos.ch
  1241. if (ch == null || ch > linelen) {
  1242. return Pos(pos.line, linelen)
  1243. } else if (ch < 0) {
  1244. return Pos(pos.line, 0)
  1245. } else {
  1246. return pos
  1247. }
  1248. }
  1249. function clipPosArray(doc, array) {
  1250. var out = []
  1251. for (var i = 0; i < array.length; i++) {
  1252. out[i] = clipPos(doc, array[i])
  1253. }
  1254. return out
  1255. }
  1256. var SavedContext = function (state, lookAhead) {
  1257. this.state = state
  1258. this.lookAhead = lookAhead
  1259. }
  1260. var Context = function (doc, state, line, lookAhead) {
  1261. this.state = state
  1262. this.doc = doc
  1263. this.line = line
  1264. this.maxLookAhead = lookAhead || 0
  1265. this.baseTokens = null
  1266. this.baseTokenPos = 1
  1267. }
  1268. Context.prototype.lookAhead = function (n) {
  1269. var line = this.doc.getLine(this.line + n)
  1270. if (line != null && n > this.maxLookAhead) {
  1271. this.maxLookAhead = n
  1272. }
  1273. return line
  1274. }
  1275. Context.prototype.baseToken = function (n) {
  1276. if (!this.baseTokens) {
  1277. return null
  1278. }
  1279. while (this.baseTokens[this.baseTokenPos] <= n) {
  1280. this.baseTokenPos += 2
  1281. }
  1282. var type = this.baseTokens[this.baseTokenPos + 1]
  1283. return { type: type && type.replace(/( |^)overlay .*/, ''), size: this.baseTokens[this.baseTokenPos] - n }
  1284. }
  1285. Context.prototype.nextLine = function () {
  1286. this.line++
  1287. if (this.maxLookAhead > 0) {
  1288. this.maxLookAhead--
  1289. }
  1290. }
  1291. Context.fromSaved = function (doc, saved, line) {
  1292. if (saved instanceof SavedContext) {
  1293. return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead)
  1294. } else {
  1295. return new Context(doc, copyState(doc.mode, saved), line)
  1296. }
  1297. }
  1298. Context.prototype.save = function (copy) {
  1299. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state
  1300. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1301. }
  1302. // Compute a style array (an array starting with a mode generation
  1303. // -- for invalidation -- followed by pairs of end positions and
  1304. // style strings), which is used to highlight the tokens on the
  1305. // line.
  1306. function highlightLine(cm, line, context, forceToEnd) {
  1307. // A styles array always starts with a number identifying the
  1308. // mode/overlays that it is based on (for easy invalidation).
  1309. var st = [cm.state.modeGen],
  1310. lineClasses = {}
  1311. // Compute the base array of styles
  1312. runMode(
  1313. cm,
  1314. line.text,
  1315. cm.doc.mode,
  1316. context,
  1317. function (end, style) {
  1318. return st.push(end, style)
  1319. },
  1320. lineClasses,
  1321. forceToEnd
  1322. )
  1323. var state = context.state
  1324. // Run overlays, adjust style array.
  1325. var loop = function (o) {
  1326. context.baseTokens = st
  1327. var overlay = cm.state.overlays[o],
  1328. i = 1,
  1329. at = 0
  1330. context.state = true
  1331. runMode(
  1332. cm,
  1333. line.text,
  1334. overlay.mode,
  1335. context,
  1336. function (end, style) {
  1337. var start = i
  1338. // Ensure there's a token end at the current position, and that i points at it
  1339. while (at < end) {
  1340. var i_end = st[i]
  1341. if (i_end > end) {
  1342. st.splice(i, 1, end, st[i + 1], i_end)
  1343. }
  1344. i += 2
  1345. at = Math.min(end, i_end)
  1346. }
  1347. if (!style) {
  1348. return
  1349. }
  1350. if (overlay.opaque) {
  1351. st.splice(start, i - start, end, 'overlay ' + style)
  1352. i = start + 2
  1353. } else {
  1354. for (; start < i; start += 2) {
  1355. var cur = st[start + 1]
  1356. st[start + 1] = (cur ? cur + ' ' : '') + 'overlay ' + style
  1357. }
  1358. }
  1359. },
  1360. lineClasses
  1361. )
  1362. context.state = state
  1363. context.baseTokens = null
  1364. context.baseTokenPos = 1
  1365. }
  1366. for (var o = 0; o < cm.state.overlays.length; ++o) loop(o)
  1367. return { styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null }
  1368. }
  1369. function getLineStyles(cm, line, updateFrontier) {
  1370. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1371. var context = getContextBefore(cm, lineNo(line))
  1372. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state)
  1373. var result = highlightLine(cm, line, context)
  1374. if (resetState) {
  1375. context.state = resetState
  1376. }
  1377. line.stateAfter = context.save(!resetState)
  1378. line.styles = result.styles
  1379. if (result.classes) {
  1380. line.styleClasses = result.classes
  1381. } else if (line.styleClasses) {
  1382. line.styleClasses = null
  1383. }
  1384. if (updateFrontier === cm.doc.highlightFrontier) {
  1385. cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier)
  1386. }
  1387. }
  1388. return line.styles
  1389. }
  1390. function getContextBefore(cm, n, precise) {
  1391. var doc = cm.doc,
  1392. display = cm.display
  1393. if (!doc.mode.startState) {
  1394. return new Context(doc, true, n)
  1395. }
  1396. var start = findStartLine(cm, n, precise)
  1397. var saved = start > doc.first && getLine(doc, start - 1).stateAfter
  1398. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start)
  1399. doc.iter(start, n, function (line) {
  1400. processLine(cm, line.text, context)
  1401. var pos = context.line
  1402. line.stateAfter = pos == n - 1 || pos % 5 == 0 || (pos >= display.viewFrom && pos < display.viewTo) ? context.save() : null
  1403. context.nextLine()
  1404. })
  1405. if (precise) {
  1406. doc.modeFrontier = context.line
  1407. }
  1408. return context
  1409. }
  1410. // Lightweight form of highlight -- proceed over this line and
  1411. // update state, but don't save a style array. Used for lines that
  1412. // aren't currently visible.
  1413. function processLine(cm, text, context, startAt) {
  1414. var mode = cm.doc.mode
  1415. var stream = new StringStream(text, cm.options.tabSize, context)
  1416. stream.start = stream.pos = startAt || 0
  1417. if (text == '') {
  1418. callBlankLine(mode, context.state)
  1419. }
  1420. while (!stream.eol()) {
  1421. readToken(mode, stream, context.state)
  1422. stream.start = stream.pos
  1423. }
  1424. }
  1425. function callBlankLine(mode, state) {
  1426. if (mode.blankLine) {
  1427. return mode.blankLine(state)
  1428. }
  1429. if (!mode.innerMode) {
  1430. return
  1431. }
  1432. var inner = innerMode(mode, state)
  1433. if (inner.mode.blankLine) {
  1434. return inner.mode.blankLine(inner.state)
  1435. }
  1436. }
  1437. function readToken(mode, stream, state, inner) {
  1438. for (var i = 0; i < 10; i++) {
  1439. if (inner) {
  1440. inner[0] = innerMode(mode, state).mode
  1441. }
  1442. var style = mode.token(stream, state)
  1443. if (stream.pos > stream.start) {
  1444. return style
  1445. }
  1446. }
  1447. throw new Error('Mode ' + mode.name + ' failed to advance stream.')
  1448. }
  1449. var Token = function (stream, type, state) {
  1450. this.start = stream.start
  1451. this.end = stream.pos
  1452. this.string = stream.current()
  1453. this.type = type || null
  1454. this.state = state
  1455. }
  1456. // Utility for getTokenAt and getLineTokens
  1457. function takeToken(cm, pos, precise, asArray) {
  1458. var doc = cm.doc,
  1459. mode = doc.mode,
  1460. style
  1461. pos = clipPos(doc, pos)
  1462. var line = getLine(doc, pos.line),
  1463. context = getContextBefore(cm, pos.line, precise)
  1464. var stream = new StringStream(line.text, cm.options.tabSize, context),
  1465. tokens
  1466. if (asArray) {
  1467. tokens = []
  1468. }
  1469. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1470. stream.start = stream.pos
  1471. style = readToken(mode, stream, context.state)
  1472. if (asArray) {
  1473. tokens.push(new Token(stream, style, copyState(doc.mode, context.state)))
  1474. }
  1475. }
  1476. return asArray ? tokens : new Token(stream, style, context.state)
  1477. }
  1478. function extractLineClasses(type, output) {
  1479. if (type) {
  1480. for (;;) {
  1481. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1482. if (!lineClass) {
  1483. break
  1484. }
  1485. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1486. var prop = lineClass[1] ? 'bgClass' : 'textClass'
  1487. if (output[prop] == null) {
  1488. output[prop] = lineClass[2]
  1489. } else if (!new RegExp('(?:^|\\s)' + lineClass[2] + '(?:$|\\s)').test(output[prop])) {
  1490. output[prop] += ' ' + lineClass[2]
  1491. }
  1492. }
  1493. }
  1494. return type
  1495. }
  1496. // Run the given mode's parser over a line, calling f for each token.
  1497. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1498. var flattenSpans = mode.flattenSpans
  1499. if (flattenSpans == null) {
  1500. flattenSpans = cm.options.flattenSpans
  1501. }
  1502. var curStart = 0,
  1503. curStyle = null
  1504. var stream = new StringStream(text, cm.options.tabSize, context),
  1505. style
  1506. var inner = cm.options.addModeClass && [null]
  1507. if (text == '') {
  1508. extractLineClasses(callBlankLine(mode, context.state), lineClasses)
  1509. }
  1510. while (!stream.eol()) {
  1511. if (stream.pos > cm.options.maxHighlightLength) {
  1512. flattenSpans = false
  1513. if (forceToEnd) {
  1514. processLine(cm, text, context, stream.pos)
  1515. }
  1516. stream.pos = text.length
  1517. style = null
  1518. } else {
  1519. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
  1520. }
  1521. if (inner) {
  1522. var mName = inner[0].name
  1523. if (mName) {
  1524. style = 'm-' + (style ? mName + ' ' + style : mName)
  1525. }
  1526. }
  1527. if (!flattenSpans || curStyle != style) {
  1528. while (curStart < stream.start) {
  1529. curStart = Math.min(stream.start, curStart + 5000)
  1530. f(curStart, curStyle)
  1531. }
  1532. curStyle = style
  1533. }
  1534. stream.start = stream.pos
  1535. }
  1536. while (curStart < stream.pos) {
  1537. // Webkit seems to refuse to render text nodes longer than 57444
  1538. // characters, and returns inaccurate measurements in nodes
  1539. // starting around 5000 chars.
  1540. var pos = Math.min(stream.pos, curStart + 5000)
  1541. f(pos, curStyle)
  1542. curStart = pos
  1543. }
  1544. }
  1545. // Finds the line to start with when starting a parse. Tries to
  1546. // find a line with a stateAfter, so that it can start with a
  1547. // valid state. If that fails, it returns the line with the
  1548. // smallest indentation, which tends to need the least context to
  1549. // parse correctly.
  1550. function findStartLine(cm, n, precise) {
  1551. var minindent,
  1552. minline,
  1553. doc = cm.doc
  1554. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1555. for (var search = n; search > lim; --search) {
  1556. if (search <= doc.first) {
  1557. return doc.first
  1558. }
  1559. var line = getLine(doc, search - 1),
  1560. after = line.stateAfter
  1561. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) {
  1562. return search
  1563. }
  1564. var indented = countColumn(line.text, null, cm.options.tabSize)
  1565. if (minline == null || minindent > indented) {
  1566. minline = search - 1
  1567. minindent = indented
  1568. }
  1569. }
  1570. return minline
  1571. }
  1572. function retreatFrontier(doc, n) {
  1573. doc.modeFrontier = Math.min(doc.modeFrontier, n)
  1574. if (doc.highlightFrontier < n - 10) {
  1575. return
  1576. }
  1577. var start = doc.first
  1578. for (var line = n - 1; line > start; line--) {
  1579. var saved = getLine(doc, line).stateAfter
  1580. // change is on 3
  1581. // state on line 1 looked ahead 2 -- so saw 3
  1582. // test 1 + 2 < 3 should cover this
  1583. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1584. start = line + 1
  1585. break
  1586. }
  1587. }
  1588. doc.highlightFrontier = Math.min(doc.highlightFrontier, start)
  1589. }
  1590. // Optimize some code when these features are not used.
  1591. var sawReadOnlySpans = false,
  1592. sawCollapsedSpans = false
  1593. function seeReadOnlySpans() {
  1594. sawReadOnlySpans = true
  1595. }
  1596. function seeCollapsedSpans() {
  1597. sawCollapsedSpans = true
  1598. }
  1599. // TEXTMARKER SPANS
  1600. function MarkedSpan(marker, from, to) {
  1601. this.marker = marker
  1602. this.from = from
  1603. this.to = to
  1604. }
  1605. // Search an array of spans for a span matching the given marker.
  1606. function getMarkedSpanFor(spans, marker) {
  1607. if (spans) {
  1608. for (var i = 0; i < spans.length; ++i) {
  1609. var span = spans[i]
  1610. if (span.marker == marker) {
  1611. return span
  1612. }
  1613. }
  1614. }
  1615. }
  1616. // Remove a span from an array, returning undefined if no spans are
  1617. // left (we don't store arrays for lines without spans).
  1618. function removeMarkedSpan(spans, span) {
  1619. var r
  1620. for (var i = 0; i < spans.length; ++i) {
  1621. if (spans[i] != span) {
  1622. ;(r || (r = [])).push(spans[i])
  1623. }
  1624. }
  1625. return r
  1626. }
  1627. // Add a span to a line.
  1628. function addMarkedSpan(line, span, op) {
  1629. var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet()))
  1630. if (inThisOp && inThisOp.has(line.markedSpans)) {
  1631. line.markedSpans.push(span)
  1632. } else {
  1633. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  1634. if (inThisOp) {
  1635. inThisOp.add(line.markedSpans)
  1636. }
  1637. }
  1638. span.marker.attachLine(line)
  1639. }
  1640. // Used for the algorithm that adjusts markers for a change in the
  1641. // document. These functions cut an array of spans at a given
  1642. // character position, returning an array of remaining chunks (or
  1643. // undefined if nothing remains).
  1644. function markedSpansBefore(old, startCh, isInsert) {
  1645. var nw
  1646. if (old) {
  1647. for (var i = 0; i < old.length; ++i) {
  1648. var span = old[i],
  1649. marker = span.marker
  1650. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  1651. if (startsBefore || (span.from == startCh && marker.type == 'bookmark' && (!isInsert || !span.marker.insertLeft))) {
  1652. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1653. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
  1654. }
  1655. }
  1656. }
  1657. return nw
  1658. }
  1659. function markedSpansAfter(old, endCh, isInsert) {
  1660. var nw
  1661. if (old) {
  1662. for (var i = 0; i < old.length; ++i) {
  1663. var span = old[i],
  1664. marker = span.marker
  1665. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
  1666. if (endsAfter || (span.from == endCh && marker.type == 'bookmark' && (!isInsert || span.marker.insertLeft))) {
  1667. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1668. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh))
  1669. }
  1670. }
  1671. }
  1672. return nw
  1673. }
  1674. // Given a change object, compute the new set of marker spans that
  1675. // cover the line in which the change took place. Removes spans
  1676. // entirely within the change, reconnects spans belonging to the
  1677. // same marker that appear on both sides of the change, and cuts off
  1678. // spans partially within the change. Returns an array of span
  1679. // arrays with one element for each line in (after) the change.
  1680. function stretchSpansOverChange(doc, change) {
  1681. if (change.full) {
  1682. return null
  1683. }
  1684. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
  1685. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
  1686. if (!oldFirst && !oldLast) {
  1687. return null
  1688. }
  1689. var startCh = change.from.ch,
  1690. endCh = change.to.ch,
  1691. isInsert = cmp(change.from, change.to) == 0
  1692. // Get the spans that 'stick out' on both sides
  1693. var first = markedSpansBefore(oldFirst, startCh, isInsert)
  1694. var last = markedSpansAfter(oldLast, endCh, isInsert)
  1695. // Next, merge those two ends
  1696. var sameLine = change.text.length == 1,
  1697. offset = lst(change.text).length + (sameLine ? startCh : 0)
  1698. if (first) {
  1699. // Fix up .to properties of first
  1700. for (var i = 0; i < first.length; ++i) {
  1701. var span = first[i]
  1702. if (span.to == null) {
  1703. var found = getMarkedSpanFor(last, span.marker)
  1704. if (!found) {
  1705. span.to = startCh
  1706. } else if (sameLine) {
  1707. span.to = found.to == null ? null : found.to + offset
  1708. }
  1709. }
  1710. }
  1711. }
  1712. if (last) {
  1713. // Fix up .from in last (or move them into first in case of sameLine)
  1714. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1715. var span$1 = last[i$1]
  1716. if (span$1.to != null) {
  1717. span$1.to += offset
  1718. }
  1719. if (span$1.from == null) {
  1720. var found$1 = getMarkedSpanFor(first, span$1.marker)
  1721. if (!found$1) {
  1722. span$1.from = offset
  1723. if (sameLine) {
  1724. ;(first || (first = [])).push(span$1)
  1725. }
  1726. }
  1727. } else {
  1728. span$1.from += offset
  1729. if (sameLine) {
  1730. ;(first || (first = [])).push(span$1)
  1731. }
  1732. }
  1733. }
  1734. }
  1735. // Make sure we didn't create any zero-length spans
  1736. if (first) {
  1737. first = clearEmptySpans(first)
  1738. }
  1739. if (last && last != first) {
  1740. last = clearEmptySpans(last)
  1741. }
  1742. var newMarkers = [first]
  1743. if (!sameLine) {
  1744. // Fill gap with whole-line-spans
  1745. var gap = change.text.length - 2,
  1746. gapMarkers
  1747. if (gap > 0 && first) {
  1748. for (var i$2 = 0; i$2 < first.length; ++i$2) {
  1749. if (first[i$2].to == null) {
  1750. ;(gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null))
  1751. }
  1752. }
  1753. }
  1754. for (var i$3 = 0; i$3 < gap; ++i$3) {
  1755. newMarkers.push(gapMarkers)
  1756. }
  1757. newMarkers.push(last)
  1758. }
  1759. return newMarkers
  1760. }
  1761. // Remove spans that are empty and don't have a clearWhenEmpty
  1762. // option of false.
  1763. function clearEmptySpans(spans) {
  1764. for (var i = 0; i < spans.length; ++i) {
  1765. var span = spans[i]
  1766. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {
  1767. spans.splice(i--, 1)
  1768. }
  1769. }
  1770. if (!spans.length) {
  1771. return null
  1772. }
  1773. return spans
  1774. }
  1775. // Used to 'clip' out readOnly ranges when making a change.
  1776. function removeReadOnlyRanges(doc, from, to) {
  1777. var markers = null
  1778. doc.iter(from.line, to.line + 1, function (line) {
  1779. if (line.markedSpans) {
  1780. for (var i = 0; i < line.markedSpans.length; ++i) {
  1781. var mark = line.markedSpans[i].marker
  1782. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {
  1783. ;(markers || (markers = [])).push(mark)
  1784. }
  1785. }
  1786. }
  1787. })
  1788. if (!markers) {
  1789. return null
  1790. }
  1791. var parts = [{ from: from, to: to }]
  1792. for (var i = 0; i < markers.length; ++i) {
  1793. var mk = markers[i],
  1794. m = mk.find(0)
  1795. for (var j = 0; j < parts.length; ++j) {
  1796. var p = parts[j]
  1797. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) {
  1798. continue
  1799. }
  1800. var newParts = [j, 1],
  1801. dfrom = cmp(p.from, m.from),
  1802. dto = cmp(p.to, m.to)
  1803. if (dfrom < 0 || (!mk.inclusiveLeft && !dfrom)) {
  1804. newParts.push({ from: p.from, to: m.from })
  1805. }
  1806. if (dto > 0 || (!mk.inclusiveRight && !dto)) {
  1807. newParts.push({ from: m.to, to: p.to })
  1808. }
  1809. parts.splice.apply(parts, newParts)
  1810. j += newParts.length - 3
  1811. }
  1812. }
  1813. return parts
  1814. }
  1815. // Connect or disconnect spans from a line.
  1816. function detachMarkedSpans(line) {
  1817. var spans = line.markedSpans
  1818. if (!spans) {
  1819. return
  1820. }
  1821. for (var i = 0; i < spans.length; ++i) {
  1822. spans[i].marker.detachLine(line)
  1823. }
  1824. line.markedSpans = null
  1825. }
  1826. function attachMarkedSpans(line, spans) {
  1827. if (!spans) {
  1828. return
  1829. }
  1830. for (var i = 0; i < spans.length; ++i) {
  1831. spans[i].marker.attachLine(line)
  1832. }
  1833. line.markedSpans = spans
  1834. }
  1835. // Helpers used when computing which overlapping collapsed span
  1836. // counts as the larger one.
  1837. function extraLeft(marker) {
  1838. return marker.inclusiveLeft ? -1 : 0
  1839. }
  1840. function extraRight(marker) {
  1841. return marker.inclusiveRight ? 1 : 0
  1842. }
  1843. // Returns a number indicating which of two overlapping collapsed
  1844. // spans is larger (and thus includes the other). Falls back to
  1845. // comparing ids when the spans cover exactly the same range.
  1846. function compareCollapsedMarkers(a, b) {
  1847. var lenDiff = a.lines.length - b.lines.length
  1848. if (lenDiff != 0) {
  1849. return lenDiff
  1850. }
  1851. var aPos = a.find(),
  1852. bPos = b.find()
  1853. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
  1854. if (fromCmp) {
  1855. return -fromCmp
  1856. }
  1857. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
  1858. if (toCmp) {
  1859. return toCmp
  1860. }
  1861. return b.id - a.id
  1862. }
  1863. // Find out whether a line ends or starts in a collapsed span. If
  1864. // so, return the marker for that span.
  1865. function collapsedSpanAtSide(line, start) {
  1866. var sps = sawCollapsedSpans && line.markedSpans,
  1867. found
  1868. if (sps) {
  1869. for (var sp = void 0, i = 0; i < sps.length; ++i) {
  1870. sp = sps[i]
  1871. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
  1872. found = sp.marker
  1873. }
  1874. }
  1875. }
  1876. return found
  1877. }
  1878. function collapsedSpanAtStart(line) {
  1879. return collapsedSpanAtSide(line, true)
  1880. }
  1881. function collapsedSpanAtEnd(line) {
  1882. return collapsedSpanAtSide(line, false)
  1883. }
  1884. function collapsedSpanAround(line, ch) {
  1885. var sps = sawCollapsedSpans && line.markedSpans,
  1886. found
  1887. if (sps) {
  1888. for (var i = 0; i < sps.length; ++i) {
  1889. var sp = sps[i]
  1890. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
  1891. found = sp.marker
  1892. }
  1893. }
  1894. }
  1895. return found
  1896. }
  1897. // Test whether there exists a collapsed span that partially
  1898. // overlaps (covers the start or end, but not both) of a new span.
  1899. // Such overlap is not allowed.
  1900. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1901. var line = getLine(doc, lineNo)
  1902. var sps = sawCollapsedSpans && line.markedSpans
  1903. if (sps) {
  1904. for (var i = 0; i < sps.length; ++i) {
  1905. var sp = sps[i]
  1906. if (!sp.marker.collapsed) {
  1907. continue
  1908. }
  1909. var found = sp.marker.find(0)
  1910. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  1911. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  1912. if ((fromCmp >= 0 && toCmp <= 0) || (fromCmp <= 0 && toCmp >= 0)) {
  1913. continue
  1914. }
  1915. if (
  1916. (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0)) ||
  1917. (fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1918. ) {
  1919. return true
  1920. }
  1921. }
  1922. }
  1923. }
  1924. // A visual line is a line as drawn on the screen. Folding, for
  1925. // example, can cause multiple logical lines to appear on the same
  1926. // visual line. This finds the start of the visual line that the
  1927. // given line is part of (usually that is the line itself).
  1928. function visualLine(line) {
  1929. var merged
  1930. while ((merged = collapsedSpanAtStart(line))) {
  1931. line = merged.find(-1, true).line
  1932. }
  1933. return line
  1934. }
  1935. function visualLineEnd(line) {
  1936. var merged
  1937. while ((merged = collapsedSpanAtEnd(line))) {
  1938. line = merged.find(1, true).line
  1939. }
  1940. return line
  1941. }
  1942. // Returns an array of logical lines that continue the visual line
  1943. // started by the argument, or undefined if there are no such lines.
  1944. function visualLineContinued(line) {
  1945. var merged, lines
  1946. while ((merged = collapsedSpanAtEnd(line))) {
  1947. line = merged.find(1, true).line
  1948. ;(lines || (lines = [])).push(line)
  1949. }
  1950. return lines
  1951. }
  1952. // Get the line number of the start of the visual line that the
  1953. // given line number is part of.
  1954. function visualLineNo(doc, lineN) {
  1955. var line = getLine(doc, lineN),
  1956. vis = visualLine(line)
  1957. if (line == vis) {
  1958. return lineN
  1959. }
  1960. return lineNo(vis)
  1961. }
  1962. // Get the line number of the start of the next visual line after
  1963. // the given line.
  1964. function visualLineEndNo(doc, lineN) {
  1965. if (lineN > doc.lastLine()) {
  1966. return lineN
  1967. }
  1968. var line = getLine(doc, lineN),
  1969. merged
  1970. if (!lineIsHidden(doc, line)) {
  1971. return lineN
  1972. }
  1973. while ((merged = collapsedSpanAtEnd(line))) {
  1974. line = merged.find(1, true).line
  1975. }
  1976. return lineNo(line) + 1
  1977. }
  1978. // Compute whether a line is hidden. Lines count as hidden when they
  1979. // are part of a visual line that starts with another line, or when
  1980. // they are entirely covered by collapsed, non-widget span.
  1981. function lineIsHidden(doc, line) {
  1982. var sps = sawCollapsedSpans && line.markedSpans
  1983. if (sps) {
  1984. for (var sp = void 0, i = 0; i < sps.length; ++i) {
  1985. sp = sps[i]
  1986. if (!sp.marker.collapsed) {
  1987. continue
  1988. }
  1989. if (sp.from == null) {
  1990. return true
  1991. }
  1992. if (sp.marker.widgetNode) {
  1993. continue
  1994. }
  1995. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) {
  1996. return true
  1997. }
  1998. }
  1999. }
  2000. }
  2001. function lineIsHiddenInner(doc, line, span) {
  2002. if (span.to == null) {
  2003. var end = span.marker.find(1, true)
  2004. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  2005. }
  2006. if (span.marker.inclusiveRight && span.to == line.text.length) {
  2007. return true
  2008. }
  2009. for (var sp = void 0, i = 0; i < line.markedSpans.length; ++i) {
  2010. sp = line.markedSpans[i]
  2011. if (
  2012. sp.marker.collapsed &&
  2013. !sp.marker.widgetNode &&
  2014. sp.from == span.to &&
  2015. (sp.to == null || sp.to != span.from) &&
  2016. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  2017. lineIsHiddenInner(doc, line, sp)
  2018. ) {
  2019. return true
  2020. }
  2021. }
  2022. }
  2023. // Find the height above the given line.
  2024. function heightAtLine(lineObj) {
  2025. lineObj = visualLine(lineObj)
  2026. var h = 0,
  2027. chunk = lineObj.parent
  2028. for (var i = 0; i < chunk.lines.length; ++i) {
  2029. var line = chunk.lines[i]
  2030. if (line == lineObj) {
  2031. break
  2032. } else {
  2033. h += line.height
  2034. }
  2035. }
  2036. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  2037. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  2038. var cur = p.children[i$1]
  2039. if (cur == chunk) {
  2040. break
  2041. } else {
  2042. h += cur.height
  2043. }
  2044. }
  2045. }
  2046. return h
  2047. }
  2048. // Compute the character length of a line, taking into account
  2049. // collapsed ranges (see markText) that might hide parts, and join
  2050. // other lines onto it.
  2051. function lineLength(line) {
  2052. if (line.height == 0) {
  2053. return 0
  2054. }
  2055. var len = line.text.length,
  2056. merged,
  2057. cur = line
  2058. while ((merged = collapsedSpanAtStart(cur))) {
  2059. var found = merged.find(0, true)
  2060. cur = found.from.line
  2061. len += found.from.ch - found.to.ch
  2062. }
  2063. cur = line
  2064. while ((merged = collapsedSpanAtEnd(cur))) {
  2065. var found$1 = merged.find(0, true)
  2066. len -= cur.text.length - found$1.from.ch
  2067. cur = found$1.to.line
  2068. len += cur.text.length - found$1.to.ch
  2069. }
  2070. return len
  2071. }
  2072. // Find the longest line in the document.
  2073. function findMaxLine(cm) {
  2074. var d = cm.display,
  2075. doc = cm.doc
  2076. d.maxLine = getLine(doc, doc.first)
  2077. d.maxLineLength = lineLength(d.maxLine)
  2078. d.maxLineChanged = true
  2079. doc.iter(function (line) {
  2080. var len = lineLength(line)
  2081. if (len > d.maxLineLength) {
  2082. d.maxLineLength = len
  2083. d.maxLine = line
  2084. }
  2085. })
  2086. }
  2087. // LINE DATA STRUCTURE
  2088. // Line objects. These hold state related to a line, including
  2089. // highlighting info (the styles array).
  2090. var Line = function (text, markedSpans, estimateHeight) {
  2091. this.text = text
  2092. attachMarkedSpans(this, markedSpans)
  2093. this.height = estimateHeight ? estimateHeight(this) : 1
  2094. }
  2095. Line.prototype.lineNo = function () {
  2096. return lineNo(this)
  2097. }
  2098. eventMixin(Line)
  2099. // Change the content (text, markers) of a line. Automatically
  2100. // invalidates cached information and tries to re-estimate the
  2101. // line's height.
  2102. function updateLine(line, text, markedSpans, estimateHeight) {
  2103. line.text = text
  2104. if (line.stateAfter) {
  2105. line.stateAfter = null
  2106. }
  2107. if (line.styles) {
  2108. line.styles = null
  2109. }
  2110. if (line.order != null) {
  2111. line.order = null
  2112. }
  2113. detachMarkedSpans(line)
  2114. attachMarkedSpans(line, markedSpans)
  2115. var estHeight = estimateHeight ? estimateHeight(line) : 1
  2116. if (estHeight != line.height) {
  2117. updateLineHeight(line, estHeight)
  2118. }
  2119. }
  2120. // Detach a line from the document tree and its markers.
  2121. function cleanUpLine(line) {
  2122. line.parent = null
  2123. detachMarkedSpans(line)
  2124. }
  2125. // Convert a style as returned by a mode (either null, or a string
  2126. // containing one or more styles) to a CSS style. This is cached,
  2127. // and also looks for line-wide styles.
  2128. var styleToClassCache = {},
  2129. styleToClassCacheWithMode = {}
  2130. function interpretTokenStyle(style, options) {
  2131. if (!style || /^\s*$/.test(style)) {
  2132. return null
  2133. }
  2134. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  2135. return cache[style] || (cache[style] = style.replace(/\S+/g, 'cm-$&'))
  2136. }
  2137. // Render the DOM representation of the text of a line. Also builds
  2138. // up a 'line map', which points at the DOM nodes that represent
  2139. // specific stretches of text, and is used by the measuring code.
  2140. // The returned object contains the DOM node, this map, and
  2141. // information about line-wide styles that were set by the mode.
  2142. function buildLineContent(cm, lineView) {
  2143. // The padding-right forces the element to have a 'border', which
  2144. // is needed on Webkit to be able to get line-level bounding
  2145. // rectangles for it (in measureChar).
  2146. var content = eltP('span', null, null, webkit ? 'padding-right: .1px' : null)
  2147. var builder = { pre: eltP('pre', [content], 'CodeMirror-line'), content: content, col: 0, pos: 0, cm: cm, trailingSpace: false, splitSpaces: cm.getOption('lineWrapping') }
  2148. lineView.measure = {}
  2149. // Iterate over the logical lines that make up this visual line.
  2150. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  2151. var line = i ? lineView.rest[i - 1] : lineView.line,
  2152. order = void 0
  2153. builder.pos = 0
  2154. builder.addToken = buildToken
  2155. // Optionally wire in some hacks into the token-rendering
  2156. // algorithm, to deal with browser quirks.
  2157. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) {
  2158. builder.addToken = buildTokenBadBidi(builder.addToken, order)
  2159. }
  2160. builder.map = []
  2161. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  2162. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  2163. if (line.styleClasses) {
  2164. if (line.styleClasses.bgClass) {
  2165. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || '')
  2166. }
  2167. if (line.styleClasses.textClass) {
  2168. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || '')
  2169. }
  2170. }
  2171. // Ensure at least a single node is present, for measuring.
  2172. if (builder.map.length == 0) {
  2173. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)))
  2174. }
  2175. // Store the map and a cache object for the current logical line
  2176. if (i == 0) {
  2177. lineView.measure.map = builder.map
  2178. lineView.measure.cache = {}
  2179. } else {
  2180. ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  2181. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  2182. }
  2183. }
  2184. // See issue #2901
  2185. if (webkit) {
  2186. var last = builder.content.lastChild
  2187. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector('.cm-tab'))) {
  2188. builder.content.className = 'cm-tab-wrap-hack'
  2189. }
  2190. }
  2191. signal(cm, 'renderLine', cm, lineView.line, builder.pre)
  2192. if (builder.pre.className) {
  2193. builder.textClass = joinClasses(builder.pre.className, builder.textClass || '')
  2194. }
  2195. return builder
  2196. }
  2197. function defaultSpecialCharPlaceholder(ch) {
  2198. var token = elt('span', '\u2022', 'cm-invalidchar')
  2199. token.title = '\\u' + ch.charCodeAt(0).toString(16)
  2200. token.setAttribute('aria-label', token.title)
  2201. return token
  2202. }
  2203. // Build up the DOM representation for a single token, and add it to
  2204. // the line map. Takes care to render special characters separately.
  2205. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  2206. if (!text) {
  2207. return
  2208. }
  2209. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  2210. var special = builder.cm.state.specialChars,
  2211. mustWrap = false
  2212. var content
  2213. if (!special.test(text)) {
  2214. builder.col += text.length
  2215. content = document.createTextNode(displayText)
  2216. builder.map.push(builder.pos, builder.pos + text.length, content)
  2217. if (ie && ie_version < 9) {
  2218. mustWrap = true
  2219. }
  2220. builder.pos += text.length
  2221. } else {
  2222. content = document.createDocumentFragment()
  2223. var pos = 0
  2224. while (true) {
  2225. special.lastIndex = pos
  2226. var m = special.exec(text)
  2227. var skipped = m ? m.index - pos : text.length - pos
  2228. if (skipped) {
  2229. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  2230. if (ie && ie_version < 9) {
  2231. content.appendChild(elt('span', [txt]))
  2232. } else {
  2233. content.appendChild(txt)
  2234. }
  2235. builder.map.push(builder.pos, builder.pos + skipped, txt)
  2236. builder.col += skipped
  2237. builder.pos += skipped
  2238. }
  2239. if (!m) {
  2240. break
  2241. }
  2242. pos += skipped + 1
  2243. var txt$1 = void 0
  2244. if (m[0] == '\t') {
  2245. var tabSize = builder.cm.options.tabSize,
  2246. tabWidth = tabSize - (builder.col % tabSize)
  2247. txt$1 = content.appendChild(elt('span', spaceStr(tabWidth), 'cm-tab'))
  2248. txt$1.setAttribute('role', 'presentation')
  2249. txt$1.setAttribute('cm-text', '\t')
  2250. builder.col += tabWidth
  2251. } else if (m[0] == '\r' || m[0] == '\n') {
  2252. txt$1 = content.appendChild(elt('span', m[0] == '\r' ? '\u240d' : '\u2424', 'cm-invalidchar'))
  2253. txt$1.setAttribute('cm-text', m[0])
  2254. builder.col += 1
  2255. } else {
  2256. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  2257. txt$1.setAttribute('cm-text', m[0])
  2258. if (ie && ie_version < 9) {
  2259. content.appendChild(elt('span', [txt$1]))
  2260. } else {
  2261. content.appendChild(txt$1)
  2262. }
  2263. builder.col += 1
  2264. }
  2265. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  2266. builder.pos++
  2267. }
  2268. }
  2269. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  2270. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  2271. var fullStyle = style || ''
  2272. if (startStyle) {
  2273. fullStyle += startStyle
  2274. }
  2275. if (endStyle) {
  2276. fullStyle += endStyle
  2277. }
  2278. var token = elt('span', [content], fullStyle, css)
  2279. if (attributes) {
  2280. for (var attr in attributes) {
  2281. if (attributes.hasOwnProperty(attr) && attr != 'style' && attr != 'class') {
  2282. token.setAttribute(attr, attributes[attr])
  2283. }
  2284. }
  2285. }
  2286. return builder.content.appendChild(token)
  2287. }
  2288. builder.content.appendChild(content)
  2289. }
  2290. // Change some spaces to NBSP to prevent the browser from collapsing
  2291. // trailing spaces at the end of a line when rendering text (issue #1362).
  2292. function splitSpaces(text, trailingBefore) {
  2293. if (text.length > 1 && !/ /.test(text)) {
  2294. return text
  2295. }
  2296. var spaceBefore = trailingBefore,
  2297. result = ''
  2298. for (var i = 0; i < text.length; i++) {
  2299. var ch = text.charAt(i)
  2300. if (ch == ' ' && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) {
  2301. ch = '\u00a0'
  2302. }
  2303. result += ch
  2304. spaceBefore = ch == ' '
  2305. }
  2306. return result
  2307. }
  2308. // Work around nonsense dimensions being reported for stretches of
  2309. // right-to-left text.
  2310. function buildTokenBadBidi(inner, order) {
  2311. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  2312. style = style ? style + ' cm-force-border' : 'cm-force-border'
  2313. var start = builder.pos,
  2314. end = start + text.length
  2315. for (;;) {
  2316. // Find the part that overlaps with the start of this text
  2317. var part = void 0
  2318. for (var i = 0; i < order.length; i++) {
  2319. part = order[i]
  2320. if (part.to > start && part.from <= start) {
  2321. break
  2322. }
  2323. }
  2324. if (part.to >= end) {
  2325. return inner(builder, text, style, startStyle, endStyle, css, attributes)
  2326. }
  2327. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes)
  2328. startStyle = null
  2329. text = text.slice(part.to - start)
  2330. start = part.to
  2331. }
  2332. }
  2333. }
  2334. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  2335. var widget = !ignoreWidget && marker.widgetNode
  2336. if (widget) {
  2337. builder.map.push(builder.pos, builder.pos + size, widget)
  2338. }
  2339. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  2340. if (!widget) {
  2341. widget = builder.content.appendChild(document.createElement('span'))
  2342. }
  2343. widget.setAttribute('cm-marker', marker.id)
  2344. }
  2345. if (widget) {
  2346. builder.cm.display.input.setUneditable(widget)
  2347. builder.content.appendChild(widget)
  2348. }
  2349. builder.pos += size
  2350. builder.trailingSpace = false
  2351. }
  2352. // Outputs a number of spans to make up a line, taking highlighting
  2353. // and marked text into account.
  2354. function insertLineContent(line, builder, styles) {
  2355. var spans = line.markedSpans,
  2356. allText = line.text,
  2357. at = 0
  2358. if (!spans) {
  2359. for (var i$1 = 1; i$1 < styles.length; i$1 += 2) {
  2360. builder.addToken(builder, allText.slice(at, (at = styles[i$1])), interpretTokenStyle(styles[i$1 + 1], builder.cm.options))
  2361. }
  2362. return
  2363. }
  2364. var len = allText.length,
  2365. pos = 0,
  2366. i = 1,
  2367. text = '',
  2368. style,
  2369. css
  2370. var nextChange = 0,
  2371. spanStyle,
  2372. spanEndStyle,
  2373. spanStartStyle,
  2374. collapsed,
  2375. attributes
  2376. for (;;) {
  2377. if (nextChange == pos) {
  2378. // Update current marker set
  2379. spanStyle = spanEndStyle = spanStartStyle = css = ''
  2380. attributes = null
  2381. collapsed = null
  2382. nextChange = Infinity
  2383. var foundBookmarks = [],
  2384. endStyles = void 0
  2385. for (var j = 0; j < spans.length; ++j) {
  2386. var sp = spans[j],
  2387. m = sp.marker
  2388. if (m.type == 'bookmark' && sp.from == pos && m.widgetNode) {
  2389. foundBookmarks.push(m)
  2390. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || (m.collapsed && sp.to == pos && sp.from == pos))) {
  2391. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  2392. nextChange = sp.to
  2393. spanEndStyle = ''
  2394. }
  2395. if (m.className) {
  2396. spanStyle += ' ' + m.className
  2397. }
  2398. if (m.css) {
  2399. css = (css ? css + ';' : '') + m.css
  2400. }
  2401. if (m.startStyle && sp.from == pos) {
  2402. spanStartStyle += ' ' + m.startStyle
  2403. }
  2404. if (m.endStyle && sp.to == nextChange) {
  2405. ;(endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  2406. }
  2407. // support for the old title property
  2408. // https://github.com/codemirror/CodeMirror/pull/5673
  2409. if (m.title) {
  2410. ;(attributes || (attributes = {})).title = m.title
  2411. }
  2412. if (m.attributes) {
  2413. for (var attr in m.attributes) {
  2414. ;(attributes || (attributes = {}))[attr] = m.attributes[attr]
  2415. }
  2416. }
  2417. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) {
  2418. collapsed = sp
  2419. }
  2420. } else if (sp.from > pos && nextChange > sp.from) {
  2421. nextChange = sp.from
  2422. }
  2423. }
  2424. if (endStyles) {
  2425. for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) {
  2426. if (endStyles[j$1 + 1] == nextChange) {
  2427. spanEndStyle += ' ' + endStyles[j$1]
  2428. }
  2429. }
  2430. }
  2431. if (!collapsed || collapsed.from == pos) {
  2432. for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) {
  2433. buildCollapsedSpan(builder, 0, foundBookmarks[j$2])
  2434. }
  2435. }
  2436. if (collapsed && (collapsed.from || 0) == pos) {
  2437. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null)
  2438. if (collapsed.to == null) {
  2439. return
  2440. }
  2441. if (collapsed.to == pos) {
  2442. collapsed = false
  2443. }
  2444. }
  2445. }
  2446. if (pos >= len) {
  2447. break
  2448. }
  2449. var upto = Math.min(len, nextChange)
  2450. while (true) {
  2451. if (text) {
  2452. var end = pos + text.length
  2453. if (!collapsed) {
  2454. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  2455. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : '', css, attributes)
  2456. }
  2457. if (end >= upto) {
  2458. text = text.slice(upto - pos)
  2459. pos = upto
  2460. break
  2461. }
  2462. pos = end
  2463. spanStartStyle = ''
  2464. }
  2465. text = allText.slice(at, (at = styles[i++]))
  2466. style = interpretTokenStyle(styles[i++], builder.cm.options)
  2467. }
  2468. }
  2469. }
  2470. // These objects are used to represent the visible (currently drawn)
  2471. // part of the document. A LineView may correspond to multiple
  2472. // logical lines, if those are connected by collapsed ranges.
  2473. function LineView(doc, line, lineN) {
  2474. // The starting line
  2475. this.line = line
  2476. // Continuing lines, if any
  2477. this.rest = visualLineContinued(line)
  2478. // Number of logical lines in this visual line
  2479. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  2480. this.node = this.text = null
  2481. this.hidden = lineIsHidden(doc, line)
  2482. }
  2483. // Create a range of LineView objects for the given lines.
  2484. function buildViewArray(cm, from, to) {
  2485. var array = [],
  2486. nextPos
  2487. for (var pos = from; pos < to; pos = nextPos) {
  2488. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  2489. nextPos = pos + view.size
  2490. array.push(view)
  2491. }
  2492. return array
  2493. }
  2494. var operationGroup = null
  2495. function pushOperation(op) {
  2496. if (operationGroup) {
  2497. operationGroup.ops.push(op)
  2498. } else {
  2499. op.ownsGroup = operationGroup = {
  2500. ops: [op],
  2501. delayedCallbacks: [],
  2502. }
  2503. }
  2504. }
  2505. function fireCallbacksForOps(group) {
  2506. // Calls delayed callbacks and cursorActivity handlers until no
  2507. // new ones appear
  2508. var callbacks = group.delayedCallbacks,
  2509. i = 0
  2510. do {
  2511. for (; i < callbacks.length; i++) {
  2512. callbacks[i].call(null)
  2513. }
  2514. for (var j = 0; j < group.ops.length; j++) {
  2515. var op = group.ops[j]
  2516. if (op.cursorActivityHandlers) {
  2517. while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {
  2518. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm)
  2519. }
  2520. }
  2521. }
  2522. } while (i < callbacks.length)
  2523. }
  2524. function finishOperation(op, endCb) {
  2525. var group = op.ownsGroup
  2526. if (!group) {
  2527. return
  2528. }
  2529. try {
  2530. fireCallbacksForOps(group)
  2531. } finally {
  2532. operationGroup = null
  2533. endCb(group)
  2534. }
  2535. }
  2536. var orphanDelayedCallbacks = null
  2537. // Often, we want to signal events at a point where we are in the
  2538. // middle of some work, but don't want the handler to start calling
  2539. // other methods on the editor, which might be in an inconsistent
  2540. // state or simply not expect any other events to happen.
  2541. // signalLater looks whether there are any handlers, and schedules
  2542. // them to be executed when the last operation ends, or, if no
  2543. // operation is active, when a timeout fires.
  2544. function signalLater(emitter, type /*, values...*/) {
  2545. var arr = getHandlers(emitter, type)
  2546. if (!arr.length) {
  2547. return
  2548. }
  2549. var args = Array.prototype.slice.call(arguments, 2),
  2550. list
  2551. if (operationGroup) {
  2552. list = operationGroup.delayedCallbacks
  2553. } else if (orphanDelayedCallbacks) {
  2554. list = orphanDelayedCallbacks
  2555. } else {
  2556. list = orphanDelayedCallbacks = []
  2557. setTimeout(fireOrphanDelayed, 0)
  2558. }
  2559. var loop = function (i) {
  2560. list.push(function () {
  2561. return arr[i].apply(null, args)
  2562. })
  2563. }
  2564. for (var i = 0; i < arr.length; ++i) loop(i)
  2565. }
  2566. function fireOrphanDelayed() {
  2567. var delayed = orphanDelayedCallbacks
  2568. orphanDelayedCallbacks = null
  2569. for (var i = 0; i < delayed.length; ++i) {
  2570. delayed[i]()
  2571. }
  2572. }
  2573. // When an aspect of a line changes, a string is added to
  2574. // lineView.changes. This updates the relevant part of the line's
  2575. // DOM structure.
  2576. function updateLineForChanges(cm, lineView, lineN, dims) {
  2577. for (var j = 0; j < lineView.changes.length; j++) {
  2578. var type = lineView.changes[j]
  2579. if (type == 'text') {
  2580. updateLineText(cm, lineView)
  2581. } else if (type == 'gutter') {
  2582. updateLineGutter(cm, lineView, lineN, dims)
  2583. } else if (type == 'class') {
  2584. updateLineClasses(cm, lineView)
  2585. } else if (type == 'widget') {
  2586. updateLineWidgets(cm, lineView, dims)
  2587. }
  2588. }
  2589. lineView.changes = null
  2590. }
  2591. // Lines with gutter elements, widgets or a background class need to
  2592. // be wrapped, and have the extra elements added to the wrapper div
  2593. function ensureLineWrapped(lineView) {
  2594. if (lineView.node == lineView.text) {
  2595. lineView.node = elt('div', null, null, 'position: relative')
  2596. if (lineView.text.parentNode) {
  2597. lineView.text.parentNode.replaceChild(lineView.node, lineView.text)
  2598. }
  2599. lineView.node.appendChild(lineView.text)
  2600. if (ie && ie_version < 8) {
  2601. lineView.node.style.zIndex = 2
  2602. }
  2603. }
  2604. return lineView.node
  2605. }
  2606. function updateLineBackground(cm, lineView) {
  2607. var cls = lineView.bgClass ? lineView.bgClass + ' ' + (lineView.line.bgClass || '') : lineView.line.bgClass
  2608. if (cls) {
  2609. cls += ' CodeMirror-linebackground'
  2610. }
  2611. if (lineView.background) {
  2612. if (cls) {
  2613. lineView.background.className = cls
  2614. } else {
  2615. lineView.background.parentNode.removeChild(lineView.background)
  2616. lineView.background = null
  2617. }
  2618. } else if (cls) {
  2619. var wrap = ensureLineWrapped(lineView)
  2620. lineView.background = wrap.insertBefore(elt('div', null, cls), wrap.firstChild)
  2621. cm.display.input.setUneditable(lineView.background)
  2622. }
  2623. }
  2624. // Wrapper around buildLineContent which will reuse the structure
  2625. // in display.externalMeasured when possible.
  2626. function getLineContent(cm, lineView) {
  2627. var ext = cm.display.externalMeasured
  2628. if (ext && ext.line == lineView.line) {
  2629. cm.display.externalMeasured = null
  2630. lineView.measure = ext.measure
  2631. return ext.built
  2632. }
  2633. return buildLineContent(cm, lineView)
  2634. }
  2635. // Redraw the line's text. Interacts with the background and text
  2636. // classes because the mode may output tokens that influence these
  2637. // classes.
  2638. function updateLineText(cm, lineView) {
  2639. var cls = lineView.text.className
  2640. var built = getLineContent(cm, lineView)
  2641. if (lineView.text == lineView.node) {
  2642. lineView.node = built.pre
  2643. }
  2644. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  2645. lineView.text = built.pre
  2646. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2647. lineView.bgClass = built.bgClass
  2648. lineView.textClass = built.textClass
  2649. updateLineClasses(cm, lineView)
  2650. } else if (cls) {
  2651. lineView.text.className = cls
  2652. }
  2653. }
  2654. function updateLineClasses(cm, lineView) {
  2655. updateLineBackground(cm, lineView)
  2656. if (lineView.line.wrapClass) {
  2657. ensureLineWrapped(lineView).className = lineView.line.wrapClass
  2658. } else if (lineView.node != lineView.text) {
  2659. lineView.node.className = ''
  2660. }
  2661. var textClass = lineView.textClass ? lineView.textClass + ' ' + (lineView.line.textClass || '') : lineView.line.textClass
  2662. lineView.text.className = textClass || ''
  2663. }
  2664. function updateLineGutter(cm, lineView, lineN, dims) {
  2665. if (lineView.gutter) {
  2666. lineView.node.removeChild(lineView.gutter)
  2667. lineView.gutter = null
  2668. }
  2669. if (lineView.gutterBackground) {
  2670. lineView.node.removeChild(lineView.gutterBackground)
  2671. lineView.gutterBackground = null
  2672. }
  2673. if (lineView.line.gutterClass) {
  2674. var wrap = ensureLineWrapped(lineView)
  2675. lineView.gutterBackground = elt(
  2676. 'div',
  2677. null,
  2678. 'CodeMirror-gutter-background ' + lineView.line.gutterClass,
  2679. 'left: ' + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + 'px; width: ' + dims.gutterTotalWidth + 'px'
  2680. )
  2681. cm.display.input.setUneditable(lineView.gutterBackground)
  2682. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  2683. }
  2684. var markers = lineView.line.gutterMarkers
  2685. if (cm.options.lineNumbers || markers) {
  2686. var wrap$1 = ensureLineWrapped(lineView)
  2687. var gutterWrap = (lineView.gutter = elt('div', null, 'CodeMirror-gutter-wrapper', 'left: ' + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + 'px'))
  2688. gutterWrap.setAttribute('aria-hidden', 'true')
  2689. cm.display.input.setUneditable(gutterWrap)
  2690. wrap$1.insertBefore(gutterWrap, lineView.text)
  2691. if (lineView.line.gutterClass) {
  2692. gutterWrap.className += ' ' + lineView.line.gutterClass
  2693. }
  2694. if (cm.options.lineNumbers && (!markers || !markers['CodeMirror-linenumbers'])) {
  2695. lineView.lineNumber = gutterWrap.appendChild(
  2696. elt(
  2697. 'div',
  2698. lineNumberFor(cm.options, lineN),
  2699. 'CodeMirror-linenumber CodeMirror-gutter-elt',
  2700. 'left: ' + dims.gutterLeft['CodeMirror-linenumbers'] + 'px; width: ' + cm.display.lineNumInnerWidth + 'px'
  2701. )
  2702. )
  2703. }
  2704. if (markers) {
  2705. for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2706. var id = cm.display.gutterSpecs[k].className,
  2707. found = markers.hasOwnProperty(id) && markers[id]
  2708. if (found) {
  2709. gutterWrap.appendChild(elt('div', [found], 'CodeMirror-gutter-elt', 'left: ' + dims.gutterLeft[id] + 'px; width: ' + dims.gutterWidth[id] + 'px'))
  2710. }
  2711. }
  2712. }
  2713. }
  2714. }
  2715. function updateLineWidgets(cm, lineView, dims) {
  2716. if (lineView.alignable) {
  2717. lineView.alignable = null
  2718. }
  2719. var isWidget = classTest('CodeMirror-linewidget')
  2720. for (var node = lineView.node.firstChild, next = void 0; node; node = next) {
  2721. next = node.nextSibling
  2722. if (isWidget.test(node.className)) {
  2723. lineView.node.removeChild(node)
  2724. }
  2725. }
  2726. insertLineWidgets(cm, lineView, dims)
  2727. }
  2728. // Build a line's DOM representation from scratch
  2729. function buildLineElement(cm, lineView, lineN, dims) {
  2730. var built = getLineContent(cm, lineView)
  2731. lineView.text = lineView.node = built.pre
  2732. if (built.bgClass) {
  2733. lineView.bgClass = built.bgClass
  2734. }
  2735. if (built.textClass) {
  2736. lineView.textClass = built.textClass
  2737. }
  2738. updateLineClasses(cm, lineView)
  2739. updateLineGutter(cm, lineView, lineN, dims)
  2740. insertLineWidgets(cm, lineView, dims)
  2741. return lineView.node
  2742. }
  2743. // A lineView may contain multiple logical lines (when merged by
  2744. // collapsed spans). The widgets for all of them need to be drawn.
  2745. function insertLineWidgets(cm, lineView, dims) {
  2746. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2747. if (lineView.rest) {
  2748. for (var i = 0; i < lineView.rest.length; i++) {
  2749. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false)
  2750. }
  2751. }
  2752. }
  2753. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2754. if (!line.widgets) {
  2755. return
  2756. }
  2757. var wrap = ensureLineWrapped(lineView)
  2758. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2759. var widget = ws[i],
  2760. node = elt('div', [widget.node], 'CodeMirror-linewidget' + (widget.className ? ' ' + widget.className : ''))
  2761. if (!widget.handleMouseEvents) {
  2762. node.setAttribute('cm-ignore-events', 'true')
  2763. }
  2764. positionLineWidget(widget, node, lineView, dims)
  2765. cm.display.input.setUneditable(node)
  2766. if (allowAbove && widget.above) {
  2767. wrap.insertBefore(node, lineView.gutter || lineView.text)
  2768. } else {
  2769. wrap.appendChild(node)
  2770. }
  2771. signalLater(widget, 'redraw')
  2772. }
  2773. }
  2774. function positionLineWidget(widget, node, lineView, dims) {
  2775. if (widget.noHScroll) {
  2776. ;(lineView.alignable || (lineView.alignable = [])).push(node)
  2777. var width = dims.wrapperWidth
  2778. node.style.left = dims.fixedPos + 'px'
  2779. if (!widget.coverGutter) {
  2780. width -= dims.gutterTotalWidth
  2781. node.style.paddingLeft = dims.gutterTotalWidth + 'px'
  2782. }
  2783. node.style.width = width + 'px'
  2784. }
  2785. if (widget.coverGutter) {
  2786. node.style.zIndex = 5
  2787. node.style.position = 'relative'
  2788. if (!widget.noHScroll) {
  2789. node.style.marginLeft = -dims.gutterTotalWidth + 'px'
  2790. }
  2791. }
  2792. }
  2793. function widgetHeight(widget) {
  2794. if (widget.height != null) {
  2795. return widget.height
  2796. }
  2797. var cm = widget.doc.cm
  2798. if (!cm) {
  2799. return 0
  2800. }
  2801. if (!contains(document.body, widget.node)) {
  2802. var parentStyle = 'position: relative;'
  2803. if (widget.coverGutter) {
  2804. parentStyle += 'margin-left: -' + cm.display.gutters.offsetWidth + 'px;'
  2805. }
  2806. if (widget.noHScroll) {
  2807. parentStyle += 'width: ' + cm.display.wrapper.clientWidth + 'px;'
  2808. }
  2809. removeChildrenAndAdd(cm.display.measure, elt('div', [widget.node], null, parentStyle))
  2810. }
  2811. return (widget.height = widget.node.parentNode.offsetHeight)
  2812. }
  2813. // Return true when the given mouse event happened in a widget
  2814. function eventInWidget(display, e) {
  2815. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2816. if (!n || (n.nodeType == 1 && n.getAttribute('cm-ignore-events') == 'true') || (n.parentNode == display.sizer && n != display.mover)) {
  2817. return true
  2818. }
  2819. }
  2820. }
  2821. // POSITION MEASUREMENT
  2822. function paddingTop(display) {
  2823. return display.lineSpace.offsetTop
  2824. }
  2825. function paddingVert(display) {
  2826. return display.mover.offsetHeight - display.lineSpace.offsetHeight
  2827. }
  2828. function paddingH(display) {
  2829. if (display.cachedPaddingH) {
  2830. return display.cachedPaddingH
  2831. }
  2832. var e = removeChildrenAndAdd(display.measure, elt('pre', 'x', 'CodeMirror-line-like'))
  2833. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2834. var data = { left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight) }
  2835. if (!isNaN(data.left) && !isNaN(data.right)) {
  2836. display.cachedPaddingH = data
  2837. }
  2838. return data
  2839. }
  2840. function scrollGap(cm) {
  2841. return scrollerGap - cm.display.nativeBarWidth
  2842. }
  2843. function displayWidth(cm) {
  2844. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2845. }
  2846. function displayHeight(cm) {
  2847. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2848. }
  2849. // Ensure the lineView.wrapping.heights array is populated. This is
  2850. // an array of bottom offsets for the lines that make up a drawn
  2851. // line. When lineWrapping is on, there might be more than one
  2852. // height.
  2853. function ensureLineHeights(cm, lineView, rect) {
  2854. var wrapping = cm.options.lineWrapping
  2855. var curWidth = wrapping && displayWidth(cm)
  2856. if (!lineView.measure.heights || (wrapping && lineView.measure.width != curWidth)) {
  2857. var heights = (lineView.measure.heights = [])
  2858. if (wrapping) {
  2859. lineView.measure.width = curWidth
  2860. var rects = lineView.text.firstChild.getClientRects()
  2861. for (var i = 0; i < rects.length - 1; i++) {
  2862. var cur = rects[i],
  2863. next = rects[i + 1]
  2864. if (Math.abs(cur.bottom - next.bottom) > 2) {
  2865. heights.push((cur.bottom + next.top) / 2 - rect.top)
  2866. }
  2867. }
  2868. }
  2869. heights.push(rect.bottom - rect.top)
  2870. }
  2871. }
  2872. // Find a line map (mapping character offsets to text nodes) and a
  2873. // measurement cache for the given line number. (A line view might
  2874. // contain multiple lines when collapsed ranges are present.)
  2875. function mapFromLineView(lineView, line, lineN) {
  2876. if (lineView.line == line) {
  2877. return { map: lineView.measure.map, cache: lineView.measure.cache }
  2878. }
  2879. if (lineView.rest) {
  2880. for (var i = 0; i < lineView.rest.length; i++) {
  2881. if (lineView.rest[i] == line) {
  2882. return { map: lineView.measure.maps[i], cache: lineView.measure.caches[i] }
  2883. }
  2884. }
  2885. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) {
  2886. if (lineNo(lineView.rest[i$1]) > lineN) {
  2887. return { map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true }
  2888. }
  2889. }
  2890. }
  2891. }
  2892. // Render a line into the hidden node display.externalMeasured. Used
  2893. // when measurement is needed for a line that's not in the viewport.
  2894. function updateExternalMeasurement(cm, line) {
  2895. line = visualLine(line)
  2896. var lineN = lineNo(line)
  2897. var view = (cm.display.externalMeasured = new LineView(cm.doc, line, lineN))
  2898. view.lineN = lineN
  2899. var built = (view.built = buildLineContent(cm, view))
  2900. view.text = built.pre
  2901. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2902. return view
  2903. }
  2904. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2905. // for a given character.
  2906. function measureChar(cm, line, ch, bias) {
  2907. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2908. }
  2909. // Find a line view that corresponds to the given line number.
  2910. function findViewForLine(cm, lineN) {
  2911. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {
  2912. return cm.display.view[findViewIndex(cm, lineN)]
  2913. }
  2914. var ext = cm.display.externalMeasured
  2915. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) {
  2916. return ext
  2917. }
  2918. }
  2919. // Measurement can be split in two steps, the set-up work that
  2920. // applies to the whole line, and the measurement of the actual
  2921. // character. Functions like coordsChar, that need to do a lot of
  2922. // measurements in a row, can thus ensure that the set-up work is
  2923. // only done once.
  2924. function prepareMeasureForLine(cm, line) {
  2925. var lineN = lineNo(line)
  2926. var view = findViewForLine(cm, lineN)
  2927. if (view && !view.text) {
  2928. view = null
  2929. } else if (view && view.changes) {
  2930. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2931. cm.curOp.forceUpdate = true
  2932. }
  2933. if (!view) {
  2934. view = updateExternalMeasurement(cm, line)
  2935. }
  2936. var info = mapFromLineView(view, line, lineN)
  2937. return {
  2938. line: line,
  2939. view: view,
  2940. rect: null,
  2941. map: info.map,
  2942. cache: info.cache,
  2943. before: info.before,
  2944. hasHeights: false,
  2945. }
  2946. }
  2947. // Given a prepared measurement object, measures the position of an
  2948. // actual character (or fetches it from the cache).
  2949. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2950. if (prepared.before) {
  2951. ch = -1
  2952. }
  2953. var key = ch + (bias || ''),
  2954. found
  2955. if (prepared.cache.hasOwnProperty(key)) {
  2956. found = prepared.cache[key]
  2957. } else {
  2958. if (!prepared.rect) {
  2959. prepared.rect = prepared.view.text.getBoundingClientRect()
  2960. }
  2961. if (!prepared.hasHeights) {
  2962. ensureLineHeights(cm, prepared.view, prepared.rect)
  2963. prepared.hasHeights = true
  2964. }
  2965. found = measureCharInner(cm, prepared, ch, bias)
  2966. if (!found.bogus) {
  2967. prepared.cache[key] = found
  2968. }
  2969. }
  2970. return { left: found.left, right: found.right, top: varHeight ? found.rtop : found.top, bottom: varHeight ? found.rbottom : found.bottom }
  2971. }
  2972. var nullRect = { left: 0, right: 0, top: 0, bottom: 0 }
  2973. function nodeAndOffsetInLineMap(map, ch, bias) {
  2974. var node, start, end, collapse, mStart, mEnd
  2975. // First, search the line map for the text node corresponding to,
  2976. // or closest to, the target character.
  2977. for (var i = 0; i < map.length; i += 3) {
  2978. mStart = map[i]
  2979. mEnd = map[i + 1]
  2980. if (ch < mStart) {
  2981. start = 0
  2982. end = 1
  2983. collapse = 'left'
  2984. } else if (ch < mEnd) {
  2985. start = ch - mStart
  2986. end = start + 1
  2987. } else if (i == map.length - 3 || (ch == mEnd && map[i + 3] > ch)) {
  2988. end = mEnd - mStart
  2989. start = end - 1
  2990. if (ch >= mEnd) {
  2991. collapse = 'right'
  2992. }
  2993. }
  2994. if (start != null) {
  2995. node = map[i + 2]
  2996. if (mStart == mEnd && bias == (node.insertLeft ? 'left' : 'right')) {
  2997. collapse = bias
  2998. }
  2999. if (bias == 'left' && start == 0) {
  3000. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  3001. node = map[(i -= 3) + 2]
  3002. collapse = 'left'
  3003. }
  3004. }
  3005. if (bias == 'right' && start == mEnd - mStart) {
  3006. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  3007. node = map[(i += 3) + 2]
  3008. collapse = 'right'
  3009. }
  3010. }
  3011. break
  3012. }
  3013. }
  3014. return { node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd }
  3015. }
  3016. function getUsefulRect(rects, bias) {
  3017. var rect = nullRect
  3018. if (bias == 'left') {
  3019. for (var i = 0; i < rects.length; i++) {
  3020. if ((rect = rects[i]).left != rect.right) {
  3021. break
  3022. }
  3023. }
  3024. } else {
  3025. for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  3026. if ((rect = rects[i$1]).left != rect.right) {
  3027. break
  3028. }
  3029. }
  3030. }
  3031. return rect
  3032. }
  3033. function measureCharInner(cm, prepared, ch, bias) {
  3034. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  3035. var node = place.node,
  3036. start = place.start,
  3037. end = place.end,
  3038. collapse = place.collapse
  3039. var rect
  3040. if (node.nodeType == 3) {
  3041. // If it is a text node, use a range to retrieve the coordinates.
  3042. for (var i$1 = 0; i$1 < 4; i$1++) {
  3043. // Retry a maximum of 4 times when nonsense rectangles are returned
  3044. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) {
  3045. --start
  3046. }
  3047. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) {
  3048. ++end
  3049. }
  3050. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  3051. rect = node.parentNode.getBoundingClientRect()
  3052. } else {
  3053. rect = getUsefulRect(range(node, start, end).getClientRects(), bias)
  3054. }
  3055. if (rect.left || rect.right || start == 0) {
  3056. break
  3057. }
  3058. end = start
  3059. start = start - 1
  3060. collapse = 'right'
  3061. }
  3062. if (ie && ie_version < 11) {
  3063. rect = maybeUpdateRectForZooming(cm.display.measure, rect)
  3064. }
  3065. } else {
  3066. // If it is a widget, simply get the box for the whole widget.
  3067. if (start > 0) {
  3068. collapse = bias = 'right'
  3069. }
  3070. var rects
  3071. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {
  3072. rect = rects[bias == 'right' ? rects.length - 1 : 0]
  3073. } else {
  3074. rect = node.getBoundingClientRect()
  3075. }
  3076. }
  3077. if (ie && ie_version < 9 && !start && (!rect || (!rect.left && !rect.right))) {
  3078. var rSpan = node.parentNode.getClientRects()[0]
  3079. if (rSpan) {
  3080. rect = { left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom }
  3081. } else {
  3082. rect = nullRect
  3083. }
  3084. }
  3085. var rtop = rect.top - prepared.rect.top,
  3086. rbot = rect.bottom - prepared.rect.top
  3087. var mid = (rtop + rbot) / 2
  3088. var heights = prepared.view.measure.heights
  3089. var i = 0
  3090. for (; i < heights.length - 1; i++) {
  3091. if (mid < heights[i]) {
  3092. break
  3093. }
  3094. }
  3095. var top = i ? heights[i - 1] : 0,
  3096. bot = heights[i]
  3097. var result = { left: (collapse == 'right' ? rect.right : rect.left) - prepared.rect.left, right: (collapse == 'left' ? rect.left : rect.right) - prepared.rect.left, top: top, bottom: bot }
  3098. if (!rect.left && !rect.right) {
  3099. result.bogus = true
  3100. }
  3101. if (!cm.options.singleCursorHeightPerLine) {
  3102. result.rtop = rtop
  3103. result.rbottom = rbot
  3104. }
  3105. return result
  3106. }
  3107. // Work around problem with bounding client rects on ranges being
  3108. // returned incorrectly when zoomed on IE10 and below.
  3109. function maybeUpdateRectForZooming(measure, rect) {
  3110. if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {
  3111. return rect
  3112. }
  3113. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  3114. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  3115. return { left: rect.left * scaleX, right: rect.right * scaleX, top: rect.top * scaleY, bottom: rect.bottom * scaleY }
  3116. }
  3117. function clearLineMeasurementCacheFor(lineView) {
  3118. if (lineView.measure) {
  3119. lineView.measure.cache = {}
  3120. lineView.measure.heights = null
  3121. if (lineView.rest) {
  3122. for (var i = 0; i < lineView.rest.length; i++) {
  3123. lineView.measure.caches[i] = {}
  3124. }
  3125. }
  3126. }
  3127. }
  3128. function clearLineMeasurementCache(cm) {
  3129. cm.display.externalMeasure = null
  3130. removeChildren(cm.display.lineMeasure)
  3131. for (var i = 0; i < cm.display.view.length; i++) {
  3132. clearLineMeasurementCacheFor(cm.display.view[i])
  3133. }
  3134. }
  3135. function clearCaches(cm) {
  3136. clearLineMeasurementCache(cm)
  3137. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  3138. if (!cm.options.lineWrapping) {
  3139. cm.display.maxLineChanged = true
  3140. }
  3141. cm.display.lineNumChars = null
  3142. }
  3143. function pageScrollX() {
  3144. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  3145. // which causes page_Offset and bounding client rects to use
  3146. // different reference viewports and invalidate our calculations.
  3147. if (chrome && android) {
  3148. return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft))
  3149. }
  3150. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  3151. }
  3152. function pageScrollY() {
  3153. if (chrome && android) {
  3154. return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop))
  3155. }
  3156. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  3157. }
  3158. function widgetTopHeight(lineObj) {
  3159. var ref = visualLine(lineObj)
  3160. var widgets = ref.widgets
  3161. var height = 0
  3162. if (widgets) {
  3163. for (var i = 0; i < widgets.length; ++i) {
  3164. if (widgets[i].above) {
  3165. height += widgetHeight(widgets[i])
  3166. }
  3167. }
  3168. }
  3169. return height
  3170. }
  3171. // Converts a {top, bottom, left, right} box from line-local
  3172. // coordinates into another coordinate system. Context may be one of
  3173. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  3174. // or "page".
  3175. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  3176. if (!includeWidgets) {
  3177. var height = widgetTopHeight(lineObj)
  3178. rect.top += height
  3179. rect.bottom += height
  3180. }
  3181. if (context == 'line') {
  3182. return rect
  3183. }
  3184. if (!context) {
  3185. context = 'local'
  3186. }
  3187. var yOff = heightAtLine(lineObj)
  3188. if (context == 'local') {
  3189. yOff += paddingTop(cm.display)
  3190. } else {
  3191. yOff -= cm.display.viewOffset
  3192. }
  3193. if (context == 'page' || context == 'window') {
  3194. var lOff = cm.display.lineSpace.getBoundingClientRect()
  3195. yOff += lOff.top + (context == 'window' ? 0 : pageScrollY())
  3196. var xOff = lOff.left + (context == 'window' ? 0 : pageScrollX())
  3197. rect.left += xOff
  3198. rect.right += xOff
  3199. }
  3200. rect.top += yOff
  3201. rect.bottom += yOff
  3202. return rect
  3203. }
  3204. // Coverts a box from "div" coords to another coordinate system.
  3205. // Context may be "window", "page", "div", or "local"./null.
  3206. function fromCoordSystem(cm, coords, context) {
  3207. if (context == 'div') {
  3208. return coords
  3209. }
  3210. var left = coords.left,
  3211. top = coords.top
  3212. // First move into "page" coordinate system
  3213. if (context == 'page') {
  3214. left -= pageScrollX()
  3215. top -= pageScrollY()
  3216. } else if (context == 'local' || !context) {
  3217. var localBox = cm.display.sizer.getBoundingClientRect()
  3218. left += localBox.left
  3219. top += localBox.top
  3220. }
  3221. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  3222. return { left: left - lineSpaceBox.left, top: top - lineSpaceBox.top }
  3223. }
  3224. function charCoords(cm, pos, context, lineObj, bias) {
  3225. if (!lineObj) {
  3226. lineObj = getLine(cm.doc, pos.line)
  3227. }
  3228. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  3229. }
  3230. // Returns a box for a given cursor position, which may have an
  3231. // 'other' property containing the position of the secondary cursor
  3232. // on a bidi boundary.
  3233. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  3234. // and after `char - 1` in writing order of `char - 1`
  3235. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  3236. // and before `char` in writing order of `char`
  3237. // Examples (upper-case letters are RTL, lower-case are LTR):
  3238. // Pos(0, 1, ...)
  3239. // before after
  3240. // ab a|b a|b
  3241. // aB a|B aB|
  3242. // Ab |Ab A|b
  3243. // AB B|A B|A
  3244. // Every position after the last character on a line is considered to stick
  3245. // to the last character on the line.
  3246. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  3247. lineObj = lineObj || getLine(cm.doc, pos.line)
  3248. if (!preparedMeasure) {
  3249. preparedMeasure = prepareMeasureForLine(cm, lineObj)
  3250. }
  3251. function get(ch, right) {
  3252. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? 'right' : 'left', varHeight)
  3253. if (right) {
  3254. m.left = m.right
  3255. } else {
  3256. m.right = m.left
  3257. }
  3258. return intoCoordSystem(cm, lineObj, m, context)
  3259. }
  3260. var order = getOrder(lineObj, cm.doc.direction),
  3261. ch = pos.ch,
  3262. sticky = pos.sticky
  3263. if (ch >= lineObj.text.length) {
  3264. ch = lineObj.text.length
  3265. sticky = 'before'
  3266. } else if (ch <= 0) {
  3267. ch = 0
  3268. sticky = 'after'
  3269. }
  3270. if (!order) {
  3271. return get(sticky == 'before' ? ch - 1 : ch, sticky == 'before')
  3272. }
  3273. function getBidi(ch, partPos, invert) {
  3274. var part = order[partPos],
  3275. right = part.level == 1
  3276. return get(invert ? ch - 1 : ch, right != invert)
  3277. }
  3278. var partPos = getBidiPartAt(order, ch, sticky)
  3279. var other = bidiOther
  3280. var val = getBidi(ch, partPos, sticky == 'before')
  3281. if (other != null) {
  3282. val.other = getBidi(ch, other, sticky != 'before')
  3283. }
  3284. return val
  3285. }
  3286. // Used to cheaply estimate the coordinates for a position. Used for
  3287. // intermediate scroll updates.
  3288. function estimateCoords(cm, pos) {
  3289. var left = 0
  3290. pos = clipPos(cm.doc, pos)
  3291. if (!cm.options.lineWrapping) {
  3292. left = charWidth(cm.display) * pos.ch
  3293. }
  3294. var lineObj = getLine(cm.doc, pos.line)
  3295. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  3296. return { left: left, right: left, top: top, bottom: top + lineObj.height }
  3297. }
  3298. // Positions returned by coordsChar contain some extra information.
  3299. // xRel is the relative x position of the input coordinates compared
  3300. // to the found position (so xRel > 0 means the coordinates are to
  3301. // the right of the character position, for example). When outside
  3302. // is true, that means the coordinates lie outside the line's
  3303. // vertical range.
  3304. function PosWithInfo(line, ch, sticky, outside, xRel) {
  3305. var pos = Pos(line, ch, sticky)
  3306. pos.xRel = xRel
  3307. if (outside) {
  3308. pos.outside = outside
  3309. }
  3310. return pos
  3311. }
  3312. // Compute the character position closest to the given coordinates.
  3313. // Input must be lineSpace-local ("div" coordinate system).
  3314. function coordsChar(cm, x, y) {
  3315. var doc = cm.doc
  3316. y += cm.display.viewOffset
  3317. if (y < 0) {
  3318. return PosWithInfo(doc.first, 0, null, -1, -1)
  3319. }
  3320. var lineN = lineAtHeight(doc, y),
  3321. last = doc.first + doc.size - 1
  3322. if (lineN > last) {
  3323. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1)
  3324. }
  3325. if (x < 0) {
  3326. x = 0
  3327. }
  3328. var lineObj = getLine(doc, lineN)
  3329. for (;;) {
  3330. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  3331. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0))
  3332. if (!collapsed) {
  3333. return found
  3334. }
  3335. var rangeEnd = collapsed.find(1)
  3336. if (rangeEnd.line == lineN) {
  3337. return rangeEnd
  3338. }
  3339. lineObj = getLine(doc, (lineN = rangeEnd.line))
  3340. }
  3341. }
  3342. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  3343. y -= widgetTopHeight(lineObj)
  3344. var end = lineObj.text.length
  3345. var begin = findFirst(
  3346. function (ch) {
  3347. return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y
  3348. },
  3349. end,
  3350. 0
  3351. )
  3352. end = findFirst(
  3353. function (ch) {
  3354. return measureCharPrepared(cm, preparedMeasure, ch).top > y
  3355. },
  3356. begin,
  3357. end
  3358. )
  3359. return { begin: begin, end: end }
  3360. }
  3361. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  3362. if (!preparedMeasure) {
  3363. preparedMeasure = prepareMeasureForLine(cm, lineObj)
  3364. }
  3365. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), 'line').top
  3366. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  3367. }
  3368. // Returns true if the given side of a box is after the given
  3369. // coordinates, in top-to-bottom, left-to-right order.
  3370. function boxIsAfter(box, x, y, left) {
  3371. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  3372. }
  3373. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  3374. // Move y into line-local coordinate space
  3375. y -= heightAtLine(lineObj)
  3376. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  3377. // When directly calling `measureCharPrepared`, we have to adjust
  3378. // for the widgets at this line.
  3379. var widgetHeight = widgetTopHeight(lineObj)
  3380. var begin = 0,
  3381. end = lineObj.text.length,
  3382. ltr = true
  3383. var order = getOrder(lineObj, cm.doc.direction)
  3384. // If the line isn't plain left-to-right text, first figure out
  3385. // which bidi section the coordinates fall into.
  3386. if (order) {
  3387. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo, preparedMeasure, order, x, y)
  3388. ltr = part.level != 1
  3389. // The awkward -1 offsets are needed because findFirst (called
  3390. // on these below) will treat its first bound as inclusive,
  3391. // second as exclusive, but we want to actually address the
  3392. // characters in the part's range
  3393. begin = ltr ? part.from : part.to - 1
  3394. end = ltr ? part.to : part.from - 1
  3395. }
  3396. // A binary search to find the first character whose bounding box
  3397. // starts after the coordinates. If we run across any whose box wrap
  3398. // the coordinates, store that.
  3399. var chAround = null,
  3400. boxAround = null
  3401. var ch = findFirst(
  3402. function (ch) {
  3403. var box = measureCharPrepared(cm, preparedMeasure, ch)
  3404. box.top += widgetHeight
  3405. box.bottom += widgetHeight
  3406. if (!boxIsAfter(box, x, y, false)) {
  3407. return false
  3408. }
  3409. if (box.top <= y && box.left <= x) {
  3410. chAround = ch
  3411. boxAround = box
  3412. }
  3413. return true
  3414. },
  3415. begin,
  3416. end
  3417. )
  3418. var baseX,
  3419. sticky,
  3420. outside = false
  3421. // If a box around the coordinates was found, use that
  3422. if (boxAround) {
  3423. // Distinguish coordinates nearer to the left or right side of the box
  3424. var atLeft = x - boxAround.left < boxAround.right - x,
  3425. atStart = atLeft == ltr
  3426. ch = chAround + (atStart ? 0 : 1)
  3427. sticky = atStart ? 'after' : 'before'
  3428. baseX = atLeft ? boxAround.left : boxAround.right
  3429. } else {
  3430. // (Adjust for extended bound, if necessary.)
  3431. if (!ltr && (ch == end || ch == begin)) {
  3432. ch++
  3433. }
  3434. // To determine which side to associate with, get the box to the
  3435. // left of the character and compare it's vertical position to the
  3436. // coordinates
  3437. sticky = ch == 0 ? 'after' : ch == lineObj.text.length ? 'before' : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y == ltr ? 'after' : 'before'
  3438. // Now get accurate coordinates for this place, in order to get a
  3439. // base X position
  3440. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), 'line', lineObj, preparedMeasure)
  3441. baseX = coords.left
  3442. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0
  3443. }
  3444. ch = skipExtendingChars(lineObj.text, ch, 1)
  3445. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  3446. }
  3447. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  3448. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  3449. // situation, we can take this ordering to correspond to the visual
  3450. // ordering. This finds the first part whose end is after the given
  3451. // coordinates.
  3452. var index = findFirst(
  3453. function (i) {
  3454. var part = order[i],
  3455. ltr = part.level != 1
  3456. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? 'before' : 'after'), 'line', lineObj, preparedMeasure), x, y, true)
  3457. },
  3458. 0,
  3459. order.length - 1
  3460. )
  3461. var part = order[index]
  3462. // If this isn't the first part, the part's start is also after
  3463. // the coordinates, and the coordinates aren't on the same line as
  3464. // that start, move one part back.
  3465. if (index > 0) {
  3466. var ltr = part.level != 1
  3467. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? 'after' : 'before'), 'line', lineObj, preparedMeasure)
  3468. if (boxIsAfter(start, x, y, true) && start.top > y) {
  3469. part = order[index - 1]
  3470. }
  3471. }
  3472. return part
  3473. }
  3474. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  3475. // In a wrapped line, rtl text on wrapping boundaries can do things
  3476. // that don't correspond to the ordering in our `order` array at
  3477. // all, so a binary search doesn't work, and we want to return a
  3478. // part that only spans one line so that the binary search in
  3479. // coordsCharInner is safe. As such, we first find the extent of the
  3480. // wrapped line, and then do a flat search in which we discard any
  3481. // spans that aren't on the line.
  3482. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y)
  3483. var begin = ref.begin
  3484. var end = ref.end
  3485. if (/\s/.test(lineObj.text.charAt(end - 1))) {
  3486. end--
  3487. }
  3488. var part = null,
  3489. closestDist = null
  3490. for (var i = 0; i < order.length; i++) {
  3491. var p = order[i]
  3492. if (p.from >= end || p.to <= begin) {
  3493. continue
  3494. }
  3495. var ltr = p.level != 1
  3496. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right
  3497. // Weigh against spans ending before this, so that they are only
  3498. // picked if nothing ends after
  3499. var dist = endX < x ? x - endX + 1e9 : endX - x
  3500. if (!part || closestDist > dist) {
  3501. part = p
  3502. closestDist = dist
  3503. }
  3504. }
  3505. if (!part) {
  3506. part = order[order.length - 1]
  3507. }
  3508. // Clip the part to the wrapped line.
  3509. if (part.from < begin) {
  3510. part = { from: begin, to: part.to, level: part.level }
  3511. }
  3512. if (part.to > end) {
  3513. part = { from: part.from, to: end, level: part.level }
  3514. }
  3515. return part
  3516. }
  3517. var measureText
  3518. // Compute the default text height.
  3519. function textHeight(display) {
  3520. if (display.cachedTextHeight != null) {
  3521. return display.cachedTextHeight
  3522. }
  3523. if (measureText == null) {
  3524. measureText = elt('pre', null, 'CodeMirror-line-like')
  3525. // Measure a bunch of lines, for browsers that compute
  3526. // fractional heights.
  3527. for (var i = 0; i < 49; ++i) {
  3528. measureText.appendChild(document.createTextNode('x'))
  3529. measureText.appendChild(elt('br'))
  3530. }
  3531. measureText.appendChild(document.createTextNode('x'))
  3532. }
  3533. removeChildrenAndAdd(display.measure, measureText)
  3534. var height = measureText.offsetHeight / 50
  3535. if (height > 3) {
  3536. display.cachedTextHeight = height
  3537. }
  3538. removeChildren(display.measure)
  3539. return height || 1
  3540. }
  3541. // Compute the default character width.
  3542. function charWidth(display) {
  3543. if (display.cachedCharWidth != null) {
  3544. return display.cachedCharWidth
  3545. }
  3546. var anchor = elt('span', 'xxxxxxxxxx')
  3547. var pre = elt('pre', [anchor], 'CodeMirror-line-like')
  3548. removeChildrenAndAdd(display.measure, pre)
  3549. var rect = anchor.getBoundingClientRect(),
  3550. width = (rect.right - rect.left) / 10
  3551. if (width > 2) {
  3552. display.cachedCharWidth = width
  3553. }
  3554. return width || 10
  3555. }
  3556. // Do a bulk-read of the DOM positions and sizes needed to draw the
  3557. // view, so that we don't interleave reading and writing to the DOM.
  3558. function getDimensions(cm) {
  3559. var d = cm.display,
  3560. left = {},
  3561. width = {}
  3562. var gutterLeft = d.gutters.clientLeft
  3563. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  3564. var id = cm.display.gutterSpecs[i].className
  3565. left[id] = n.offsetLeft + n.clientLeft + gutterLeft
  3566. width[id] = n.clientWidth
  3567. }
  3568. return { fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth }
  3569. }
  3570. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  3571. // but using getBoundingClientRect to get a sub-pixel-accurate
  3572. // result.
  3573. function compensateForHScroll(display) {
  3574. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  3575. }
  3576. // Returns a function that estimates the height of a line, to use as
  3577. // first approximation until the line becomes visible (and is thus
  3578. // properly measurable).
  3579. function estimateHeight(cm) {
  3580. var th = textHeight(cm.display),
  3581. wrapping = cm.options.lineWrapping
  3582. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  3583. return function (line) {
  3584. if (lineIsHidden(cm.doc, line)) {
  3585. return 0
  3586. }
  3587. var widgetsHeight = 0
  3588. if (line.widgets) {
  3589. for (var i = 0; i < line.widgets.length; i++) {
  3590. if (line.widgets[i].height) {
  3591. widgetsHeight += line.widgets[i].height
  3592. }
  3593. }
  3594. }
  3595. if (wrapping) {
  3596. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th
  3597. } else {
  3598. return widgetsHeight + th
  3599. }
  3600. }
  3601. }
  3602. function estimateLineHeights(cm) {
  3603. var doc = cm.doc,
  3604. est = estimateHeight(cm)
  3605. doc.iter(function (line) {
  3606. var estHeight = est(line)
  3607. if (estHeight != line.height) {
  3608. updateLineHeight(line, estHeight)
  3609. }
  3610. })
  3611. }
  3612. // Given a mouse event, find the corresponding position. If liberal
  3613. // is false, it checks whether a gutter or scrollbar was clicked,
  3614. // and returns null if it was. forRect is used by rectangular
  3615. // selections, and tries to estimate a character position even for
  3616. // coordinates beyond the right of the text.
  3617. function posFromMouse(cm, e, liberal, forRect) {
  3618. var display = cm.display
  3619. if (!liberal && e_target(e).getAttribute('cm-not-content') == 'true') {
  3620. return null
  3621. }
  3622. var x,
  3623. y,
  3624. space = display.lineSpace.getBoundingClientRect()
  3625. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3626. try {
  3627. x = e.clientX - space.left
  3628. y = e.clientY - space.top
  3629. } catch (e$1) {
  3630. return null
  3631. }
  3632. var coords = coordsChar(cm, x, y),
  3633. line
  3634. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3635. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  3636. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  3637. }
  3638. return coords
  3639. }
  3640. // Find the view element corresponding to a given line. Return null
  3641. // when the line isn't visible.
  3642. function findViewIndex(cm, n) {
  3643. if (n >= cm.display.viewTo) {
  3644. return null
  3645. }
  3646. n -= cm.display.viewFrom
  3647. if (n < 0) {
  3648. return null
  3649. }
  3650. var view = cm.display.view
  3651. for (var i = 0; i < view.length; i++) {
  3652. n -= view[i].size
  3653. if (n < 0) {
  3654. return i
  3655. }
  3656. }
  3657. }
  3658. // Updates the display.view data structure for a given change to the
  3659. // document. From and to are in pre-change coordinates. Lendiff is
  3660. // the amount of lines added or subtracted by the change. This is
  3661. // used for changes that span multiple lines, or change the way
  3662. // lines are divided into visual lines. regLineChange (below)
  3663. // registers single-line changes.
  3664. function regChange(cm, from, to, lendiff) {
  3665. if (from == null) {
  3666. from = cm.doc.first
  3667. }
  3668. if (to == null) {
  3669. to = cm.doc.first + cm.doc.size
  3670. }
  3671. if (!lendiff) {
  3672. lendiff = 0
  3673. }
  3674. var display = cm.display
  3675. if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) {
  3676. display.updateLineNumbers = from
  3677. }
  3678. cm.curOp.viewChanged = true
  3679. if (from >= display.viewTo) {
  3680. // Change after
  3681. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {
  3682. resetView(cm)
  3683. }
  3684. } else if (to <= display.viewFrom) {
  3685. // Change before
  3686. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3687. resetView(cm)
  3688. } else {
  3689. display.viewFrom += lendiff
  3690. display.viewTo += lendiff
  3691. }
  3692. } else if (from <= display.viewFrom && to >= display.viewTo) {
  3693. // Full overlap
  3694. resetView(cm)
  3695. } else if (from <= display.viewFrom) {
  3696. // Top overlap
  3697. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3698. if (cut) {
  3699. display.view = display.view.slice(cut.index)
  3700. display.viewFrom = cut.lineN
  3701. display.viewTo += lendiff
  3702. } else {
  3703. resetView(cm)
  3704. }
  3705. } else if (to >= display.viewTo) {
  3706. // Bottom overlap
  3707. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3708. if (cut$1) {
  3709. display.view = display.view.slice(0, cut$1.index)
  3710. display.viewTo = cut$1.lineN
  3711. } else {
  3712. resetView(cm)
  3713. }
  3714. } else {
  3715. // Gap in the middle
  3716. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3717. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3718. if (cutTop && cutBot) {
  3719. display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index))
  3720. display.viewTo += lendiff
  3721. } else {
  3722. resetView(cm)
  3723. }
  3724. }
  3725. var ext = display.externalMeasured
  3726. if (ext) {
  3727. if (to < ext.lineN) {
  3728. ext.lineN += lendiff
  3729. } else if (from < ext.lineN + ext.size) {
  3730. display.externalMeasured = null
  3731. }
  3732. }
  3733. }
  3734. // Register a change to a single line. Type must be one of "text",
  3735. // "gutter", "class", "widget"
  3736. function regLineChange(cm, line, type) {
  3737. cm.curOp.viewChanged = true
  3738. var display = cm.display,
  3739. ext = cm.display.externalMeasured
  3740. if (ext && line >= ext.lineN && line < ext.lineN + ext.size) {
  3741. display.externalMeasured = null
  3742. }
  3743. if (line < display.viewFrom || line >= display.viewTo) {
  3744. return
  3745. }
  3746. var lineView = display.view[findViewIndex(cm, line)]
  3747. if (lineView.node == null) {
  3748. return
  3749. }
  3750. var arr = lineView.changes || (lineView.changes = [])
  3751. if (indexOf(arr, type) == -1) {
  3752. arr.push(type)
  3753. }
  3754. }
  3755. // Clear the view.
  3756. function resetView(cm) {
  3757. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3758. cm.display.view = []
  3759. cm.display.viewOffset = 0
  3760. }
  3761. function viewCuttingPoint(cm, oldN, newN, dir) {
  3762. var index = findViewIndex(cm, oldN),
  3763. diff,
  3764. view = cm.display.view
  3765. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {
  3766. return { index: index, lineN: newN }
  3767. }
  3768. var n = cm.display.viewFrom
  3769. for (var i = 0; i < index; i++) {
  3770. n += view[i].size
  3771. }
  3772. if (n != oldN) {
  3773. if (dir > 0) {
  3774. if (index == view.length - 1) {
  3775. return null
  3776. }
  3777. diff = n + view[index].size - oldN
  3778. index++
  3779. } else {
  3780. diff = n - oldN
  3781. }
  3782. oldN += diff
  3783. newN += diff
  3784. }
  3785. while (visualLineNo(cm.doc, newN) != newN) {
  3786. if (index == (dir < 0 ? 0 : view.length - 1)) {
  3787. return null
  3788. }
  3789. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3790. index += dir
  3791. }
  3792. return { index: index, lineN: newN }
  3793. }
  3794. // Force the view to cover a given range, adding empty view element
  3795. // or clipping off existing ones as needed.
  3796. function adjustView(cm, from, to) {
  3797. var display = cm.display,
  3798. view = display.view
  3799. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3800. display.view = buildViewArray(cm, from, to)
  3801. display.viewFrom = from
  3802. } else {
  3803. if (display.viewFrom > from) {
  3804. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view)
  3805. } else if (display.viewFrom < from) {
  3806. display.view = display.view.slice(findViewIndex(cm, from))
  3807. }
  3808. display.viewFrom = from
  3809. if (display.viewTo < to) {
  3810. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to))
  3811. } else if (display.viewTo > to) {
  3812. display.view = display.view.slice(0, findViewIndex(cm, to))
  3813. }
  3814. }
  3815. display.viewTo = to
  3816. }
  3817. // Count the number of lines in the view whose DOM representation is
  3818. // out of date (or nonexistent).
  3819. function countDirtyView(cm) {
  3820. var view = cm.display.view,
  3821. dirty = 0
  3822. for (var i = 0; i < view.length; i++) {
  3823. var lineView = view[i]
  3824. if (!lineView.hidden && (!lineView.node || lineView.changes)) {
  3825. ++dirty
  3826. }
  3827. }
  3828. return dirty
  3829. }
  3830. function updateSelection(cm) {
  3831. cm.display.input.showSelection(cm.display.input.prepareSelection())
  3832. }
  3833. function prepareSelection(cm, primary) {
  3834. if (primary === void 0) primary = true
  3835. var doc = cm.doc,
  3836. result = {}
  3837. var curFragment = (result.cursors = document.createDocumentFragment())
  3838. var selFragment = (result.selection = document.createDocumentFragment())
  3839. var customCursor = cm.options.$customCursor
  3840. if (customCursor) {
  3841. primary = true
  3842. }
  3843. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3844. if (!primary && i == doc.sel.primIndex) {
  3845. continue
  3846. }
  3847. var range = doc.sel.ranges[i]
  3848. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) {
  3849. continue
  3850. }
  3851. var collapsed = range.empty()
  3852. if (customCursor) {
  3853. var head = customCursor(cm, range)
  3854. if (head) {
  3855. drawSelectionCursor(cm, head, curFragment)
  3856. }
  3857. } else if (collapsed || cm.options.showCursorWhenSelecting) {
  3858. drawSelectionCursor(cm, range.head, curFragment)
  3859. }
  3860. if (!collapsed) {
  3861. drawSelectionRange(cm, range, selFragment)
  3862. }
  3863. }
  3864. return result
  3865. }
  3866. // Draws a cursor for the given range
  3867. function drawSelectionCursor(cm, head, output) {
  3868. var pos = cursorCoords(cm, head, 'div', null, null, !cm.options.singleCursorHeightPerLine)
  3869. var cursor = output.appendChild(elt('div', '\u00a0', 'CodeMirror-cursor'))
  3870. cursor.style.left = pos.left + 'px'
  3871. cursor.style.top = pos.top + 'px'
  3872. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + 'px'
  3873. if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
  3874. var charPos = charCoords(cm, head, 'div', null, null)
  3875. var width = charPos.right - charPos.left
  3876. cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + 'px'
  3877. }
  3878. if (pos.other) {
  3879. // Secondary cursor, shown when on a 'jump' in bi-directional text
  3880. var otherCursor = output.appendChild(elt('div', '\u00a0', 'CodeMirror-cursor CodeMirror-secondarycursor'))
  3881. otherCursor.style.display = ''
  3882. otherCursor.style.left = pos.other.left + 'px'
  3883. otherCursor.style.top = pos.other.top + 'px'
  3884. otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + 'px'
  3885. }
  3886. }
  3887. function cmpCoords(a, b) {
  3888. return a.top - b.top || a.left - b.left
  3889. }
  3890. // Draws the given range as a highlighted selection
  3891. function drawSelectionRange(cm, range, output) {
  3892. var display = cm.display,
  3893. doc = cm.doc
  3894. var fragment = document.createDocumentFragment()
  3895. var padding = paddingH(cm.display),
  3896. leftSide = padding.left
  3897. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  3898. var docLTR = doc.direction == 'ltr'
  3899. function add(left, top, width, bottom) {
  3900. if (top < 0) {
  3901. top = 0
  3902. }
  3903. top = Math.round(top)
  3904. bottom = Math.round(bottom)
  3905. fragment.appendChild(
  3906. elt(
  3907. 'div',
  3908. null,
  3909. 'CodeMirror-selected',
  3910. 'position: absolute; left: ' +
  3911. left +
  3912. 'px;\n top: ' +
  3913. top +
  3914. 'px; width: ' +
  3915. (width == null ? rightSide - left : width) +
  3916. 'px;\n height: ' +
  3917. (bottom - top) +
  3918. 'px'
  3919. )
  3920. )
  3921. }
  3922. function drawForLine(line, fromArg, toArg) {
  3923. var lineObj = getLine(doc, line)
  3924. var lineLen = lineObj.text.length
  3925. var start, end
  3926. function coords(ch, bias) {
  3927. return charCoords(cm, Pos(line, ch), 'div', lineObj, bias)
  3928. }
  3929. function wrapX(pos, dir, side) {
  3930. var extent = wrappedLineExtentChar(cm, lineObj, null, pos)
  3931. var prop = (dir == 'ltr') == (side == 'after') ? 'left' : 'right'
  3932. var ch = side == 'after' ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1)
  3933. return coords(ch, prop)[prop]
  3934. }
  3935. var order = getOrder(lineObj, doc.direction)
  3936. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  3937. var ltr = dir == 'ltr'
  3938. var fromPos = coords(from, ltr ? 'left' : 'right')
  3939. var toPos = coords(to - 1, ltr ? 'right' : 'left')
  3940. var openStart = fromArg == null && from == 0,
  3941. openEnd = toArg == null && to == lineLen
  3942. var first = i == 0,
  3943. last = !order || i == order.length - 1
  3944. if (toPos.top - fromPos.top <= 3) {
  3945. // Single line
  3946. var openLeft = (docLTR ? openStart : openEnd) && first
  3947. var openRight = (docLTR ? openEnd : openStart) && last
  3948. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left
  3949. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right
  3950. add(left, fromPos.top, right - left, fromPos.bottom)
  3951. } else {
  3952. // Multiple lines
  3953. var topLeft, topRight, botLeft, botRight
  3954. if (ltr) {
  3955. topLeft = docLTR && openStart && first ? leftSide : fromPos.left
  3956. topRight = docLTR ? rightSide : wrapX(from, dir, 'before')
  3957. botLeft = docLTR ? leftSide : wrapX(to, dir, 'after')
  3958. botRight = docLTR && openEnd && last ? rightSide : toPos.right
  3959. } else {
  3960. topLeft = !docLTR ? leftSide : wrapX(from, dir, 'before')
  3961. topRight = !docLTR && openStart && first ? rightSide : fromPos.right
  3962. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left
  3963. botRight = !docLTR ? rightSide : wrapX(to, dir, 'after')
  3964. }
  3965. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom)
  3966. if (fromPos.bottom < toPos.top) {
  3967. add(leftSide, fromPos.bottom, null, toPos.top)
  3968. }
  3969. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom)
  3970. }
  3971. if (!start || cmpCoords(fromPos, start) < 0) {
  3972. start = fromPos
  3973. }
  3974. if (cmpCoords(toPos, start) < 0) {
  3975. start = toPos
  3976. }
  3977. if (!end || cmpCoords(fromPos, end) < 0) {
  3978. end = fromPos
  3979. }
  3980. if (cmpCoords(toPos, end) < 0) {
  3981. end = toPos
  3982. }
  3983. })
  3984. return { start: start, end: end }
  3985. }
  3986. var sFrom = range.from(),
  3987. sTo = range.to()
  3988. if (sFrom.line == sTo.line) {
  3989. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  3990. } else {
  3991. var fromLine = getLine(doc, sFrom.line),
  3992. toLine = getLine(doc, sTo.line)
  3993. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  3994. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  3995. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  3996. if (singleVLine) {
  3997. if (leftEnd.top < rightStart.top - 2) {
  3998. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  3999. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  4000. } else {
  4001. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  4002. }
  4003. }
  4004. if (leftEnd.bottom < rightStart.top) {
  4005. add(leftSide, leftEnd.bottom, null, rightStart.top)
  4006. }
  4007. }
  4008. output.appendChild(fragment)
  4009. }
  4010. // Cursor-blinking
  4011. function restartBlink(cm) {
  4012. if (!cm.state.focused) {
  4013. return
  4014. }
  4015. var display = cm.display
  4016. clearInterval(display.blinker)
  4017. var on = true
  4018. display.cursorDiv.style.visibility = ''
  4019. if (cm.options.cursorBlinkRate > 0) {
  4020. display.blinker = setInterval(function () {
  4021. if (!cm.hasFocus()) {
  4022. onBlur(cm)
  4023. }
  4024. display.cursorDiv.style.visibility = (on = !on) ? '' : 'hidden'
  4025. }, cm.options.cursorBlinkRate)
  4026. } else if (cm.options.cursorBlinkRate < 0) {
  4027. display.cursorDiv.style.visibility = 'hidden'
  4028. }
  4029. }
  4030. function ensureFocus(cm) {
  4031. if (!cm.hasFocus()) {
  4032. cm.display.input.focus()
  4033. if (!cm.state.focused) {
  4034. onFocus(cm)
  4035. }
  4036. }
  4037. }
  4038. function delayBlurEvent(cm) {
  4039. cm.state.delayingBlurEvent = true
  4040. setTimeout(function () {
  4041. if (cm.state.delayingBlurEvent) {
  4042. cm.state.delayingBlurEvent = false
  4043. if (cm.state.focused) {
  4044. onBlur(cm)
  4045. }
  4046. }
  4047. }, 100)
  4048. }
  4049. function onFocus(cm, e) {
  4050. if (cm.state.delayingBlurEvent && !cm.state.draggingText) {
  4051. cm.state.delayingBlurEvent = false
  4052. }
  4053. if (cm.options.readOnly == 'nocursor') {
  4054. return
  4055. }
  4056. if (!cm.state.focused) {
  4057. signal(cm, 'focus', cm, e)
  4058. cm.state.focused = true
  4059. addClass(cm.display.wrapper, 'CodeMirror-focused')
  4060. // This test prevents this from firing when a context
  4061. // menu is closed (since the input reset would kill the
  4062. // select-all detection hack)
  4063. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  4064. cm.display.input.reset()
  4065. if (webkit) {
  4066. setTimeout(function () {
  4067. return cm.display.input.reset(true)
  4068. }, 20)
  4069. } // Issue #1730
  4070. }
  4071. cm.display.input.receivedFocus()
  4072. }
  4073. restartBlink(cm)
  4074. }
  4075. function onBlur(cm, e) {
  4076. if (cm.state.delayingBlurEvent) {
  4077. return
  4078. }
  4079. if (cm.state.focused) {
  4080. signal(cm, 'blur', cm, e)
  4081. cm.state.focused = false
  4082. rmClass(cm.display.wrapper, 'CodeMirror-focused')
  4083. }
  4084. clearInterval(cm.display.blinker)
  4085. setTimeout(function () {
  4086. if (!cm.state.focused) {
  4087. cm.display.shift = false
  4088. }
  4089. }, 150)
  4090. }
  4091. // Read the actual heights of the rendered lines, and update their
  4092. // stored heights to match.
  4093. function updateHeightsInViewport(cm) {
  4094. var display = cm.display
  4095. var prevBottom = display.lineDiv.offsetTop
  4096. var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top)
  4097. var oldHeight = display.lineDiv.getBoundingClientRect().top
  4098. var mustScroll = 0
  4099. for (var i = 0; i < display.view.length; i++) {
  4100. var cur = display.view[i],
  4101. wrapping = cm.options.lineWrapping
  4102. var height = void 0,
  4103. width = 0
  4104. if (cur.hidden) {
  4105. continue
  4106. }
  4107. oldHeight += cur.line.height
  4108. if (ie && ie_version < 8) {
  4109. var bot = cur.node.offsetTop + cur.node.offsetHeight
  4110. height = bot - prevBottom
  4111. prevBottom = bot
  4112. } else {
  4113. var box = cur.node.getBoundingClientRect()
  4114. height = box.bottom - box.top
  4115. // Check that lines don't extend past the right of the current
  4116. // editor width
  4117. if (!wrapping && cur.text.firstChild) {
  4118. width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1
  4119. }
  4120. }
  4121. var diff = cur.line.height - height
  4122. if (diff > 0.005 || diff < -0.005) {
  4123. if (oldHeight < viewTop) {
  4124. mustScroll -= diff
  4125. }
  4126. updateLineHeight(cur.line, height)
  4127. updateWidgetHeight(cur.line)
  4128. if (cur.rest) {
  4129. for (var j = 0; j < cur.rest.length; j++) {
  4130. updateWidgetHeight(cur.rest[j])
  4131. }
  4132. }
  4133. }
  4134. if (width > cm.display.sizerWidth) {
  4135. var chWidth = Math.ceil(width / charWidth(cm.display))
  4136. if (chWidth > cm.display.maxLineLength) {
  4137. cm.display.maxLineLength = chWidth
  4138. cm.display.maxLine = cur.line
  4139. cm.display.maxLineChanged = true
  4140. }
  4141. }
  4142. }
  4143. if (Math.abs(mustScroll) > 2) {
  4144. display.scroller.scrollTop += mustScroll
  4145. }
  4146. }
  4147. // Read and store the height of line widgets associated with the
  4148. // given line.
  4149. function updateWidgetHeight(line) {
  4150. if (line.widgets) {
  4151. for (var i = 0; i < line.widgets.length; ++i) {
  4152. var w = line.widgets[i],
  4153. parent = w.node.parentNode
  4154. if (parent) {
  4155. w.height = parent.offsetHeight
  4156. }
  4157. }
  4158. }
  4159. }
  4160. // Compute the lines that are visible in a given viewport (defaults
  4161. // the the current scroll position). viewport may contain top,
  4162. // height, and ensure (see op.scrollToPos) properties.
  4163. function visibleLines(display, doc, viewport) {
  4164. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  4165. top = Math.floor(top - paddingTop(display))
  4166. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  4167. var from = lineAtHeight(doc, top),
  4168. to = lineAtHeight(doc, bottom)
  4169. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  4170. // forces those lines into the viewport (if possible).
  4171. if (viewport && viewport.ensure) {
  4172. var ensureFrom = viewport.ensure.from.line,
  4173. ensureTo = viewport.ensure.to.line
  4174. if (ensureFrom < from) {
  4175. from = ensureFrom
  4176. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  4177. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  4178. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  4179. to = ensureTo
  4180. }
  4181. }
  4182. return { from: from, to: Math.max(to, from + 1) }
  4183. }
  4184. // SCROLLING THINGS INTO VIEW
  4185. // If an editor sits on the top or bottom of the window, partially
  4186. // scrolled out of view, this ensures that the cursor is visible.
  4187. function maybeScrollWindow(cm, rect) {
  4188. if (signalDOMEvent(cm, 'scrollCursorIntoView')) {
  4189. return
  4190. }
  4191. var display = cm.display,
  4192. box = display.sizer.getBoundingClientRect(),
  4193. doScroll = null
  4194. if (rect.top + box.top < 0) {
  4195. doScroll = true
  4196. } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) {
  4197. doScroll = false
  4198. }
  4199. if (doScroll != null && !phantom) {
  4200. var scrollNode = elt(
  4201. 'div',
  4202. '\u200b',
  4203. null,
  4204. 'position: absolute;\n top: ' +
  4205. (rect.top - display.viewOffset - paddingTop(cm.display)) +
  4206. 'px;\n height: ' +
  4207. (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) +
  4208. 'px;\n left: ' +
  4209. rect.left +
  4210. 'px; width: ' +
  4211. Math.max(2, rect.right - rect.left) +
  4212. 'px;'
  4213. )
  4214. cm.display.lineSpace.appendChild(scrollNode)
  4215. scrollNode.scrollIntoView(doScroll)
  4216. cm.display.lineSpace.removeChild(scrollNode)
  4217. }
  4218. }
  4219. // Scroll a given position into view (immediately), verifying that
  4220. // it actually became visible (as line heights are accurately
  4221. // measured, the position of something may 'drift' during drawing).
  4222. function scrollPosIntoView(cm, pos, end, margin) {
  4223. if (margin == null) {
  4224. margin = 0
  4225. }
  4226. var rect
  4227. if (!cm.options.lineWrapping && pos == end) {
  4228. // Set pos and end to the cursor positions around the character pos sticks to
  4229. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  4230. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  4231. end = pos.sticky == 'before' ? Pos(pos.line, pos.ch + 1, 'before') : pos
  4232. pos = pos.ch ? Pos(pos.line, pos.sticky == 'before' ? pos.ch - 1 : pos.ch, 'after') : pos
  4233. }
  4234. for (var limit = 0; limit < 5; limit++) {
  4235. var changed = false
  4236. var coords = cursorCoords(cm, pos)
  4237. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  4238. rect = {
  4239. left: Math.min(coords.left, endCoords.left),
  4240. top: Math.min(coords.top, endCoords.top) - margin,
  4241. right: Math.max(coords.left, endCoords.left),
  4242. bottom: Math.max(coords.bottom, endCoords.bottom) + margin,
  4243. }
  4244. var scrollPos = calculateScrollPos(cm, rect)
  4245. var startTop = cm.doc.scrollTop,
  4246. startLeft = cm.doc.scrollLeft
  4247. if (scrollPos.scrollTop != null) {
  4248. updateScrollTop(cm, scrollPos.scrollTop)
  4249. if (Math.abs(cm.doc.scrollTop - startTop) > 1) {
  4250. changed = true
  4251. }
  4252. }
  4253. if (scrollPos.scrollLeft != null) {
  4254. setScrollLeft(cm, scrollPos.scrollLeft)
  4255. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) {
  4256. changed = true
  4257. }
  4258. }
  4259. if (!changed) {
  4260. break
  4261. }
  4262. }
  4263. return rect
  4264. }
  4265. // Scroll a given set of coordinates into view (immediately).
  4266. function scrollIntoView(cm, rect) {
  4267. var scrollPos = calculateScrollPos(cm, rect)
  4268. if (scrollPos.scrollTop != null) {
  4269. updateScrollTop(cm, scrollPos.scrollTop)
  4270. }
  4271. if (scrollPos.scrollLeft != null) {
  4272. setScrollLeft(cm, scrollPos.scrollLeft)
  4273. }
  4274. }
  4275. // Calculate a new scroll position needed to scroll the given
  4276. // rectangle into view. Returns an object with scrollTop and
  4277. // scrollLeft properties. When these are undefined, the
  4278. // vertical/horizontal position does not need to be adjusted.
  4279. function calculateScrollPos(cm, rect) {
  4280. var display = cm.display,
  4281. snapMargin = textHeight(cm.display)
  4282. if (rect.top < 0) {
  4283. rect.top = 0
  4284. }
  4285. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  4286. var screen = displayHeight(cm),
  4287. result = {}
  4288. if (rect.bottom - rect.top > screen) {
  4289. rect.bottom = rect.top + screen
  4290. }
  4291. var docBottom = cm.doc.height + paddingVert(display)
  4292. var atTop = rect.top < snapMargin,
  4293. atBottom = rect.bottom > docBottom - snapMargin
  4294. if (rect.top < screentop) {
  4295. result.scrollTop = atTop ? 0 : rect.top
  4296. } else if (rect.bottom > screentop + screen) {
  4297. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen)
  4298. if (newTop != screentop) {
  4299. result.scrollTop = newTop
  4300. }
  4301. }
  4302. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth
  4303. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace
  4304. var screenw = displayWidth(cm) - display.gutters.offsetWidth
  4305. var tooWide = rect.right - rect.left > screenw
  4306. if (tooWide) {
  4307. rect.right = rect.left + screenw
  4308. }
  4309. if (rect.left < 10) {
  4310. result.scrollLeft = 0
  4311. } else if (rect.left < screenleft) {
  4312. result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10))
  4313. } else if (rect.right > screenw + screenleft - 3) {
  4314. result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw
  4315. }
  4316. return result
  4317. }
  4318. // Store a relative adjustment to the scroll position in the current
  4319. // operation (to be applied when the operation finishes).
  4320. function addToScrollTop(cm, top) {
  4321. if (top == null) {
  4322. return
  4323. }
  4324. resolveScrollToPos(cm)
  4325. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top
  4326. }
  4327. // Make sure that at the end of the operation the current cursor is
  4328. // shown.
  4329. function ensureCursorVisible(cm) {
  4330. resolveScrollToPos(cm)
  4331. var cur = cm.getCursor()
  4332. cm.curOp.scrollToPos = { from: cur, to: cur, margin: cm.options.cursorScrollMargin }
  4333. }
  4334. function scrollToCoords(cm, x, y) {
  4335. if (x != null || y != null) {
  4336. resolveScrollToPos(cm)
  4337. }
  4338. if (x != null) {
  4339. cm.curOp.scrollLeft = x
  4340. }
  4341. if (y != null) {
  4342. cm.curOp.scrollTop = y
  4343. }
  4344. }
  4345. function scrollToRange(cm, range) {
  4346. resolveScrollToPos(cm)
  4347. cm.curOp.scrollToPos = range
  4348. }
  4349. // When an operation has its scrollToPos property set, and another
  4350. // scroll action is applied before the end of the operation, this
  4351. // 'simulates' scrolling that position into view in a cheap way, so
  4352. // that the effect of intermediate scroll commands is not ignored.
  4353. function resolveScrollToPos(cm) {
  4354. var range = cm.curOp.scrollToPos
  4355. if (range) {
  4356. cm.curOp.scrollToPos = null
  4357. var from = estimateCoords(cm, range.from),
  4358. to = estimateCoords(cm, range.to)
  4359. scrollToCoordsRange(cm, from, to, range.margin)
  4360. }
  4361. }
  4362. function scrollToCoordsRange(cm, from, to, margin) {
  4363. var sPos = calculateScrollPos(cm, {
  4364. left: Math.min(from.left, to.left),
  4365. top: Math.min(from.top, to.top) - margin,
  4366. right: Math.max(from.right, to.right),
  4367. bottom: Math.max(from.bottom, to.bottom) + margin,
  4368. })
  4369. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop)
  4370. }
  4371. // Sync the scrollable area and scrollbars, ensure the viewport
  4372. // covers the visible area.
  4373. function updateScrollTop(cm, val) {
  4374. if (Math.abs(cm.doc.scrollTop - val) < 2) {
  4375. return
  4376. }
  4377. if (!gecko) {
  4378. updateDisplaySimple(cm, { top: val })
  4379. }
  4380. setScrollTop(cm, val, true)
  4381. if (gecko) {
  4382. updateDisplaySimple(cm)
  4383. }
  4384. startWorker(cm, 100)
  4385. }
  4386. function setScrollTop(cm, val, forceScroll) {
  4387. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val))
  4388. if (cm.display.scroller.scrollTop == val && !forceScroll) {
  4389. return
  4390. }
  4391. cm.doc.scrollTop = val
  4392. cm.display.scrollbars.setScrollTop(val)
  4393. if (cm.display.scroller.scrollTop != val) {
  4394. cm.display.scroller.scrollTop = val
  4395. }
  4396. }
  4397. // Sync scroller and scrollbar, ensure the gutter elements are
  4398. // aligned.
  4399. function setScrollLeft(cm, val, isScroller, forceScroll) {
  4400. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth))
  4401. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) {
  4402. return
  4403. }
  4404. cm.doc.scrollLeft = val
  4405. alignHorizontally(cm)
  4406. if (cm.display.scroller.scrollLeft != val) {
  4407. cm.display.scroller.scrollLeft = val
  4408. }
  4409. cm.display.scrollbars.setScrollLeft(val)
  4410. }
  4411. // SCROLLBARS
  4412. // Prepare DOM reads needed to update the scrollbars. Done in one
  4413. // shot to minimize update/measure roundtrips.
  4414. function measureForScrollbars(cm) {
  4415. var d = cm.display,
  4416. gutterW = d.gutters.offsetWidth
  4417. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  4418. return {
  4419. clientHeight: d.scroller.clientHeight,
  4420. viewHeight: d.wrapper.clientHeight,
  4421. scrollWidth: d.scroller.scrollWidth,
  4422. clientWidth: d.scroller.clientWidth,
  4423. viewWidth: d.wrapper.clientWidth,
  4424. barLeft: cm.options.fixedGutter ? gutterW : 0,
  4425. docHeight: docH,
  4426. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  4427. nativeBarWidth: d.nativeBarWidth,
  4428. gutterWidth: gutterW,
  4429. }
  4430. }
  4431. var NativeScrollbars = function (place, scroll, cm) {
  4432. this.cm = cm
  4433. var vert = (this.vert = elt('div', [elt('div', null, null, 'min-width: 1px')], 'CodeMirror-vscrollbar'))
  4434. var horiz = (this.horiz = elt('div', [elt('div', null, null, 'height: 100%; min-height: 1px')], 'CodeMirror-hscrollbar'))
  4435. vert.tabIndex = horiz.tabIndex = -1
  4436. place(vert)
  4437. place(horiz)
  4438. on(vert, 'scroll', function () {
  4439. if (vert.clientHeight) {
  4440. scroll(vert.scrollTop, 'vertical')
  4441. }
  4442. })
  4443. on(horiz, 'scroll', function () {
  4444. if (horiz.clientWidth) {
  4445. scroll(horiz.scrollLeft, 'horizontal')
  4446. }
  4447. })
  4448. this.checkedZeroWidth = false
  4449. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  4450. if (ie && ie_version < 8) {
  4451. this.horiz.style.minHeight = this.vert.style.minWidth = '18px'
  4452. }
  4453. }
  4454. NativeScrollbars.prototype.update = function (measure) {
  4455. var needsH = measure.scrollWidth > measure.clientWidth + 1
  4456. var needsV = measure.scrollHeight > measure.clientHeight + 1
  4457. var sWidth = measure.nativeBarWidth
  4458. if (needsV) {
  4459. this.vert.style.display = 'block'
  4460. this.vert.style.bottom = needsH ? sWidth + 'px' : '0'
  4461. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  4462. // A bug in IE8 can cause this value to be negative, so guard it.
  4463. this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + 'px'
  4464. } else {
  4465. this.vert.scrollTop = 0
  4466. this.vert.style.display = ''
  4467. this.vert.firstChild.style.height = '0'
  4468. }
  4469. if (needsH) {
  4470. this.horiz.style.display = 'block'
  4471. this.horiz.style.right = needsV ? sWidth + 'px' : '0'
  4472. this.horiz.style.left = measure.barLeft + 'px'
  4473. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  4474. this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + 'px'
  4475. } else {
  4476. this.horiz.style.display = ''
  4477. this.horiz.firstChild.style.width = '0'
  4478. }
  4479. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  4480. if (sWidth == 0) {
  4481. this.zeroWidthHack()
  4482. }
  4483. this.checkedZeroWidth = true
  4484. }
  4485. return { right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0 }
  4486. }
  4487. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  4488. if (this.horiz.scrollLeft != pos) {
  4489. this.horiz.scrollLeft = pos
  4490. }
  4491. if (this.disableHoriz) {
  4492. this.enableZeroWidthBar(this.horiz, this.disableHoriz, 'horiz')
  4493. }
  4494. }
  4495. NativeScrollbars.prototype.setScrollTop = function (pos) {
  4496. if (this.vert.scrollTop != pos) {
  4497. this.vert.scrollTop = pos
  4498. }
  4499. if (this.disableVert) {
  4500. this.enableZeroWidthBar(this.vert, this.disableVert, 'vert')
  4501. }
  4502. }
  4503. NativeScrollbars.prototype.zeroWidthHack = function () {
  4504. var w = mac && !mac_geMountainLion ? '12px' : '18px'
  4505. this.horiz.style.height = this.vert.style.width = w
  4506. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = 'none'
  4507. this.disableHoriz = new Delayed()
  4508. this.disableVert = new Delayed()
  4509. }
  4510. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  4511. bar.style.pointerEvents = 'auto'
  4512. function maybeDisable() {
  4513. // To find out whether the scrollbar is still visible, we
  4514. // check whether the element under the pixel in the bottom
  4515. // right corner of the scrollbar box is the scrollbar box
  4516. // itself (when the bar is still visible) or its filler child
  4517. // (when the bar is hidden). If it is still visible, we keep
  4518. // it enabled, if it's hidden, we disable pointer events.
  4519. var box = bar.getBoundingClientRect()
  4520. var elt = type == 'vert' ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1)
  4521. if (elt != bar) {
  4522. bar.style.pointerEvents = 'none'
  4523. } else {
  4524. delay.set(1000, maybeDisable)
  4525. }
  4526. }
  4527. delay.set(1000, maybeDisable)
  4528. }
  4529. NativeScrollbars.prototype.clear = function () {
  4530. var parent = this.horiz.parentNode
  4531. parent.removeChild(this.horiz)
  4532. parent.removeChild(this.vert)
  4533. }
  4534. var NullScrollbars = function () {}
  4535. NullScrollbars.prototype.update = function () {
  4536. return { bottom: 0, right: 0 }
  4537. }
  4538. NullScrollbars.prototype.setScrollLeft = function () {}
  4539. NullScrollbars.prototype.setScrollTop = function () {}
  4540. NullScrollbars.prototype.clear = function () {}
  4541. function updateScrollbars(cm, measure) {
  4542. if (!measure) {
  4543. measure = measureForScrollbars(cm)
  4544. }
  4545. var startWidth = cm.display.barWidth,
  4546. startHeight = cm.display.barHeight
  4547. updateScrollbarsInner(cm, measure)
  4548. for (var i = 0; (i < 4 && startWidth != cm.display.barWidth) || startHeight != cm.display.barHeight; i++) {
  4549. if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {
  4550. updateHeightsInViewport(cm)
  4551. }
  4552. updateScrollbarsInner(cm, measureForScrollbars(cm))
  4553. startWidth = cm.display.barWidth
  4554. startHeight = cm.display.barHeight
  4555. }
  4556. }
  4557. // Re-synchronize the fake scrollbars with the actual size of the
  4558. // content.
  4559. function updateScrollbarsInner(cm, measure) {
  4560. var d = cm.display
  4561. var sizes = d.scrollbars.update(measure)
  4562. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + 'px'
  4563. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + 'px'
  4564. d.heightForcer.style.borderBottom = sizes.bottom + 'px solid transparent'
  4565. if (sizes.right && sizes.bottom) {
  4566. d.scrollbarFiller.style.display = 'block'
  4567. d.scrollbarFiller.style.height = sizes.bottom + 'px'
  4568. d.scrollbarFiller.style.width = sizes.right + 'px'
  4569. } else {
  4570. d.scrollbarFiller.style.display = ''
  4571. }
  4572. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  4573. d.gutterFiller.style.display = 'block'
  4574. d.gutterFiller.style.height = sizes.bottom + 'px'
  4575. d.gutterFiller.style.width = measure.gutterWidth + 'px'
  4576. } else {
  4577. d.gutterFiller.style.display = ''
  4578. }
  4579. }
  4580. var scrollbarModel = { native: NativeScrollbars, null: NullScrollbars }
  4581. function initScrollbars(cm) {
  4582. if (cm.display.scrollbars) {
  4583. cm.display.scrollbars.clear()
  4584. if (cm.display.scrollbars.addClass) {
  4585. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass)
  4586. }
  4587. }
  4588. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](
  4589. function (node) {
  4590. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  4591. // Prevent clicks in the scrollbars from killing focus
  4592. on(node, 'mousedown', function () {
  4593. if (cm.state.focused) {
  4594. setTimeout(function () {
  4595. return cm.display.input.focus()
  4596. }, 0)
  4597. }
  4598. })
  4599. node.setAttribute('cm-not-content', 'true')
  4600. },
  4601. function (pos, axis) {
  4602. if (axis == 'horizontal') {
  4603. setScrollLeft(cm, pos)
  4604. } else {
  4605. updateScrollTop(cm, pos)
  4606. }
  4607. },
  4608. cm
  4609. )
  4610. if (cm.display.scrollbars.addClass) {
  4611. addClass(cm.display.wrapper, cm.display.scrollbars.addClass)
  4612. }
  4613. }
  4614. // Operations are used to wrap a series of changes to the editor
  4615. // state in such a way that each change won't have to update the
  4616. // cursor and display (which would be awkward, slow, and
  4617. // error-prone). Instead, display updates are batched and then all
  4618. // combined and executed at once.
  4619. var nextOpId = 0
  4620. // Start a new operation.
  4621. function startOperation(cm) {
  4622. cm.curOp = {
  4623. cm: cm,
  4624. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  4625. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  4626. forceUpdate: false, // Used to force a redraw
  4627. updateInput: 0, // Whether to reset the input textarea
  4628. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  4629. changeObjs: null, // Accumulated changes, for firing change events
  4630. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  4631. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  4632. selectionChanged: false, // Whether the selection needs to be redrawn
  4633. updateMaxLine: false, // Set when the widest line needs to be determined anew
  4634. scrollLeft: null,
  4635. scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  4636. scrollToPos: null, // Used to scroll to a specific position
  4637. focus: false,
  4638. id: ++nextOpId, // Unique ID
  4639. markArrays: null, // Used by addMarkedSpan
  4640. }
  4641. pushOperation(cm.curOp)
  4642. }
  4643. // Finish an operation, updating the display and signalling delayed events
  4644. function endOperation(cm) {
  4645. var op = cm.curOp
  4646. if (op) {
  4647. finishOperation(op, function (group) {
  4648. for (var i = 0; i < group.ops.length; i++) {
  4649. group.ops[i].cm.curOp = null
  4650. }
  4651. endOperations(group)
  4652. })
  4653. }
  4654. }
  4655. // The DOM updates done when an operation finishes are batched so
  4656. // that the minimum number of relayouts are required.
  4657. function endOperations(group) {
  4658. var ops = group.ops
  4659. for (
  4660. var i = 0;
  4661. i < ops.length;
  4662. i++ // Read DOM
  4663. ) {
  4664. endOperation_R1(ops[i])
  4665. }
  4666. for (
  4667. var i$1 = 0;
  4668. i$1 < ops.length;
  4669. i$1++ // Write DOM (maybe)
  4670. ) {
  4671. endOperation_W1(ops[i$1])
  4672. }
  4673. for (
  4674. var i$2 = 0;
  4675. i$2 < ops.length;
  4676. i$2++ // Read DOM
  4677. ) {
  4678. endOperation_R2(ops[i$2])
  4679. }
  4680. for (
  4681. var i$3 = 0;
  4682. i$3 < ops.length;
  4683. i$3++ // Write DOM (maybe)
  4684. ) {
  4685. endOperation_W2(ops[i$3])
  4686. }
  4687. for (
  4688. var i$4 = 0;
  4689. i$4 < ops.length;
  4690. i$4++ // Read DOM
  4691. ) {
  4692. endOperation_finish(ops[i$4])
  4693. }
  4694. }
  4695. function endOperation_R1(op) {
  4696. var cm = op.cm,
  4697. display = cm.display
  4698. maybeClipScrollbars(cm)
  4699. if (op.updateMaxLine) {
  4700. findMaxLine(cm)
  4701. }
  4702. op.mustUpdate =
  4703. op.viewChanged ||
  4704. op.forceUpdate ||
  4705. op.scrollTop != null ||
  4706. (op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo)) ||
  4707. (display.maxLineChanged && cm.options.lineWrapping)
  4708. op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { top: op.scrollTop, ensure: op.scrollToPos }, op.forceUpdate)
  4709. }
  4710. function endOperation_W1(op) {
  4711. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  4712. }
  4713. function endOperation_R2(op) {
  4714. var cm = op.cm,
  4715. display = cm.display
  4716. if (op.updatedDisplay) {
  4717. updateHeightsInViewport(cm)
  4718. }
  4719. op.barMeasure = measureForScrollbars(cm)
  4720. // If the max line changed since it was last measured, measure it,
  4721. // and ensure the document's width matches it.
  4722. // updateDisplay_W2 will use these properties to do the actual resizing
  4723. if (display.maxLineChanged && !cm.options.lineWrapping) {
  4724. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  4725. cm.display.sizerWidth = op.adjustWidthTo
  4726. op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  4727. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  4728. }
  4729. if (op.updatedDisplay || op.selectionChanged) {
  4730. op.preparedSelection = display.input.prepareSelection()
  4731. }
  4732. }
  4733. function endOperation_W2(op) {
  4734. var cm = op.cm
  4735. if (op.adjustWidthTo != null) {
  4736. cm.display.sizer.style.minWidth = op.adjustWidthTo + 'px'
  4737. if (op.maxScrollLeft < cm.doc.scrollLeft) {
  4738. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true)
  4739. }
  4740. cm.display.maxLineChanged = false
  4741. }
  4742. var takeFocus = op.focus && op.focus == activeElt()
  4743. if (op.preparedSelection) {
  4744. cm.display.input.showSelection(op.preparedSelection, takeFocus)
  4745. }
  4746. if (op.updatedDisplay || op.startHeight != cm.doc.height) {
  4747. updateScrollbars(cm, op.barMeasure)
  4748. }
  4749. if (op.updatedDisplay) {
  4750. setDocumentHeight(cm, op.barMeasure)
  4751. }
  4752. if (op.selectionChanged) {
  4753. restartBlink(cm)
  4754. }
  4755. if (cm.state.focused && op.updateInput) {
  4756. cm.display.input.reset(op.typing)
  4757. }
  4758. if (takeFocus) {
  4759. ensureFocus(op.cm)
  4760. }
  4761. }
  4762. function endOperation_finish(op) {
  4763. var cm = op.cm,
  4764. display = cm.display,
  4765. doc = cm.doc
  4766. if (op.updatedDisplay) {
  4767. postUpdateDisplay(cm, op.update)
  4768. }
  4769. // Abort mouse wheel delta measurement, when scrolling explicitly
  4770. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {
  4771. display.wheelStartX = display.wheelStartY = null
  4772. }
  4773. // Propagate the scroll position to the actual DOM scroller
  4774. if (op.scrollTop != null) {
  4775. setScrollTop(cm, op.scrollTop, op.forceScroll)
  4776. }
  4777. if (op.scrollLeft != null) {
  4778. setScrollLeft(cm, op.scrollLeft, true, true)
  4779. }
  4780. // If we need to scroll a specific position into view, do so.
  4781. if (op.scrollToPos) {
  4782. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  4783. maybeScrollWindow(cm, rect)
  4784. }
  4785. // Fire events for markers that are hidden/unidden by editing or
  4786. // undoing
  4787. var hidden = op.maybeHiddenMarkers,
  4788. unhidden = op.maybeUnhiddenMarkers
  4789. if (hidden) {
  4790. for (var i = 0; i < hidden.length; ++i) {
  4791. if (!hidden[i].lines.length) {
  4792. signal(hidden[i], 'hide')
  4793. }
  4794. }
  4795. }
  4796. if (unhidden) {
  4797. for (var i$1 = 0; i$1 < unhidden.length; ++i$1) {
  4798. if (unhidden[i$1].lines.length) {
  4799. signal(unhidden[i$1], 'unhide')
  4800. }
  4801. }
  4802. }
  4803. if (display.wrapper.offsetHeight) {
  4804. doc.scrollTop = cm.display.scroller.scrollTop
  4805. }
  4806. // Fire change events, and delayed event handlers
  4807. if (op.changeObjs) {
  4808. signal(cm, 'changes', cm, op.changeObjs)
  4809. }
  4810. if (op.update) {
  4811. op.update.finish()
  4812. }
  4813. }
  4814. // Run the given function in an operation
  4815. function runInOp(cm, f) {
  4816. if (cm.curOp) {
  4817. return f()
  4818. }
  4819. startOperation(cm)
  4820. try {
  4821. return f()
  4822. } finally {
  4823. endOperation(cm)
  4824. }
  4825. }
  4826. // Wraps a function in an operation. Returns the wrapped function.
  4827. function operation(cm, f) {
  4828. return function () {
  4829. if (cm.curOp) {
  4830. return f.apply(cm, arguments)
  4831. }
  4832. startOperation(cm)
  4833. try {
  4834. return f.apply(cm, arguments)
  4835. } finally {
  4836. endOperation(cm)
  4837. }
  4838. }
  4839. }
  4840. // Used to add methods to editor and doc instances, wrapping them in
  4841. // operations.
  4842. function methodOp(f) {
  4843. return function () {
  4844. if (this.curOp) {
  4845. return f.apply(this, arguments)
  4846. }
  4847. startOperation(this)
  4848. try {
  4849. return f.apply(this, arguments)
  4850. } finally {
  4851. endOperation(this)
  4852. }
  4853. }
  4854. }
  4855. function docMethodOp(f) {
  4856. return function () {
  4857. var cm = this.cm
  4858. if (!cm || cm.curOp) {
  4859. return f.apply(this, arguments)
  4860. }
  4861. startOperation(cm)
  4862. try {
  4863. return f.apply(this, arguments)
  4864. } finally {
  4865. endOperation(cm)
  4866. }
  4867. }
  4868. }
  4869. // HIGHLIGHT WORKER
  4870. function startWorker(cm, time) {
  4871. if (cm.doc.highlightFrontier < cm.display.viewTo) {
  4872. cm.state.highlight.set(time, bind(highlightWorker, cm))
  4873. }
  4874. }
  4875. function highlightWorker(cm) {
  4876. var doc = cm.doc
  4877. if (doc.highlightFrontier >= cm.display.viewTo) {
  4878. return
  4879. }
  4880. var end = +new Date() + cm.options.workTime
  4881. var context = getContextBefore(cm, doc.highlightFrontier)
  4882. var changedLines = []
  4883. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  4884. if (context.line >= cm.display.viewFrom) {
  4885. // Visible
  4886. var oldStyles = line.styles
  4887. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null
  4888. var highlighted = highlightLine(cm, line, context, true)
  4889. if (resetState) {
  4890. context.state = resetState
  4891. }
  4892. line.styles = highlighted.styles
  4893. var oldCls = line.styleClasses,
  4894. newCls = highlighted.classes
  4895. if (newCls) {
  4896. line.styleClasses = newCls
  4897. } else if (oldCls) {
  4898. line.styleClasses = null
  4899. }
  4900. var ischange =
  4901. !oldStyles || oldStyles.length != line.styles.length || (oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass))
  4902. for (var i = 0; !ischange && i < oldStyles.length; ++i) {
  4903. ischange = oldStyles[i] != line.styles[i]
  4904. }
  4905. if (ischange) {
  4906. changedLines.push(context.line)
  4907. }
  4908. line.stateAfter = context.save()
  4909. context.nextLine()
  4910. } else {
  4911. if (line.text.length <= cm.options.maxHighlightLength) {
  4912. processLine(cm, line.text, context)
  4913. }
  4914. line.stateAfter = context.line % 5 == 0 ? context.save() : null
  4915. context.nextLine()
  4916. }
  4917. if (+new Date() > end) {
  4918. startWorker(cm, cm.options.workDelay)
  4919. return true
  4920. }
  4921. })
  4922. doc.highlightFrontier = context.line
  4923. doc.modeFrontier = Math.max(doc.modeFrontier, context.line)
  4924. if (changedLines.length) {
  4925. runInOp(cm, function () {
  4926. for (var i = 0; i < changedLines.length; i++) {
  4927. regLineChange(cm, changedLines[i], 'text')
  4928. }
  4929. })
  4930. }
  4931. }
  4932. // DISPLAY DRAWING
  4933. var DisplayUpdate = function (cm, viewport, force) {
  4934. var display = cm.display
  4935. this.viewport = viewport
  4936. // Store some values that we'll need later (but don't want to force a relayout for)
  4937. this.visible = visibleLines(display, cm.doc, viewport)
  4938. this.editorIsHidden = !display.wrapper.offsetWidth
  4939. this.wrapperHeight = display.wrapper.clientHeight
  4940. this.wrapperWidth = display.wrapper.clientWidth
  4941. this.oldDisplayWidth = displayWidth(cm)
  4942. this.force = force
  4943. this.dims = getDimensions(cm)
  4944. this.events = []
  4945. }
  4946. DisplayUpdate.prototype.signal = function (emitter, type) {
  4947. if (hasHandler(emitter, type)) {
  4948. this.events.push(arguments)
  4949. }
  4950. }
  4951. DisplayUpdate.prototype.finish = function () {
  4952. for (var i = 0; i < this.events.length; i++) {
  4953. signal.apply(null, this.events[i])
  4954. }
  4955. }
  4956. function maybeClipScrollbars(cm) {
  4957. var display = cm.display
  4958. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  4959. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  4960. display.heightForcer.style.height = scrollGap(cm) + 'px'
  4961. display.sizer.style.marginBottom = -display.nativeBarWidth + 'px'
  4962. display.sizer.style.borderRightWidth = scrollGap(cm) + 'px'
  4963. display.scrollbarsClipped = true
  4964. }
  4965. }
  4966. function selectionSnapshot(cm) {
  4967. if (cm.hasFocus()) {
  4968. return null
  4969. }
  4970. var active = activeElt()
  4971. if (!active || !contains(cm.display.lineDiv, active)) {
  4972. return null
  4973. }
  4974. var result = { activeElt: active }
  4975. if (window.getSelection) {
  4976. var sel = window.getSelection()
  4977. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  4978. result.anchorNode = sel.anchorNode
  4979. result.anchorOffset = sel.anchorOffset
  4980. result.focusNode = sel.focusNode
  4981. result.focusOffset = sel.focusOffset
  4982. }
  4983. }
  4984. return result
  4985. }
  4986. function restoreSelection(snapshot) {
  4987. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) {
  4988. return
  4989. }
  4990. snapshot.activeElt.focus()
  4991. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  4992. var sel = window.getSelection(),
  4993. range = document.createRange()
  4994. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset)
  4995. range.collapse(false)
  4996. sel.removeAllRanges()
  4997. sel.addRange(range)
  4998. sel.extend(snapshot.focusNode, snapshot.focusOffset)
  4999. }
  5000. }
  5001. // Does the actual updating of the line display. Bails out
  5002. // (returning false) when there is nothing to be done and forced is
  5003. // false.
  5004. function updateDisplayIfNeeded(cm, update) {
  5005. var display = cm.display,
  5006. doc = cm.doc
  5007. if (update.editorIsHidden) {
  5008. resetView(cm)
  5009. return false
  5010. }
  5011. // Bail out if the visible area is already rendered and nothing changed.
  5012. if (
  5013. !update.force &&
  5014. update.visible.from >= display.viewFrom &&
  5015. update.visible.to <= display.viewTo &&
  5016. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  5017. display.renderedView == display.view &&
  5018. countDirtyView(cm) == 0
  5019. ) {
  5020. return false
  5021. }
  5022. if (maybeUpdateLineNumberWidth(cm)) {
  5023. resetView(cm)
  5024. update.dims = getDimensions(cm)
  5025. }
  5026. // Compute a suitable new viewport (from & to)
  5027. var end = doc.first + doc.size
  5028. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  5029. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  5030. if (display.viewFrom < from && from - display.viewFrom < 20) {
  5031. from = Math.max(doc.first, display.viewFrom)
  5032. }
  5033. if (display.viewTo > to && display.viewTo - to < 20) {
  5034. to = Math.min(end, display.viewTo)
  5035. }
  5036. if (sawCollapsedSpans) {
  5037. from = visualLineNo(cm.doc, from)
  5038. to = visualLineEndNo(cm.doc, to)
  5039. }
  5040. var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  5041. adjustView(cm, from, to)
  5042. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  5043. // Position the mover div to align with the current scroll position
  5044. cm.display.mover.style.top = display.viewOffset + 'px'
  5045. var toUpdate = countDirtyView(cm)
  5046. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {
  5047. return false
  5048. }
  5049. // For big changes, we hide the enclosing element during the
  5050. // update, since that speeds up the operations on most browsers.
  5051. var selSnapshot = selectionSnapshot(cm)
  5052. if (toUpdate > 4) {
  5053. display.lineDiv.style.display = 'none'
  5054. }
  5055. patchDisplay(cm, display.updateLineNumbers, update.dims)
  5056. if (toUpdate > 4) {
  5057. display.lineDiv.style.display = ''
  5058. }
  5059. display.renderedView = display.view
  5060. // There might have been a widget with a focused element that got
  5061. // hidden or updated, if so re-focus it.
  5062. restoreSelection(selSnapshot)
  5063. // Prevent selection and cursors from interfering with the scroll
  5064. // width and height.
  5065. removeChildren(display.cursorDiv)
  5066. removeChildren(display.selectionDiv)
  5067. display.gutters.style.height = display.sizer.style.minHeight = 0
  5068. if (different) {
  5069. display.lastWrapHeight = update.wrapperHeight
  5070. display.lastWrapWidth = update.wrapperWidth
  5071. startWorker(cm, 400)
  5072. }
  5073. display.updateLineNumbers = null
  5074. return true
  5075. }
  5076. function postUpdateDisplay(cm, update) {
  5077. var viewport = update.viewport
  5078. for (var first = true; ; first = false) {
  5079. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  5080. // Clip forced viewport to actual scrollable area.
  5081. if (viewport && viewport.top != null) {
  5082. viewport = { top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) }
  5083. }
  5084. // Updated line heights might result in the drawn area not
  5085. // actually covering the viewport. Keep looping until it does.
  5086. update.visible = visibleLines(cm.display, cm.doc, viewport)
  5087. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) {
  5088. break
  5089. }
  5090. } else if (first) {
  5091. update.visible = visibleLines(cm.display, cm.doc, viewport)
  5092. }
  5093. if (!updateDisplayIfNeeded(cm, update)) {
  5094. break
  5095. }
  5096. updateHeightsInViewport(cm)
  5097. var barMeasure = measureForScrollbars(cm)
  5098. updateSelection(cm)
  5099. updateScrollbars(cm, barMeasure)
  5100. setDocumentHeight(cm, barMeasure)
  5101. update.force = false
  5102. }
  5103. update.signal(cm, 'update', cm)
  5104. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  5105. update.signal(cm, 'viewportChange', cm, cm.display.viewFrom, cm.display.viewTo)
  5106. cm.display.reportedViewFrom = cm.display.viewFrom
  5107. cm.display.reportedViewTo = cm.display.viewTo
  5108. }
  5109. }
  5110. function updateDisplaySimple(cm, viewport) {
  5111. var update = new DisplayUpdate(cm, viewport)
  5112. if (updateDisplayIfNeeded(cm, update)) {
  5113. updateHeightsInViewport(cm)
  5114. postUpdateDisplay(cm, update)
  5115. var barMeasure = measureForScrollbars(cm)
  5116. updateSelection(cm)
  5117. updateScrollbars(cm, barMeasure)
  5118. setDocumentHeight(cm, barMeasure)
  5119. update.finish()
  5120. }
  5121. }
  5122. // Sync the actual display DOM structure with display.view, removing
  5123. // nodes for lines that are no longer in view, and creating the ones
  5124. // that are not there yet, and updating the ones that are out of
  5125. // date.
  5126. function patchDisplay(cm, updateNumbersFrom, dims) {
  5127. var display = cm.display,
  5128. lineNumbers = cm.options.lineNumbers
  5129. var container = display.lineDiv,
  5130. cur = container.firstChild
  5131. function rm(node) {
  5132. var next = node.nextSibling
  5133. // Works around a throw-scroll bug in OS X Webkit
  5134. if (webkit && mac && cm.display.currentWheelTarget == node) {
  5135. node.style.display = 'none'
  5136. } else {
  5137. node.parentNode.removeChild(node)
  5138. }
  5139. return next
  5140. }
  5141. var view = display.view,
  5142. lineN = display.viewFrom
  5143. // Loop over the elements in the view, syncing cur (the DOM nodes
  5144. // in display.lineDiv) with the view as we go.
  5145. for (var i = 0; i < view.length; i++) {
  5146. var lineView = view[i]
  5147. if (lineView.hidden);
  5148. else if (!lineView.node || lineView.node.parentNode != container) {
  5149. // Not drawn yet
  5150. var node = buildLineElement(cm, lineView, lineN, dims)
  5151. container.insertBefore(node, cur)
  5152. } else {
  5153. // Already drawn
  5154. while (cur != lineView.node) {
  5155. cur = rm(cur)
  5156. }
  5157. var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber
  5158. if (lineView.changes) {
  5159. if (indexOf(lineView.changes, 'gutter') > -1) {
  5160. updateNumber = false
  5161. }
  5162. updateLineForChanges(cm, lineView, lineN, dims)
  5163. }
  5164. if (updateNumber) {
  5165. removeChildren(lineView.lineNumber)
  5166. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  5167. }
  5168. cur = lineView.node.nextSibling
  5169. }
  5170. lineN += lineView.size
  5171. }
  5172. while (cur) {
  5173. cur = rm(cur)
  5174. }
  5175. }
  5176. function updateGutterSpace(display) {
  5177. var width = display.gutters.offsetWidth
  5178. display.sizer.style.marginLeft = width + 'px'
  5179. // Send an event to consumers responding to changes in gutter width.
  5180. signalLater(display, 'gutterChanged', display)
  5181. }
  5182. function setDocumentHeight(cm, measure) {
  5183. cm.display.sizer.style.minHeight = measure.docHeight + 'px'
  5184. cm.display.heightForcer.style.top = measure.docHeight + 'px'
  5185. cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + 'px'
  5186. }
  5187. // Re-align line numbers and gutter marks to compensate for
  5188. // horizontal scrolling.
  5189. function alignHorizontally(cm) {
  5190. var display = cm.display,
  5191. view = display.view
  5192. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) {
  5193. return
  5194. }
  5195. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  5196. var gutterW = display.gutters.offsetWidth,
  5197. left = comp + 'px'
  5198. for (var i = 0; i < view.length; i++) {
  5199. if (!view[i].hidden) {
  5200. if (cm.options.fixedGutter) {
  5201. if (view[i].gutter) {
  5202. view[i].gutter.style.left = left
  5203. }
  5204. if (view[i].gutterBackground) {
  5205. view[i].gutterBackground.style.left = left
  5206. }
  5207. }
  5208. var align = view[i].alignable
  5209. if (align) {
  5210. for (var j = 0; j < align.length; j++) {
  5211. align[j].style.left = left
  5212. }
  5213. }
  5214. }
  5215. }
  5216. if (cm.options.fixedGutter) {
  5217. display.gutters.style.left = comp + gutterW + 'px'
  5218. }
  5219. }
  5220. // Used to ensure that the line number gutter is still the right
  5221. // size for the current document size. Returns true when an update
  5222. // is needed.
  5223. function maybeUpdateLineNumberWidth(cm) {
  5224. if (!cm.options.lineNumbers) {
  5225. return false
  5226. }
  5227. var doc = cm.doc,
  5228. last = lineNumberFor(cm.options, doc.first + doc.size - 1),
  5229. display = cm.display
  5230. if (last.length != display.lineNumChars) {
  5231. var test = display.measure.appendChild(elt('div', [elt('div', last)], 'CodeMirror-linenumber CodeMirror-gutter-elt'))
  5232. var innerW = test.firstChild.offsetWidth,
  5233. padding = test.offsetWidth - innerW
  5234. display.lineGutter.style.width = ''
  5235. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  5236. display.lineNumWidth = display.lineNumInnerWidth + padding
  5237. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  5238. display.lineGutter.style.width = display.lineNumWidth + 'px'
  5239. updateGutterSpace(cm.display)
  5240. return true
  5241. }
  5242. return false
  5243. }
  5244. function getGutters(gutters, lineNumbers) {
  5245. var result = [],
  5246. sawLineNumbers = false
  5247. for (var i = 0; i < gutters.length; i++) {
  5248. var name = gutters[i],
  5249. style = null
  5250. if (typeof name != 'string') {
  5251. style = name.style
  5252. name = name.className
  5253. }
  5254. if (name == 'CodeMirror-linenumbers') {
  5255. if (!lineNumbers) {
  5256. continue
  5257. } else {
  5258. sawLineNumbers = true
  5259. }
  5260. }
  5261. result.push({ className: name, style: style })
  5262. }
  5263. if (lineNumbers && !sawLineNumbers) {
  5264. result.push({ className: 'CodeMirror-linenumbers', style: null })
  5265. }
  5266. return result
  5267. }
  5268. // Rebuild the gutter elements, ensure the margin to the left of the
  5269. // code matches their width.
  5270. function renderGutters(display) {
  5271. var gutters = display.gutters,
  5272. specs = display.gutterSpecs
  5273. removeChildren(gutters)
  5274. display.lineGutter = null
  5275. for (var i = 0; i < specs.length; ++i) {
  5276. var ref = specs[i]
  5277. var className = ref.className
  5278. var style = ref.style
  5279. var gElt = gutters.appendChild(elt('div', null, 'CodeMirror-gutter ' + className))
  5280. if (style) {
  5281. gElt.style.cssText = style
  5282. }
  5283. if (className == 'CodeMirror-linenumbers') {
  5284. display.lineGutter = gElt
  5285. gElt.style.width = (display.lineNumWidth || 1) + 'px'
  5286. }
  5287. }
  5288. gutters.style.display = specs.length ? '' : 'none'
  5289. updateGutterSpace(display)
  5290. }
  5291. function updateGutters(cm) {
  5292. renderGutters(cm.display)
  5293. regChange(cm)
  5294. alignHorizontally(cm)
  5295. }
  5296. // The display handles the DOM integration, both for input reading
  5297. // and content drawing. It holds references to DOM nodes and
  5298. // display-related state.
  5299. function Display(place, doc, input, options) {
  5300. var d = this
  5301. this.input = input
  5302. // Covers bottom-right square when both scrollbars are present.
  5303. d.scrollbarFiller = elt('div', null, 'CodeMirror-scrollbar-filler')
  5304. d.scrollbarFiller.setAttribute('cm-not-content', 'true')
  5305. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  5306. // and h scrollbar is present.
  5307. d.gutterFiller = elt('div', null, 'CodeMirror-gutter-filler')
  5308. d.gutterFiller.setAttribute('cm-not-content', 'true')
  5309. // Will contain the actual code, positioned to cover the viewport.
  5310. d.lineDiv = eltP('div', null, 'CodeMirror-code')
  5311. // Elements are added to these to represent selection and cursors.
  5312. d.selectionDiv = elt('div', null, null, 'position: relative; z-index: 1')
  5313. d.cursorDiv = elt('div', null, 'CodeMirror-cursors')
  5314. // A visibility: hidden element used to find the size of things.
  5315. d.measure = elt('div', null, 'CodeMirror-measure')
  5316. // When lines outside of the viewport are measured, they are drawn in this.
  5317. d.lineMeasure = elt('div', null, 'CodeMirror-measure')
  5318. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  5319. d.lineSpace = eltP('div', [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, 'position: relative; outline: none')
  5320. var lines = eltP('div', [d.lineSpace], 'CodeMirror-lines')
  5321. // Moved around its parent to cover visible view.
  5322. d.mover = elt('div', [lines], null, 'position: relative')
  5323. // Set to the height of the document, allowing scrolling.
  5324. d.sizer = elt('div', [d.mover], 'CodeMirror-sizer')
  5325. d.sizerWidth = null
  5326. // Behavior of elts with overflow: auto and padding is
  5327. // inconsistent across browsers. This is used to ensure the
  5328. // scrollable area is big enough.
  5329. d.heightForcer = elt('div', null, null, 'position: absolute; height: ' + scrollerGap + 'px; width: 1px;')
  5330. // Will contain the gutters, if any.
  5331. d.gutters = elt('div', null, 'CodeMirror-gutters')
  5332. d.lineGutter = null
  5333. // Actual scrollable element.
  5334. d.scroller = elt('div', [d.sizer, d.heightForcer, d.gutters], 'CodeMirror-scroll')
  5335. d.scroller.setAttribute('tabIndex', '-1')
  5336. // The element in which the editor lives.
  5337. d.wrapper = elt('div', [d.scrollbarFiller, d.gutterFiller, d.scroller], 'CodeMirror')
  5338. // This attribute is respected by automatic translation systems such as Google Translate,
  5339. // and may also be respected by tools used by human translators.
  5340. d.wrapper.setAttribute('translate', 'no')
  5341. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  5342. if (ie && ie_version < 8) {
  5343. d.gutters.style.zIndex = -1
  5344. d.scroller.style.paddingRight = 0
  5345. }
  5346. if (!webkit && !(gecko && mobile)) {
  5347. d.scroller.draggable = true
  5348. }
  5349. if (place) {
  5350. if (place.appendChild) {
  5351. place.appendChild(d.wrapper)
  5352. } else {
  5353. place(d.wrapper)
  5354. }
  5355. }
  5356. // Current rendered range (may be bigger than the view window).
  5357. d.viewFrom = d.viewTo = doc.first
  5358. d.reportedViewFrom = d.reportedViewTo = doc.first
  5359. // Information about the rendered lines.
  5360. d.view = []
  5361. d.renderedView = null
  5362. // Holds info about a single rendered line when it was rendered
  5363. // for measurement, while not in view.
  5364. d.externalMeasured = null
  5365. // Empty space (in pixels) above the view
  5366. d.viewOffset = 0
  5367. d.lastWrapHeight = d.lastWrapWidth = 0
  5368. d.updateLineNumbers = null
  5369. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  5370. d.scrollbarsClipped = false
  5371. // Used to only resize the line number gutter when necessary (when
  5372. // the amount of lines crosses a boundary that makes its width change)
  5373. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  5374. // Set to true when a non-horizontal-scrolling line widget is
  5375. // added. As an optimization, line widget aligning is skipped when
  5376. // this is false.
  5377. d.alignWidgets = false
  5378. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5379. // Tracks the maximum line length so that the horizontal scrollbar
  5380. // can be kept static when scrolling.
  5381. d.maxLine = null
  5382. d.maxLineLength = 0
  5383. d.maxLineChanged = false
  5384. // Used for measuring wheel scrolling granularity
  5385. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  5386. // True when shift is held down.
  5387. d.shift = false
  5388. // Used to track whether anything happened since the context menu
  5389. // was opened.
  5390. d.selForContextMenu = null
  5391. d.activeTouch = null
  5392. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers)
  5393. renderGutters(d)
  5394. input.init(d)
  5395. }
  5396. // Since the delta values reported on mouse wheel events are
  5397. // unstandardized between browsers and even browser versions, and
  5398. // generally horribly unpredictable, this code starts by measuring
  5399. // the scroll effect that the first few mouse wheel events have,
  5400. // and, from that, detects the way it can convert deltas to pixel
  5401. // offsets afterwards.
  5402. //
  5403. // The reason we want to know the amount a wheel event will scroll
  5404. // is that it gives us a chance to update the display before the
  5405. // actual scrolling happens, reducing flickering.
  5406. var wheelSamples = 0,
  5407. wheelPixelsPerUnit = null
  5408. // Fill in a browser-detected starting value on browsers where we
  5409. // know one. These don't have to be accurate -- the result of them
  5410. // being wrong would just be a slight flicker on the first wheel
  5411. // scroll (if it is large enough).
  5412. if (ie) {
  5413. wheelPixelsPerUnit = -0.53
  5414. } else if (gecko) {
  5415. wheelPixelsPerUnit = 15
  5416. } else if (chrome) {
  5417. wheelPixelsPerUnit = -0.7
  5418. } else if (safari) {
  5419. wheelPixelsPerUnit = -1 / 3
  5420. }
  5421. function wheelEventDelta(e) {
  5422. var dx = e.wheelDeltaX,
  5423. dy = e.wheelDeltaY
  5424. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) {
  5425. dx = e.detail
  5426. }
  5427. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) {
  5428. dy = e.detail
  5429. } else if (dy == null) {
  5430. dy = e.wheelDelta
  5431. }
  5432. return { x: dx, y: dy }
  5433. }
  5434. function wheelEventPixels(e) {
  5435. var delta = wheelEventDelta(e)
  5436. delta.x *= wheelPixelsPerUnit
  5437. delta.y *= wheelPixelsPerUnit
  5438. return delta
  5439. }
  5440. function onScrollWheel(cm, e) {
  5441. var delta = wheelEventDelta(e),
  5442. dx = delta.x,
  5443. dy = delta.y
  5444. var pixelsPerUnit = wheelPixelsPerUnit
  5445. if (e.deltaMode === 0) {
  5446. dx = e.deltaX
  5447. dy = e.deltaY
  5448. pixelsPerUnit = 1
  5449. }
  5450. var display = cm.display,
  5451. scroll = display.scroller
  5452. // Quit if there's nothing to scroll here
  5453. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  5454. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  5455. if (!((dx && canScrollX) || (dy && canScrollY))) {
  5456. return
  5457. }
  5458. // Webkit browsers on OS X abort momentum scrolls when the target
  5459. // of the scroll event is removed from the scrollable element.
  5460. // This hack (see related code in patchDisplay) makes sure the
  5461. // element is kept around.
  5462. if (dy && mac && webkit) {
  5463. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  5464. for (var i = 0; i < view.length; i++) {
  5465. if (view[i].node == cur) {
  5466. cm.display.currentWheelTarget = cur
  5467. break outer
  5468. }
  5469. }
  5470. }
  5471. }
  5472. // On some browsers, horizontal scrolling will cause redraws to
  5473. // happen before the gutter has been realigned, causing it to
  5474. // wriggle around in a most unseemly way. When we have an
  5475. // estimated pixels/delta value, we just handle horizontal
  5476. // scrolling entirely here. It'll be slightly off from native, but
  5477. // better than glitching out.
  5478. if (dx && !gecko && !presto && pixelsPerUnit != null) {
  5479. if (dy && canScrollY) {
  5480. updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit))
  5481. }
  5482. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit))
  5483. // Only prevent default scrolling if vertical scrolling is
  5484. // actually possible. Otherwise, it causes vertical scroll
  5485. // jitter on OSX trackpads when deltaX is small and deltaY
  5486. // is large (issue #3579)
  5487. if (!dy || (dy && canScrollY)) {
  5488. e_preventDefault(e)
  5489. }
  5490. display.wheelStartX = null // Abort measurement, if in progress
  5491. return
  5492. }
  5493. // 'Project' the visible viewport to cover the area that is being
  5494. // scrolled into view (if we know enough to estimate it).
  5495. if (dy && pixelsPerUnit != null) {
  5496. var pixels = dy * pixelsPerUnit
  5497. var top = cm.doc.scrollTop,
  5498. bot = top + display.wrapper.clientHeight
  5499. if (pixels < 0) {
  5500. top = Math.max(0, top + pixels - 50)
  5501. } else {
  5502. bot = Math.min(cm.doc.height, bot + pixels + 50)
  5503. }
  5504. updateDisplaySimple(cm, { top: top, bottom: bot })
  5505. }
  5506. if (wheelSamples < 20 && e.deltaMode !== 0) {
  5507. if (display.wheelStartX == null) {
  5508. display.wheelStartX = scroll.scrollLeft
  5509. display.wheelStartY = scroll.scrollTop
  5510. display.wheelDX = dx
  5511. display.wheelDY = dy
  5512. setTimeout(function () {
  5513. if (display.wheelStartX == null) {
  5514. return
  5515. }
  5516. var movedX = scroll.scrollLeft - display.wheelStartX
  5517. var movedY = scroll.scrollTop - display.wheelStartY
  5518. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX)
  5519. display.wheelStartX = display.wheelStartY = null
  5520. if (!sample) {
  5521. return
  5522. }
  5523. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  5524. ++wheelSamples
  5525. }, 200)
  5526. } else {
  5527. display.wheelDX += dx
  5528. display.wheelDY += dy
  5529. }
  5530. }
  5531. }
  5532. // Selection objects are immutable. A new one is created every time
  5533. // the selection changes. A selection is one or more non-overlapping
  5534. // (and non-touching) ranges, sorted, and an integer that indicates
  5535. // which one is the primary selection (the one that's scrolled into
  5536. // view, that getCursor returns, etc).
  5537. var Selection = function (ranges, primIndex) {
  5538. this.ranges = ranges
  5539. this.primIndex = primIndex
  5540. }
  5541. Selection.prototype.primary = function () {
  5542. return this.ranges[this.primIndex]
  5543. }
  5544. Selection.prototype.equals = function (other) {
  5545. if (other == this) {
  5546. return true
  5547. }
  5548. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) {
  5549. return false
  5550. }
  5551. for (var i = 0; i < this.ranges.length; i++) {
  5552. var here = this.ranges[i],
  5553. there = other.ranges[i]
  5554. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) {
  5555. return false
  5556. }
  5557. }
  5558. return true
  5559. }
  5560. Selection.prototype.deepCopy = function () {
  5561. var out = []
  5562. for (var i = 0; i < this.ranges.length; i++) {
  5563. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head))
  5564. }
  5565. return new Selection(out, this.primIndex)
  5566. }
  5567. Selection.prototype.somethingSelected = function () {
  5568. for (var i = 0; i < this.ranges.length; i++) {
  5569. if (!this.ranges[i].empty()) {
  5570. return true
  5571. }
  5572. }
  5573. return false
  5574. }
  5575. Selection.prototype.contains = function (pos, end) {
  5576. if (!end) {
  5577. end = pos
  5578. }
  5579. for (var i = 0; i < this.ranges.length; i++) {
  5580. var range = this.ranges[i]
  5581. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) {
  5582. return i
  5583. }
  5584. }
  5585. return -1
  5586. }
  5587. var Range = function (anchor, head) {
  5588. this.anchor = anchor
  5589. this.head = head
  5590. }
  5591. Range.prototype.from = function () {
  5592. return minPos(this.anchor, this.head)
  5593. }
  5594. Range.prototype.to = function () {
  5595. return maxPos(this.anchor, this.head)
  5596. }
  5597. Range.prototype.empty = function () {
  5598. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch
  5599. }
  5600. // Take an unsorted, potentially overlapping set of ranges, and
  5601. // build a selection out of it. 'Consumes' ranges array (modifying
  5602. // it).
  5603. function normalizeSelection(cm, ranges, primIndex) {
  5604. var mayTouch = cm && cm.options.selectionsMayTouch
  5605. var prim = ranges[primIndex]
  5606. ranges.sort(function (a, b) {
  5607. return cmp(a.from(), b.from())
  5608. })
  5609. primIndex = indexOf(ranges, prim)
  5610. for (var i = 1; i < ranges.length; i++) {
  5611. var cur = ranges[i],
  5612. prev = ranges[i - 1]
  5613. var diff = cmp(prev.to(), cur.from())
  5614. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  5615. var from = minPos(prev.from(), cur.from()),
  5616. to = maxPos(prev.to(), cur.to())
  5617. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  5618. if (i <= primIndex) {
  5619. --primIndex
  5620. }
  5621. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  5622. }
  5623. }
  5624. return new Selection(ranges, primIndex)
  5625. }
  5626. function simpleSelection(anchor, head) {
  5627. return new Selection([new Range(anchor, head || anchor)], 0)
  5628. }
  5629. // Compute the position of the end of a change (its 'to' property
  5630. // refers to the pre-change end).
  5631. function changeEnd(change) {
  5632. if (!change.text) {
  5633. return change.to
  5634. }
  5635. return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  5636. }
  5637. // Adjust a position to refer to the post-change position of the
  5638. // same text, or the end of the change if the change covers it.
  5639. function adjustForChange(pos, change) {
  5640. if (cmp(pos, change.from) < 0) {
  5641. return pos
  5642. }
  5643. if (cmp(pos, change.to) <= 0) {
  5644. return changeEnd(change)
  5645. }
  5646. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1,
  5647. ch = pos.ch
  5648. if (pos.line == change.to.line) {
  5649. ch += changeEnd(change).ch - change.to.ch
  5650. }
  5651. return Pos(line, ch)
  5652. }
  5653. function computeSelAfterChange(doc, change) {
  5654. var out = []
  5655. for (var i = 0; i < doc.sel.ranges.length; i++) {
  5656. var range = doc.sel.ranges[i]
  5657. out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change)))
  5658. }
  5659. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  5660. }
  5661. function offsetPos(pos, old, nw) {
  5662. if (pos.line == old.line) {
  5663. return Pos(nw.line, pos.ch - old.ch + nw.ch)
  5664. } else {
  5665. return Pos(nw.line + (pos.line - old.line), pos.ch)
  5666. }
  5667. }
  5668. // Used by replaceSelections to allow moving the selection to the
  5669. // start or around the replaced test. Hint may be "start" or "around".
  5670. function computeReplacedSel(doc, changes, hint) {
  5671. var out = []
  5672. var oldPrev = Pos(doc.first, 0),
  5673. newPrev = oldPrev
  5674. for (var i = 0; i < changes.length; i++) {
  5675. var change = changes[i]
  5676. var from = offsetPos(change.from, oldPrev, newPrev)
  5677. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  5678. oldPrev = change.to
  5679. newPrev = to
  5680. if (hint == 'around') {
  5681. var range = doc.sel.ranges[i],
  5682. inv = cmp(range.head, range.anchor) < 0
  5683. out[i] = new Range(inv ? to : from, inv ? from : to)
  5684. } else {
  5685. out[i] = new Range(from, from)
  5686. }
  5687. }
  5688. return new Selection(out, doc.sel.primIndex)
  5689. }
  5690. // Used to get the editor into a consistent state again when options change.
  5691. function loadMode(cm) {
  5692. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  5693. resetModeState(cm)
  5694. }
  5695. function resetModeState(cm) {
  5696. cm.doc.iter(function (line) {
  5697. if (line.stateAfter) {
  5698. line.stateAfter = null
  5699. }
  5700. if (line.styles) {
  5701. line.styles = null
  5702. }
  5703. })
  5704. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first
  5705. startWorker(cm, 100)
  5706. cm.state.modeGen++
  5707. if (cm.curOp) {
  5708. regChange(cm)
  5709. }
  5710. }
  5711. // DOCUMENT DATA STRUCTURE
  5712. // By default, updates that start and end at the beginning of a line
  5713. // are treated specially, in order to make the association of line
  5714. // widgets and marker elements with the text behave more intuitive.
  5715. function isWholeLineUpdate(doc, change) {
  5716. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == '' && (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  5717. }
  5718. // Perform a change on the document data structure.
  5719. function updateDoc(doc, change, markedSpans, estimateHeight) {
  5720. function spansFor(n) {
  5721. return markedSpans ? markedSpans[n] : null
  5722. }
  5723. function update(line, text, spans) {
  5724. updateLine(line, text, spans, estimateHeight)
  5725. signalLater(line, 'change', line, change)
  5726. }
  5727. function linesFor(start, end) {
  5728. var result = []
  5729. for (var i = start; i < end; ++i) {
  5730. result.push(new Line(text[i], spansFor(i), estimateHeight))
  5731. }
  5732. return result
  5733. }
  5734. var from = change.from,
  5735. to = change.to,
  5736. text = change.text
  5737. var firstLine = getLine(doc, from.line),
  5738. lastLine = getLine(doc, to.line)
  5739. var lastText = lst(text),
  5740. lastSpans = spansFor(text.length - 1),
  5741. nlines = to.line - from.line
  5742. // Adjust the line structure
  5743. if (change.full) {
  5744. doc.insert(0, linesFor(0, text.length))
  5745. doc.remove(text.length, doc.size - text.length)
  5746. } else if (isWholeLineUpdate(doc, change)) {
  5747. // This is a whole-line replace. Treated specially to make
  5748. // sure line objects move the way they are supposed to.
  5749. var added = linesFor(0, text.length - 1)
  5750. update(lastLine, lastLine.text, lastSpans)
  5751. if (nlines) {
  5752. doc.remove(from.line, nlines)
  5753. }
  5754. if (added.length) {
  5755. doc.insert(from.line, added)
  5756. }
  5757. } else if (firstLine == lastLine) {
  5758. if (text.length == 1) {
  5759. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  5760. } else {
  5761. var added$1 = linesFor(1, text.length - 1)
  5762. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
  5763. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  5764. doc.insert(from.line + 1, added$1)
  5765. }
  5766. } else if (text.length == 1) {
  5767. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  5768. doc.remove(from.line + 1, nlines)
  5769. } else {
  5770. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  5771. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  5772. var added$2 = linesFor(1, text.length - 1)
  5773. if (nlines > 1) {
  5774. doc.remove(from.line + 1, nlines - 1)
  5775. }
  5776. doc.insert(from.line + 1, added$2)
  5777. }
  5778. signalLater(doc, 'change', doc, change)
  5779. }
  5780. // Call f for all linked documents.
  5781. function linkedDocs(doc, f, sharedHistOnly) {
  5782. function propagate(doc, skip, sharedHist) {
  5783. if (doc.linked) {
  5784. for (var i = 0; i < doc.linked.length; ++i) {
  5785. var rel = doc.linked[i]
  5786. if (rel.doc == skip) {
  5787. continue
  5788. }
  5789. var shared = sharedHist && rel.sharedHist
  5790. if (sharedHistOnly && !shared) {
  5791. continue
  5792. }
  5793. f(rel.doc, shared)
  5794. propagate(rel.doc, doc, shared)
  5795. }
  5796. }
  5797. }
  5798. propagate(doc, null, true)
  5799. }
  5800. // Attach a document to an editor.
  5801. function attachDoc(cm, doc) {
  5802. if (doc.cm) {
  5803. throw new Error('This document is already in use.')
  5804. }
  5805. cm.doc = doc
  5806. doc.cm = cm
  5807. estimateLineHeights(cm)
  5808. loadMode(cm)
  5809. setDirectionClass(cm)
  5810. cm.options.direction = doc.direction
  5811. if (!cm.options.lineWrapping) {
  5812. findMaxLine(cm)
  5813. }
  5814. cm.options.mode = doc.modeOption
  5815. regChange(cm)
  5816. }
  5817. function setDirectionClass(cm) {
  5818. ;(cm.doc.direction == 'rtl' ? addClass : rmClass)(cm.display.lineDiv, 'CodeMirror-rtl')
  5819. }
  5820. function directionChanged(cm) {
  5821. runInOp(cm, function () {
  5822. setDirectionClass(cm)
  5823. regChange(cm)
  5824. })
  5825. }
  5826. function History(prev) {
  5827. // Arrays of change events and selections. Doing something adds an
  5828. // event to done and clears undo. Undoing moves events from done
  5829. // to undone, redoing moves them in the other direction.
  5830. this.done = []
  5831. this.undone = []
  5832. this.undoDepth = prev ? prev.undoDepth : Infinity
  5833. // Used to track when changes can be merged into a single undo
  5834. // event
  5835. this.lastModTime = this.lastSelTime = 0
  5836. this.lastOp = this.lastSelOp = null
  5837. this.lastOrigin = this.lastSelOrigin = null
  5838. // Used by the isClean() method
  5839. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1
  5840. }
  5841. // Create a history change event from an updateDoc-style change
  5842. // object.
  5843. function historyChangeFromChange(doc, change) {
  5844. var histChange = { from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to) }
  5845. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  5846. linkedDocs(
  5847. doc,
  5848. function (doc) {
  5849. return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  5850. },
  5851. true
  5852. )
  5853. return histChange
  5854. }
  5855. // Pop all selection events off the end of a history array. Stop at
  5856. // a change event.
  5857. function clearSelectionEvents(array) {
  5858. while (array.length) {
  5859. var last = lst(array)
  5860. if (last.ranges) {
  5861. array.pop()
  5862. } else {
  5863. break
  5864. }
  5865. }
  5866. }
  5867. // Find the top change event in the history. Pop off selection
  5868. // events that are in the way.
  5869. function lastChangeEvent(hist, force) {
  5870. if (force) {
  5871. clearSelectionEvents(hist.done)
  5872. return lst(hist.done)
  5873. } else if (hist.done.length && !lst(hist.done).ranges) {
  5874. return lst(hist.done)
  5875. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  5876. hist.done.pop()
  5877. return lst(hist.done)
  5878. }
  5879. }
  5880. // Register a change in the history. Merges changes that are within
  5881. // a single operation, or are close together with an origin that
  5882. // allows merging (starting with "+") into a single event.
  5883. function addChangeToHistory(doc, change, selAfter, opId) {
  5884. var hist = doc.history
  5885. hist.undone.length = 0
  5886. var time = +new Date(),
  5887. cur
  5888. var last
  5889. if (
  5890. (hist.lastOp == opId ||
  5891. (hist.lastOrigin == change.origin &&
  5892. change.origin &&
  5893. ((change.origin.charAt(0) == '+' && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || change.origin.charAt(0) == '*'))) &&
  5894. (cur = lastChangeEvent(hist, hist.lastOp == opId))
  5895. ) {
  5896. // Merge this change into the last event
  5897. last = lst(cur.changes)
  5898. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  5899. // Optimized case for simple insertion -- don't want to add
  5900. // new changesets for every character typed
  5901. last.to = changeEnd(change)
  5902. } else {
  5903. // Add new sub-event
  5904. cur.changes.push(historyChangeFromChange(doc, change))
  5905. }
  5906. } else {
  5907. // Can not be merged, start a new event.
  5908. var before = lst(hist.done)
  5909. if (!before || !before.ranges) {
  5910. pushSelectionToHistory(doc.sel, hist.done)
  5911. }
  5912. cur = { changes: [historyChangeFromChange(doc, change)], generation: hist.generation }
  5913. hist.done.push(cur)
  5914. while (hist.done.length > hist.undoDepth) {
  5915. hist.done.shift()
  5916. if (!hist.done[0].ranges) {
  5917. hist.done.shift()
  5918. }
  5919. }
  5920. }
  5921. hist.done.push(selAfter)
  5922. hist.generation = ++hist.maxGeneration
  5923. hist.lastModTime = hist.lastSelTime = time
  5924. hist.lastOp = hist.lastSelOp = opId
  5925. hist.lastOrigin = hist.lastSelOrigin = change.origin
  5926. if (!last) {
  5927. signal(doc, 'historyAdded')
  5928. }
  5929. }
  5930. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  5931. var ch = origin.charAt(0)
  5932. return (
  5933. ch == '*' ||
  5934. (ch == '+' &&
  5935. prev.ranges.length == sel.ranges.length &&
  5936. prev.somethingSelected() == sel.somethingSelected() &&
  5937. new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500))
  5938. )
  5939. }
  5940. // Called whenever the selection changes, sets the new selection as
  5941. // the pending selection in the history, and pushes the old pending
  5942. // selection into the 'done' array when it was significantly
  5943. // different (in number of selected ranges, emptiness, or time).
  5944. function addSelectionToHistory(doc, sel, opId, options) {
  5945. var hist = doc.history,
  5946. origin = options && options.origin
  5947. // A new event is started when the previous origin does not match
  5948. // the current, or the origins don't allow matching. Origins
  5949. // starting with * are always merged, those starting with + are
  5950. // merged when similar and close together in time.
  5951. if (
  5952. opId == hist.lastSelOp ||
  5953. (origin && hist.lastSelOrigin == origin && ((hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin) || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))
  5954. ) {
  5955. hist.done[hist.done.length - 1] = sel
  5956. } else {
  5957. pushSelectionToHistory(sel, hist.done)
  5958. }
  5959. hist.lastSelTime = +new Date()
  5960. hist.lastSelOrigin = origin
  5961. hist.lastSelOp = opId
  5962. if (options && options.clearRedo !== false) {
  5963. clearSelectionEvents(hist.undone)
  5964. }
  5965. }
  5966. function pushSelectionToHistory(sel, dest) {
  5967. var top = lst(dest)
  5968. if (!(top && top.ranges && top.equals(sel))) {
  5969. dest.push(sel)
  5970. }
  5971. }
  5972. // Used to store marked span information in the history.
  5973. function attachLocalSpans(doc, change, from, to) {
  5974. var existing = change['spans_' + doc.id],
  5975. n = 0
  5976. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  5977. if (line.markedSpans) {
  5978. ;(existing || (existing = change['spans_' + doc.id] = {}))[n] = line.markedSpans
  5979. }
  5980. ++n
  5981. })
  5982. }
  5983. // When un/re-doing restores text containing marked spans, those
  5984. // that have been explicitly cleared should not be restored.
  5985. function removeClearedSpans(spans) {
  5986. if (!spans) {
  5987. return null
  5988. }
  5989. var out
  5990. for (var i = 0; i < spans.length; ++i) {
  5991. if (spans[i].marker.explicitlyCleared) {
  5992. if (!out) {
  5993. out = spans.slice(0, i)
  5994. }
  5995. } else if (out) {
  5996. out.push(spans[i])
  5997. }
  5998. }
  5999. return !out ? spans : out.length ? out : null
  6000. }
  6001. // Retrieve and filter the old marked spans stored in a change event.
  6002. function getOldSpans(doc, change) {
  6003. var found = change['spans_' + doc.id]
  6004. if (!found) {
  6005. return null
  6006. }
  6007. var nw = []
  6008. for (var i = 0; i < change.text.length; ++i) {
  6009. nw.push(removeClearedSpans(found[i]))
  6010. }
  6011. return nw
  6012. }
  6013. // Used for un/re-doing changes from the history. Combines the
  6014. // result of computing the existing spans with the set of spans that
  6015. // existed in the history (so that deleting around a span and then
  6016. // undoing brings back the span).
  6017. function mergeOldSpans(doc, change) {
  6018. var old = getOldSpans(doc, change)
  6019. var stretched = stretchSpansOverChange(doc, change)
  6020. if (!old) {
  6021. return stretched
  6022. }
  6023. if (!stretched) {
  6024. return old
  6025. }
  6026. for (var i = 0; i < old.length; ++i) {
  6027. var oldCur = old[i],
  6028. stretchCur = stretched[i]
  6029. if (oldCur && stretchCur) {
  6030. spans: for (var j = 0; j < stretchCur.length; ++j) {
  6031. var span = stretchCur[j]
  6032. for (var k = 0; k < oldCur.length; ++k) {
  6033. if (oldCur[k].marker == span.marker) {
  6034. continue spans
  6035. }
  6036. }
  6037. oldCur.push(span)
  6038. }
  6039. } else if (stretchCur) {
  6040. old[i] = stretchCur
  6041. }
  6042. }
  6043. return old
  6044. }
  6045. // Used both to provide a JSON-safe object in .getHistory, and, when
  6046. // detaching a document, to split the history in two
  6047. function copyHistoryArray(events, newGroup, instantiateSel) {
  6048. var copy = []
  6049. for (var i = 0; i < events.length; ++i) {
  6050. var event = events[i]
  6051. if (event.ranges) {
  6052. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  6053. continue
  6054. }
  6055. var changes = event.changes,
  6056. newChanges = []
  6057. copy.push({ changes: newChanges })
  6058. for (var j = 0; j < changes.length; ++j) {
  6059. var change = changes[j],
  6060. m = void 0
  6061. newChanges.push({ from: change.from, to: change.to, text: change.text })
  6062. if (newGroup) {
  6063. for (var prop in change) {
  6064. if ((m = prop.match(/^spans_(\d+)$/))) {
  6065. if (indexOf(newGroup, Number(m[1])) > -1) {
  6066. lst(newChanges)[prop] = change[prop]
  6067. delete change[prop]
  6068. }
  6069. }
  6070. }
  6071. }
  6072. }
  6073. }
  6074. return copy
  6075. }
  6076. // The 'scroll' parameter given to many of these indicated whether
  6077. // the new cursor position should be scrolled into view after
  6078. // modifying the selection.
  6079. // If shift is held or the extend flag is set, extends a range to
  6080. // include a given position (and optionally a second position).
  6081. // Otherwise, simply returns the range between the given positions.
  6082. // Used for cursor motion and such.
  6083. function extendRange(range, head, other, extend) {
  6084. if (extend) {
  6085. var anchor = range.anchor
  6086. if (other) {
  6087. var posBefore = cmp(head, anchor) < 0
  6088. if (posBefore != cmp(other, anchor) < 0) {
  6089. anchor = head
  6090. head = other
  6091. } else if (posBefore != cmp(head, other) < 0) {
  6092. head = other
  6093. }
  6094. }
  6095. return new Range(anchor, head)
  6096. } else {
  6097. return new Range(other || head, head)
  6098. }
  6099. }
  6100. // Extend the primary selection range, discard the rest.
  6101. function extendSelection(doc, head, other, options, extend) {
  6102. if (extend == null) {
  6103. extend = doc.cm && (doc.cm.display.shift || doc.extend)
  6104. }
  6105. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options)
  6106. }
  6107. // Extend all selections (pos is an array of selections with length
  6108. // equal the number of selections)
  6109. function extendSelections(doc, heads, options) {
  6110. var out = []
  6111. var extend = doc.cm && (doc.cm.display.shift || doc.extend)
  6112. for (var i = 0; i < doc.sel.ranges.length; i++) {
  6113. out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend)
  6114. }
  6115. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex)
  6116. setSelection(doc, newSel, options)
  6117. }
  6118. // Updates a single range in the selection.
  6119. function replaceOneSelection(doc, i, range, options) {
  6120. var ranges = doc.sel.ranges.slice(0)
  6121. ranges[i] = range
  6122. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options)
  6123. }
  6124. // Reset the selection to a single range.
  6125. function setSimpleSelection(doc, anchor, head, options) {
  6126. setSelection(doc, simpleSelection(anchor, head), options)
  6127. }
  6128. // Give beforeSelectionChange handlers a change to influence a
  6129. // selection update.
  6130. function filterSelectionChange(doc, sel, options) {
  6131. var obj = {
  6132. ranges: sel.ranges,
  6133. update: function (ranges) {
  6134. this.ranges = []
  6135. for (var i = 0; i < ranges.length; i++) {
  6136. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head))
  6137. }
  6138. },
  6139. origin: options && options.origin,
  6140. }
  6141. signal(doc, 'beforeSelectionChange', doc, obj)
  6142. if (doc.cm) {
  6143. signal(doc.cm, 'beforeSelectionChange', doc.cm, obj)
  6144. }
  6145. if (obj.ranges != sel.ranges) {
  6146. return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1)
  6147. } else {
  6148. return sel
  6149. }
  6150. }
  6151. function setSelectionReplaceHistory(doc, sel, options) {
  6152. var done = doc.history.done,
  6153. last = lst(done)
  6154. if (last && last.ranges) {
  6155. done[done.length - 1] = sel
  6156. setSelectionNoUndo(doc, sel, options)
  6157. } else {
  6158. setSelection(doc, sel, options)
  6159. }
  6160. }
  6161. // Set a new selection.
  6162. function setSelection(doc, sel, options) {
  6163. setSelectionNoUndo(doc, sel, options)
  6164. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  6165. }
  6166. function setSelectionNoUndo(doc, sel, options) {
  6167. if (hasHandler(doc, 'beforeSelectionChange') || (doc.cm && hasHandler(doc.cm, 'beforeSelectionChange'))) {
  6168. sel = filterSelectionChange(doc, sel, options)
  6169. }
  6170. var bias = (options && options.bias) || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  6171. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  6172. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption('readOnly') != 'nocursor') {
  6173. ensureCursorVisible(doc.cm)
  6174. }
  6175. }
  6176. function setSelectionInner(doc, sel) {
  6177. if (sel.equals(doc.sel)) {
  6178. return
  6179. }
  6180. doc.sel = sel
  6181. if (doc.cm) {
  6182. doc.cm.curOp.updateInput = 1
  6183. doc.cm.curOp.selectionChanged = true
  6184. signalCursorActivity(doc.cm)
  6185. }
  6186. signalLater(doc, 'cursorActivity', doc)
  6187. }
  6188. // Verify that the selection does not partially select any atomic
  6189. // marked ranges.
  6190. function reCheckSelection(doc) {
  6191. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false))
  6192. }
  6193. // Return a selection that does not partially select any atomic
  6194. // ranges.
  6195. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  6196. var out
  6197. for (var i = 0; i < sel.ranges.length; i++) {
  6198. var range = sel.ranges[i]
  6199. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  6200. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  6201. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  6202. if (out || newAnchor != range.anchor || newHead != range.head) {
  6203. if (!out) {
  6204. out = sel.ranges.slice(0, i)
  6205. }
  6206. out[i] = new Range(newAnchor, newHead)
  6207. }
  6208. }
  6209. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  6210. }
  6211. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  6212. var line = getLine(doc, pos.line)
  6213. if (line.markedSpans) {
  6214. for (var i = 0; i < line.markedSpans.length; ++i) {
  6215. var sp = line.markedSpans[i],
  6216. m = sp.marker
  6217. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  6218. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  6219. // is with selectLeft/Right
  6220. var preventCursorLeft = 'selectLeft' in m ? !m.selectLeft : m.inclusiveLeft
  6221. var preventCursorRight = 'selectRight' in m ? !m.selectRight : m.inclusiveRight
  6222. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  6223. if (mayClear) {
  6224. signal(m, 'beforeCursorEnter')
  6225. if (m.explicitlyCleared) {
  6226. if (!line.markedSpans) {
  6227. break
  6228. } else {
  6229. --i
  6230. continue
  6231. }
  6232. }
  6233. }
  6234. if (!m.atomic) {
  6235. continue
  6236. }
  6237. if (oldPos) {
  6238. var near = m.find(dir < 0 ? 1 : -1),
  6239. diff = void 0
  6240. if (dir < 0 ? preventCursorRight : preventCursorLeft) {
  6241. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null)
  6242. }
  6243. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) {
  6244. return skipAtomicInner(doc, near, pos, dir, mayClear)
  6245. }
  6246. }
  6247. var far = m.find(dir < 0 ? -1 : 1)
  6248. if (dir < 0 ? preventCursorLeft : preventCursorRight) {
  6249. far = movePos(doc, far, dir, far.line == pos.line ? line : null)
  6250. }
  6251. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  6252. }
  6253. }
  6254. }
  6255. return pos
  6256. }
  6257. // Ensure a given position is not inside an atomic range.
  6258. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  6259. var dir = bias || 1
  6260. var found =
  6261. skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  6262. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  6263. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  6264. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  6265. if (!found) {
  6266. doc.cantEdit = true
  6267. return Pos(doc.first, 0)
  6268. }
  6269. return found
  6270. }
  6271. function movePos(doc, pos, dir, line) {
  6272. if (dir < 0 && pos.ch == 0) {
  6273. if (pos.line > doc.first) {
  6274. return clipPos(doc, Pos(pos.line - 1))
  6275. } else {
  6276. return null
  6277. }
  6278. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  6279. if (pos.line < doc.first + doc.size - 1) {
  6280. return Pos(pos.line + 1, 0)
  6281. } else {
  6282. return null
  6283. }
  6284. } else {
  6285. return new Pos(pos.line, pos.ch + dir)
  6286. }
  6287. }
  6288. function selectAll(cm) {
  6289. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  6290. }
  6291. // UPDATING
  6292. // Allow "beforeChange" event handlers to influence a change
  6293. function filterChange(doc, change, update) {
  6294. var obj = {
  6295. canceled: false,
  6296. from: change.from,
  6297. to: change.to,
  6298. text: change.text,
  6299. origin: change.origin,
  6300. cancel: function () {
  6301. return (obj.canceled = true)
  6302. },
  6303. }
  6304. if (update) {
  6305. obj.update = function (from, to, text, origin) {
  6306. if (from) {
  6307. obj.from = clipPos(doc, from)
  6308. }
  6309. if (to) {
  6310. obj.to = clipPos(doc, to)
  6311. }
  6312. if (text) {
  6313. obj.text = text
  6314. }
  6315. if (origin !== undefined) {
  6316. obj.origin = origin
  6317. }
  6318. }
  6319. }
  6320. signal(doc, 'beforeChange', doc, obj)
  6321. if (doc.cm) {
  6322. signal(doc.cm, 'beforeChange', doc.cm, obj)
  6323. }
  6324. if (obj.canceled) {
  6325. if (doc.cm) {
  6326. doc.cm.curOp.updateInput = 2
  6327. }
  6328. return null
  6329. }
  6330. return { from: obj.from, to: obj.to, text: obj.text, origin: obj.origin }
  6331. }
  6332. // Apply a change to a document, and add it to the document's
  6333. // history, and propagating it to all linked documents.
  6334. function makeChange(doc, change, ignoreReadOnly) {
  6335. if (doc.cm) {
  6336. if (!doc.cm.curOp) {
  6337. return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly)
  6338. }
  6339. if (doc.cm.state.suppressEdits) {
  6340. return
  6341. }
  6342. }
  6343. if (hasHandler(doc, 'beforeChange') || (doc.cm && hasHandler(doc.cm, 'beforeChange'))) {
  6344. change = filterChange(doc, change, true)
  6345. if (!change) {
  6346. return
  6347. }
  6348. }
  6349. // Possibly split or suppress the update based on the presence
  6350. // of read-only spans in its range.
  6351. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  6352. if (split) {
  6353. for (var i = split.length - 1; i >= 0; --i) {
  6354. makeChangeInner(doc, { from: split[i].from, to: split[i].to, text: i ? [''] : change.text, origin: change.origin })
  6355. }
  6356. } else {
  6357. makeChangeInner(doc, change)
  6358. }
  6359. }
  6360. function makeChangeInner(doc, change) {
  6361. if (change.text.length == 1 && change.text[0] == '' && cmp(change.from, change.to) == 0) {
  6362. return
  6363. }
  6364. var selAfter = computeSelAfterChange(doc, change)
  6365. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  6366. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  6367. var rebased = []
  6368. linkedDocs(doc, function (doc, sharedHist) {
  6369. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6370. rebaseHist(doc.history, change)
  6371. rebased.push(doc.history)
  6372. }
  6373. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  6374. })
  6375. }
  6376. // Revert a change stored in a document's history.
  6377. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  6378. var suppress = doc.cm && doc.cm.state.suppressEdits
  6379. if (suppress && !allowSelectionOnly) {
  6380. return
  6381. }
  6382. var hist = doc.history,
  6383. event,
  6384. selAfter = doc.sel
  6385. var source = type == 'undo' ? hist.done : hist.undone,
  6386. dest = type == 'undo' ? hist.undone : hist.done
  6387. // Verify that there is a useable event (so that ctrl-z won't
  6388. // needlessly clear selection events)
  6389. var i = 0
  6390. for (; i < source.length; i++) {
  6391. event = source[i]
  6392. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) {
  6393. break
  6394. }
  6395. }
  6396. if (i == source.length) {
  6397. return
  6398. }
  6399. hist.lastOrigin = hist.lastSelOrigin = null
  6400. for (;;) {
  6401. event = source.pop()
  6402. if (event.ranges) {
  6403. pushSelectionToHistory(event, dest)
  6404. if (allowSelectionOnly && !event.equals(doc.sel)) {
  6405. setSelection(doc, event, { clearRedo: false })
  6406. return
  6407. }
  6408. selAfter = event
  6409. } else if (suppress) {
  6410. source.push(event)
  6411. return
  6412. } else {
  6413. break
  6414. }
  6415. }
  6416. // Build up a reverse change object to add to the opposite history
  6417. // stack (redo when undoing, and vice versa).
  6418. var antiChanges = []
  6419. pushSelectionToHistory(selAfter, dest)
  6420. dest.push({ changes: antiChanges, generation: hist.generation })
  6421. hist.generation = event.generation || ++hist.maxGeneration
  6422. var filter = hasHandler(doc, 'beforeChange') || (doc.cm && hasHandler(doc.cm, 'beforeChange'))
  6423. var loop = function (i) {
  6424. var change = event.changes[i]
  6425. change.origin = type
  6426. if (filter && !filterChange(doc, change, false)) {
  6427. source.length = 0
  6428. return {}
  6429. }
  6430. antiChanges.push(historyChangeFromChange(doc, change))
  6431. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  6432. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  6433. if (!i && doc.cm) {
  6434. doc.cm.scrollIntoView({ from: change.from, to: changeEnd(change) })
  6435. }
  6436. var rebased = []
  6437. // Propagate to the linked documents
  6438. linkedDocs(doc, function (doc, sharedHist) {
  6439. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6440. rebaseHist(doc.history, change)
  6441. rebased.push(doc.history)
  6442. }
  6443. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  6444. })
  6445. }
  6446. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  6447. var returned = loop(i$1)
  6448. if (returned) return returned.v
  6449. }
  6450. }
  6451. // Sub-views need their line numbers shifted when text is added
  6452. // above or below them in the parent document.
  6453. function shiftDoc(doc, distance) {
  6454. if (distance == 0) {
  6455. return
  6456. }
  6457. doc.first += distance
  6458. doc.sel = new Selection(
  6459. map(doc.sel.ranges, function (range) {
  6460. return new Range(Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch))
  6461. }),
  6462. doc.sel.primIndex
  6463. )
  6464. if (doc.cm) {
  6465. regChange(doc.cm, doc.first, doc.first - distance, distance)
  6466. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) {
  6467. regLineChange(doc.cm, l, 'gutter')
  6468. }
  6469. }
  6470. }
  6471. // More lower-level change function, handling only a single document
  6472. // (not linked ones).
  6473. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  6474. if (doc.cm && !doc.cm.curOp) {
  6475. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans)
  6476. }
  6477. if (change.to.line < doc.first) {
  6478. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  6479. return
  6480. }
  6481. if (change.from.line > doc.lastLine()) {
  6482. return
  6483. }
  6484. // Clip the change to the size of this doc
  6485. if (change.from.line < doc.first) {
  6486. var shift = change.text.length - 1 - (doc.first - change.from.line)
  6487. shiftDoc(doc, shift)
  6488. change = { from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin }
  6489. }
  6490. var last = doc.lastLine()
  6491. if (change.to.line > last) {
  6492. change = { from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin }
  6493. }
  6494. change.removed = getBetween(doc, change.from, change.to)
  6495. if (!selAfter) {
  6496. selAfter = computeSelAfterChange(doc, change)
  6497. }
  6498. if (doc.cm) {
  6499. makeChangeSingleDocInEditor(doc.cm, change, spans)
  6500. } else {
  6501. updateDoc(doc, change, spans)
  6502. }
  6503. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  6504. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) {
  6505. doc.cantEdit = false
  6506. }
  6507. }
  6508. // Handle the interaction of a change to a document with the editor
  6509. // that this document is part of.
  6510. function makeChangeSingleDocInEditor(cm, change, spans) {
  6511. var doc = cm.doc,
  6512. display = cm.display,
  6513. from = change.from,
  6514. to = change.to
  6515. var recomputeMaxLength = false,
  6516. checkWidthStart = from.line
  6517. if (!cm.options.lineWrapping) {
  6518. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  6519. doc.iter(checkWidthStart, to.line + 1, function (line) {
  6520. if (line == display.maxLine) {
  6521. recomputeMaxLength = true
  6522. return true
  6523. }
  6524. })
  6525. }
  6526. if (doc.sel.contains(change.from, change.to) > -1) {
  6527. signalCursorActivity(cm)
  6528. }
  6529. updateDoc(doc, change, spans, estimateHeight(cm))
  6530. if (!cm.options.lineWrapping) {
  6531. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  6532. var len = lineLength(line)
  6533. if (len > display.maxLineLength) {
  6534. display.maxLine = line
  6535. display.maxLineLength = len
  6536. display.maxLineChanged = true
  6537. recomputeMaxLength = false
  6538. }
  6539. })
  6540. if (recomputeMaxLength) {
  6541. cm.curOp.updateMaxLine = true
  6542. }
  6543. }
  6544. retreatFrontier(doc, from.line)
  6545. startWorker(cm, 400)
  6546. var lendiff = change.text.length - (to.line - from.line) - 1
  6547. // Remember that these lines changed, for updating the display
  6548. if (change.full) {
  6549. regChange(cm)
  6550. } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {
  6551. regLineChange(cm, from.line, 'text')
  6552. } else {
  6553. regChange(cm, from.line, to.line + 1, lendiff)
  6554. }
  6555. var changesHandler = hasHandler(cm, 'changes'),
  6556. changeHandler = hasHandler(cm, 'change')
  6557. if (changeHandler || changesHandler) {
  6558. var obj = {
  6559. from: from,
  6560. to: to,
  6561. text: change.text,
  6562. removed: change.removed,
  6563. origin: change.origin,
  6564. }
  6565. if (changeHandler) {
  6566. signalLater(cm, 'change', cm, obj)
  6567. }
  6568. if (changesHandler) {
  6569. ;(cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj)
  6570. }
  6571. }
  6572. cm.display.selForContextMenu = null
  6573. }
  6574. function replaceRange(doc, code, from, to, origin) {
  6575. var assign
  6576. if (!to) {
  6577. to = from
  6578. }
  6579. if (cmp(to, from) < 0) {
  6580. ;(assign = [to, from]), (from = assign[0]), (to = assign[1])
  6581. }
  6582. if (typeof code == 'string') {
  6583. code = doc.splitLines(code)
  6584. }
  6585. makeChange(doc, { from: from, to: to, text: code, origin: origin })
  6586. }
  6587. // Rebasing/resetting history to deal with externally-sourced changes
  6588. function rebaseHistSelSingle(pos, from, to, diff) {
  6589. if (to < pos.line) {
  6590. pos.line += diff
  6591. } else if (from < pos.line) {
  6592. pos.line = from
  6593. pos.ch = 0
  6594. }
  6595. }
  6596. // Tries to rebase an array of history events given a change in the
  6597. // document. If the change touches the same lines as the event, the
  6598. // event, and everything 'behind' it, is discarded. If the change is
  6599. // before the event, the event's positions are updated. Uses a
  6600. // copy-on-write scheme for the positions, to avoid having to
  6601. // reallocate them all on every rebase, but also avoid problems with
  6602. // shared position objects being unsafely updated.
  6603. function rebaseHistArray(array, from, to, diff) {
  6604. for (var i = 0; i < array.length; ++i) {
  6605. var sub = array[i],
  6606. ok = true
  6607. if (sub.ranges) {
  6608. if (!sub.copied) {
  6609. sub = array[i] = sub.deepCopy()
  6610. sub.copied = true
  6611. }
  6612. for (var j = 0; j < sub.ranges.length; j++) {
  6613. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  6614. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  6615. }
  6616. continue
  6617. }
  6618. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  6619. var cur = sub.changes[j$1]
  6620. if (to < cur.from.line) {
  6621. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  6622. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  6623. } else if (from <= cur.to.line) {
  6624. ok = false
  6625. break
  6626. }
  6627. }
  6628. if (!ok) {
  6629. array.splice(0, i + 1)
  6630. i = 0
  6631. }
  6632. }
  6633. }
  6634. function rebaseHist(hist, change) {
  6635. var from = change.from.line,
  6636. to = change.to.line,
  6637. diff = change.text.length - (to - from) - 1
  6638. rebaseHistArray(hist.done, from, to, diff)
  6639. rebaseHistArray(hist.undone, from, to, diff)
  6640. }
  6641. // Utility for applying a change to a line by handle or number,
  6642. // returning the number and optionally registering the line as
  6643. // changed.
  6644. function changeLine(doc, handle, changeType, op) {
  6645. var no = handle,
  6646. line = handle
  6647. if (typeof handle == 'number') {
  6648. line = getLine(doc, clipLine(doc, handle))
  6649. } else {
  6650. no = lineNo(handle)
  6651. }
  6652. if (no == null) {
  6653. return null
  6654. }
  6655. if (op(line, no) && doc.cm) {
  6656. regLineChange(doc.cm, no, changeType)
  6657. }
  6658. return line
  6659. }
  6660. // The document is represented as a BTree consisting of leaves, with
  6661. // chunk of lines in them, and branches, with up to ten leaves or
  6662. // other branch nodes below them. The top node is always a branch
  6663. // node, and is the document object itself (meaning it has
  6664. // additional methods and properties).
  6665. //
  6666. // All nodes have parent links. The tree is used both to go from
  6667. // line numbers to line objects, and to go from objects to numbers.
  6668. // It also indexes by height, and is used to convert between height
  6669. // and line object, and to find the total height of the document.
  6670. //
  6671. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6672. function LeafChunk(lines) {
  6673. this.lines = lines
  6674. this.parent = null
  6675. var height = 0
  6676. for (var i = 0; i < lines.length; ++i) {
  6677. lines[i].parent = this
  6678. height += lines[i].height
  6679. }
  6680. this.height = height
  6681. }
  6682. LeafChunk.prototype = {
  6683. chunkSize: function () {
  6684. return this.lines.length
  6685. },
  6686. // Remove the n lines at offset 'at'.
  6687. removeInner: function (at, n) {
  6688. for (var i = at, e = at + n; i < e; ++i) {
  6689. var line = this.lines[i]
  6690. this.height -= line.height
  6691. cleanUpLine(line)
  6692. signalLater(line, 'delete')
  6693. }
  6694. this.lines.splice(at, n)
  6695. },
  6696. // Helper used to collapse a small branch into a single leaf.
  6697. collapse: function (lines) {
  6698. lines.push.apply(lines, this.lines)
  6699. },
  6700. // Insert the given array of lines at offset 'at', count them as
  6701. // having the given height.
  6702. insertInner: function (at, lines, height) {
  6703. this.height += height
  6704. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  6705. for (var i = 0; i < lines.length; ++i) {
  6706. lines[i].parent = this
  6707. }
  6708. },
  6709. // Used to iterate over a part of the tree.
  6710. iterN: function (at, n, op) {
  6711. for (var e = at + n; at < e; ++at) {
  6712. if (op(this.lines[at])) {
  6713. return true
  6714. }
  6715. }
  6716. },
  6717. }
  6718. function BranchChunk(children) {
  6719. this.children = children
  6720. var size = 0,
  6721. height = 0
  6722. for (var i = 0; i < children.length; ++i) {
  6723. var ch = children[i]
  6724. size += ch.chunkSize()
  6725. height += ch.height
  6726. ch.parent = this
  6727. }
  6728. this.size = size
  6729. this.height = height
  6730. this.parent = null
  6731. }
  6732. BranchChunk.prototype = {
  6733. chunkSize: function () {
  6734. return this.size
  6735. },
  6736. removeInner: function (at, n) {
  6737. this.size -= n
  6738. for (var i = 0; i < this.children.length; ++i) {
  6739. var child = this.children[i],
  6740. sz = child.chunkSize()
  6741. if (at < sz) {
  6742. var rm = Math.min(n, sz - at),
  6743. oldHeight = child.height
  6744. child.removeInner(at, rm)
  6745. this.height -= oldHeight - child.height
  6746. if (sz == rm) {
  6747. this.children.splice(i--, 1)
  6748. child.parent = null
  6749. }
  6750. if ((n -= rm) == 0) {
  6751. break
  6752. }
  6753. at = 0
  6754. } else {
  6755. at -= sz
  6756. }
  6757. }
  6758. // If the result is smaller than 25 lines, ensure that it is a
  6759. // single leaf node.
  6760. if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6761. var lines = []
  6762. this.collapse(lines)
  6763. this.children = [new LeafChunk(lines)]
  6764. this.children[0].parent = this
  6765. }
  6766. },
  6767. collapse: function (lines) {
  6768. for (var i = 0; i < this.children.length; ++i) {
  6769. this.children[i].collapse(lines)
  6770. }
  6771. },
  6772. insertInner: function (at, lines, height) {
  6773. this.size += lines.length
  6774. this.height += height
  6775. for (var i = 0; i < this.children.length; ++i) {
  6776. var child = this.children[i],
  6777. sz = child.chunkSize()
  6778. if (at <= sz) {
  6779. child.insertInner(at, lines, height)
  6780. if (child.lines && child.lines.length > 50) {
  6781. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  6782. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  6783. var remaining = (child.lines.length % 25) + 25
  6784. for (var pos = remaining; pos < child.lines.length; ) {
  6785. var leaf = new LeafChunk(child.lines.slice(pos, (pos += 25)))
  6786. child.height -= leaf.height
  6787. this.children.splice(++i, 0, leaf)
  6788. leaf.parent = this
  6789. }
  6790. child.lines = child.lines.slice(0, remaining)
  6791. this.maybeSpill()
  6792. }
  6793. break
  6794. }
  6795. at -= sz
  6796. }
  6797. },
  6798. // When a node has grown, check whether it should be split.
  6799. maybeSpill: function () {
  6800. if (this.children.length <= 10) {
  6801. return
  6802. }
  6803. var me = this
  6804. do {
  6805. var spilled = me.children.splice(me.children.length - 5, 5)
  6806. var sibling = new BranchChunk(spilled)
  6807. if (!me.parent) {
  6808. // Become the parent node
  6809. var copy = new BranchChunk(me.children)
  6810. copy.parent = me
  6811. me.children = [copy, sibling]
  6812. me = copy
  6813. } else {
  6814. me.size -= sibling.size
  6815. me.height -= sibling.height
  6816. var myIndex = indexOf(me.parent.children, me)
  6817. me.parent.children.splice(myIndex + 1, 0, sibling)
  6818. }
  6819. sibling.parent = me.parent
  6820. } while (me.children.length > 10)
  6821. me.parent.maybeSpill()
  6822. },
  6823. iterN: function (at, n, op) {
  6824. for (var i = 0; i < this.children.length; ++i) {
  6825. var child = this.children[i],
  6826. sz = child.chunkSize()
  6827. if (at < sz) {
  6828. var used = Math.min(n, sz - at)
  6829. if (child.iterN(at, used, op)) {
  6830. return true
  6831. }
  6832. if ((n -= used) == 0) {
  6833. break
  6834. }
  6835. at = 0
  6836. } else {
  6837. at -= sz
  6838. }
  6839. }
  6840. },
  6841. }
  6842. // Line widgets are block elements displayed above or below a line.
  6843. var LineWidget = function (doc, node, options) {
  6844. if (options) {
  6845. for (var opt in options) {
  6846. if (options.hasOwnProperty(opt)) {
  6847. this[opt] = options[opt]
  6848. }
  6849. }
  6850. }
  6851. this.doc = doc
  6852. this.node = node
  6853. }
  6854. LineWidget.prototype.clear = function () {
  6855. var cm = this.doc.cm,
  6856. ws = this.line.widgets,
  6857. line = this.line,
  6858. no = lineNo(line)
  6859. if (no == null || !ws) {
  6860. return
  6861. }
  6862. for (var i = 0; i < ws.length; ++i) {
  6863. if (ws[i] == this) {
  6864. ws.splice(i--, 1)
  6865. }
  6866. }
  6867. if (!ws.length) {
  6868. line.widgets = null
  6869. }
  6870. var height = widgetHeight(this)
  6871. updateLineHeight(line, Math.max(0, line.height - height))
  6872. if (cm) {
  6873. runInOp(cm, function () {
  6874. adjustScrollWhenAboveVisible(cm, line, -height)
  6875. regLineChange(cm, no, 'widget')
  6876. })
  6877. signalLater(cm, 'lineWidgetCleared', cm, this, no)
  6878. }
  6879. }
  6880. LineWidget.prototype.changed = function () {
  6881. var this$1 = this
  6882. var oldH = this.height,
  6883. cm = this.doc.cm,
  6884. line = this.line
  6885. this.height = null
  6886. var diff = widgetHeight(this) - oldH
  6887. if (!diff) {
  6888. return
  6889. }
  6890. if (!lineIsHidden(this.doc, line)) {
  6891. updateLineHeight(line, line.height + diff)
  6892. }
  6893. if (cm) {
  6894. runInOp(cm, function () {
  6895. cm.curOp.forceUpdate = true
  6896. adjustScrollWhenAboveVisible(cm, line, diff)
  6897. signalLater(cm, 'lineWidgetChanged', cm, this$1, lineNo(line))
  6898. })
  6899. }
  6900. }
  6901. eventMixin(LineWidget)
  6902. function adjustScrollWhenAboveVisible(cm, line, diff) {
  6903. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) {
  6904. addToScrollTop(cm, diff)
  6905. }
  6906. }
  6907. function addLineWidget(doc, handle, node, options) {
  6908. var widget = new LineWidget(doc, node, options)
  6909. var cm = doc.cm
  6910. if (cm && widget.noHScroll) {
  6911. cm.display.alignWidgets = true
  6912. }
  6913. changeLine(doc, handle, 'widget', function (line) {
  6914. var widgets = line.widgets || (line.widgets = [])
  6915. if (widget.insertAt == null) {
  6916. widgets.push(widget)
  6917. } else {
  6918. widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget)
  6919. }
  6920. widget.line = line
  6921. if (cm && !lineIsHidden(doc, line)) {
  6922. var aboveVisible = heightAtLine(line) < doc.scrollTop
  6923. updateLineHeight(line, line.height + widgetHeight(widget))
  6924. if (aboveVisible) {
  6925. addToScrollTop(cm, widget.height)
  6926. }
  6927. cm.curOp.forceUpdate = true
  6928. }
  6929. return true
  6930. })
  6931. if (cm) {
  6932. signalLater(cm, 'lineWidgetAdded', cm, widget, typeof handle == 'number' ? handle : lineNo(handle))
  6933. }
  6934. return widget
  6935. }
  6936. // TEXTMARKERS
  6937. // Created with markText and setBookmark methods. A TextMarker is a
  6938. // handle that can be used to clear or find a marked position in the
  6939. // document. Line objects hold arrays (markedSpans) containing
  6940. // {from, to, marker} object pointing to such marker objects, and
  6941. // indicating that such a marker is present on that line. Multiple
  6942. // lines may point to the same marker when it spans across lines.
  6943. // The spans will have null for their from/to properties when the
  6944. // marker continues beyond the start/end of the line. Markers have
  6945. // links back to the lines they currently touch.
  6946. // Collapsed markers have unique ids, in order to be able to order
  6947. // them, which is needed for uniquely determining an outer marker
  6948. // when they overlap (they may nest, but not partially overlap).
  6949. var nextMarkerId = 0
  6950. var TextMarker = function (doc, type) {
  6951. this.lines = []
  6952. this.type = type
  6953. this.doc = doc
  6954. this.id = ++nextMarkerId
  6955. }
  6956. // Clear the marker.
  6957. TextMarker.prototype.clear = function () {
  6958. if (this.explicitlyCleared) {
  6959. return
  6960. }
  6961. var cm = this.doc.cm,
  6962. withOp = cm && !cm.curOp
  6963. if (withOp) {
  6964. startOperation(cm)
  6965. }
  6966. if (hasHandler(this, 'clear')) {
  6967. var found = this.find()
  6968. if (found) {
  6969. signalLater(this, 'clear', found.from, found.to)
  6970. }
  6971. }
  6972. var min = null,
  6973. max = null
  6974. for (var i = 0; i < this.lines.length; ++i) {
  6975. var line = this.lines[i]
  6976. var span = getMarkedSpanFor(line.markedSpans, this)
  6977. if (cm && !this.collapsed) {
  6978. regLineChange(cm, lineNo(line), 'text')
  6979. } else if (cm) {
  6980. if (span.to != null) {
  6981. max = lineNo(line)
  6982. }
  6983. if (span.from != null) {
  6984. min = lineNo(line)
  6985. }
  6986. }
  6987. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  6988. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {
  6989. updateLineHeight(line, textHeight(cm.display))
  6990. }
  6991. }
  6992. if (cm && this.collapsed && !cm.options.lineWrapping) {
  6993. for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  6994. var visual = visualLine(this.lines[i$1]),
  6995. len = lineLength(visual)
  6996. if (len > cm.display.maxLineLength) {
  6997. cm.display.maxLine = visual
  6998. cm.display.maxLineLength = len
  6999. cm.display.maxLineChanged = true
  7000. }
  7001. }
  7002. }
  7003. if (min != null && cm && this.collapsed) {
  7004. regChange(cm, min, max + 1)
  7005. }
  7006. this.lines.length = 0
  7007. this.explicitlyCleared = true
  7008. if (this.atomic && this.doc.cantEdit) {
  7009. this.doc.cantEdit = false
  7010. if (cm) {
  7011. reCheckSelection(cm.doc)
  7012. }
  7013. }
  7014. if (cm) {
  7015. signalLater(cm, 'markerCleared', cm, this, min, max)
  7016. }
  7017. if (withOp) {
  7018. endOperation(cm)
  7019. }
  7020. if (this.parent) {
  7021. this.parent.clear()
  7022. }
  7023. }
  7024. // Find the position of the marker in the document. Returns a {from,
  7025. // to} object by default. Side can be passed to get a specific side
  7026. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  7027. // Pos objects returned contain a line object, rather than a line
  7028. // number (used to prevent looking up the same line twice).
  7029. TextMarker.prototype.find = function (side, lineObj) {
  7030. if (side == null && this.type == 'bookmark') {
  7031. side = 1
  7032. }
  7033. var from, to
  7034. for (var i = 0; i < this.lines.length; ++i) {
  7035. var line = this.lines[i]
  7036. var span = getMarkedSpanFor(line.markedSpans, this)
  7037. if (span.from != null) {
  7038. from = Pos(lineObj ? line : lineNo(line), span.from)
  7039. if (side == -1) {
  7040. return from
  7041. }
  7042. }
  7043. if (span.to != null) {
  7044. to = Pos(lineObj ? line : lineNo(line), span.to)
  7045. if (side == 1) {
  7046. return to
  7047. }
  7048. }
  7049. }
  7050. return from && { from: from, to: to }
  7051. }
  7052. // Signals that the marker's widget changed, and surrounding layout
  7053. // should be recomputed.
  7054. TextMarker.prototype.changed = function () {
  7055. var this$1 = this
  7056. var pos = this.find(-1, true),
  7057. widget = this,
  7058. cm = this.doc.cm
  7059. if (!pos || !cm) {
  7060. return
  7061. }
  7062. runInOp(cm, function () {
  7063. var line = pos.line,
  7064. lineN = lineNo(pos.line)
  7065. var view = findViewForLine(cm, lineN)
  7066. if (view) {
  7067. clearLineMeasurementCacheFor(view)
  7068. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  7069. }
  7070. cm.curOp.updateMaxLine = true
  7071. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  7072. var oldHeight = widget.height
  7073. widget.height = null
  7074. var dHeight = widgetHeight(widget) - oldHeight
  7075. if (dHeight) {
  7076. updateLineHeight(line, line.height + dHeight)
  7077. }
  7078. }
  7079. signalLater(cm, 'markerChanged', cm, this$1)
  7080. })
  7081. }
  7082. TextMarker.prototype.attachLine = function (line) {
  7083. if (!this.lines.length && this.doc.cm) {
  7084. var op = this.doc.cm.curOp
  7085. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {
  7086. ;(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this)
  7087. }
  7088. }
  7089. this.lines.push(line)
  7090. }
  7091. TextMarker.prototype.detachLine = function (line) {
  7092. this.lines.splice(indexOf(this.lines, line), 1)
  7093. if (!this.lines.length && this.doc.cm) {
  7094. var op = this.doc.cm.curOp
  7095. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  7096. }
  7097. }
  7098. eventMixin(TextMarker)
  7099. // Create a marker, wire it up to the right lines, and
  7100. function markText(doc, from, to, options, type) {
  7101. // Shared markers (across linked documents) are handled separately
  7102. // (markTextShared will call out to this again, once per
  7103. // document).
  7104. if (options && options.shared) {
  7105. return markTextShared(doc, from, to, options, type)
  7106. }
  7107. // Ensure we are in an operation.
  7108. if (doc.cm && !doc.cm.curOp) {
  7109. return operation(doc.cm, markText)(doc, from, to, options, type)
  7110. }
  7111. var marker = new TextMarker(doc, type),
  7112. diff = cmp(from, to)
  7113. if (options) {
  7114. copyObj(options, marker, false)
  7115. }
  7116. // Don't connect empty markers unless clearWhenEmpty is false
  7117. if (diff > 0 || (diff == 0 && marker.clearWhenEmpty !== false)) {
  7118. return marker
  7119. }
  7120. if (marker.replacedWith) {
  7121. // Showing up as a widget implies collapsed (widget replaces text)
  7122. marker.collapsed = true
  7123. marker.widgetNode = eltP('span', [marker.replacedWith], 'CodeMirror-widget')
  7124. if (!options.handleMouseEvents) {
  7125. marker.widgetNode.setAttribute('cm-ignore-events', 'true')
  7126. }
  7127. if (options.insertLeft) {
  7128. marker.widgetNode.insertLeft = true
  7129. }
  7130. }
  7131. if (marker.collapsed) {
  7132. if (conflictingCollapsedRange(doc, from.line, from, to, marker) || (from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))) {
  7133. throw new Error('Inserting collapsed marker partially overlapping an existing one')
  7134. }
  7135. seeCollapsedSpans()
  7136. }
  7137. if (marker.addToHistory) {
  7138. addChangeToHistory(doc, { from: from, to: to, origin: 'markText' }, doc.sel, NaN)
  7139. }
  7140. var curLine = from.line,
  7141. cm = doc.cm,
  7142. updateMaxLine
  7143. doc.iter(curLine, to.line + 1, function (line) {
  7144. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {
  7145. updateMaxLine = true
  7146. }
  7147. if (marker.collapsed && curLine != from.line) {
  7148. updateLineHeight(line, 0)
  7149. }
  7150. addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp)
  7151. ++curLine
  7152. })
  7153. // lineIsHidden depends on the presence of the spans, so needs a second pass
  7154. if (marker.collapsed) {
  7155. doc.iter(from.line, to.line + 1, function (line) {
  7156. if (lineIsHidden(doc, line)) {
  7157. updateLineHeight(line, 0)
  7158. }
  7159. })
  7160. }
  7161. if (marker.clearOnEnter) {
  7162. on(marker, 'beforeCursorEnter', function () {
  7163. return marker.clear()
  7164. })
  7165. }
  7166. if (marker.readOnly) {
  7167. seeReadOnlySpans()
  7168. if (doc.history.done.length || doc.history.undone.length) {
  7169. doc.clearHistory()
  7170. }
  7171. }
  7172. if (marker.collapsed) {
  7173. marker.id = ++nextMarkerId
  7174. marker.atomic = true
  7175. }
  7176. if (cm) {
  7177. // Sync editor state
  7178. if (updateMaxLine) {
  7179. cm.curOp.updateMaxLine = true
  7180. }
  7181. if (marker.collapsed) {
  7182. regChange(cm, from.line, to.line + 1)
  7183. } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) {
  7184. for (var i = from.line; i <= to.line; i++) {
  7185. regLineChange(cm, i, 'text')
  7186. }
  7187. }
  7188. if (marker.atomic) {
  7189. reCheckSelection(cm.doc)
  7190. }
  7191. signalLater(cm, 'markerAdded', cm, marker)
  7192. }
  7193. return marker
  7194. }
  7195. // SHARED TEXTMARKERS
  7196. // A shared marker spans multiple linked documents. It is
  7197. // implemented as a meta-marker-object controlling multiple normal
  7198. // markers.
  7199. var SharedTextMarker = function (markers, primary) {
  7200. this.markers = markers
  7201. this.primary = primary
  7202. for (var i = 0; i < markers.length; ++i) {
  7203. markers[i].parent = this
  7204. }
  7205. }
  7206. SharedTextMarker.prototype.clear = function () {
  7207. if (this.explicitlyCleared) {
  7208. return
  7209. }
  7210. this.explicitlyCleared = true
  7211. for (var i = 0; i < this.markers.length; ++i) {
  7212. this.markers[i].clear()
  7213. }
  7214. signalLater(this, 'clear')
  7215. }
  7216. SharedTextMarker.prototype.find = function (side, lineObj) {
  7217. return this.primary.find(side, lineObj)
  7218. }
  7219. eventMixin(SharedTextMarker)
  7220. function markTextShared(doc, from, to, options, type) {
  7221. options = copyObj(options)
  7222. options.shared = false
  7223. var markers = [markText(doc, from, to, options, type)],
  7224. primary = markers[0]
  7225. var widget = options.widgetNode
  7226. linkedDocs(doc, function (doc) {
  7227. if (widget) {
  7228. options.widgetNode = widget.cloneNode(true)
  7229. }
  7230. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  7231. for (var i = 0; i < doc.linked.length; ++i) {
  7232. if (doc.linked[i].isParent) {
  7233. return
  7234. }
  7235. }
  7236. primary = lst(markers)
  7237. })
  7238. return new SharedTextMarker(markers, primary)
  7239. }
  7240. function findSharedMarkers(doc) {
  7241. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) {
  7242. return m.parent
  7243. })
  7244. }
  7245. function copySharedMarkers(doc, markers) {
  7246. for (var i = 0; i < markers.length; i++) {
  7247. var marker = markers[i],
  7248. pos = marker.find()
  7249. var mFrom = doc.clipPos(pos.from),
  7250. mTo = doc.clipPos(pos.to)
  7251. if (cmp(mFrom, mTo)) {
  7252. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  7253. marker.markers.push(subMark)
  7254. subMark.parent = marker
  7255. }
  7256. }
  7257. }
  7258. function detachSharedMarkers(markers) {
  7259. var loop = function (i) {
  7260. var marker = markers[i],
  7261. linked = [marker.primary.doc]
  7262. linkedDocs(marker.primary.doc, function (d) {
  7263. return linked.push(d)
  7264. })
  7265. for (var j = 0; j < marker.markers.length; j++) {
  7266. var subMarker = marker.markers[j]
  7267. if (indexOf(linked, subMarker.doc) == -1) {
  7268. subMarker.parent = null
  7269. marker.markers.splice(j--, 1)
  7270. }
  7271. }
  7272. }
  7273. for (var i = 0; i < markers.length; i++) loop(i)
  7274. }
  7275. var nextDocId = 0
  7276. var Doc = function (text, mode, firstLine, lineSep, direction) {
  7277. if (!(this instanceof Doc)) {
  7278. return new Doc(text, mode, firstLine, lineSep, direction)
  7279. }
  7280. if (firstLine == null) {
  7281. firstLine = 0
  7282. }
  7283. BranchChunk.call(this, [new LeafChunk([new Line('', null)])])
  7284. this.first = firstLine
  7285. this.scrollTop = this.scrollLeft = 0
  7286. this.cantEdit = false
  7287. this.cleanGeneration = 1
  7288. this.modeFrontier = this.highlightFrontier = firstLine
  7289. var start = Pos(firstLine, 0)
  7290. this.sel = simpleSelection(start)
  7291. this.history = new History(null)
  7292. this.id = ++nextDocId
  7293. this.modeOption = mode
  7294. this.lineSep = lineSep
  7295. this.direction = direction == 'rtl' ? 'rtl' : 'ltr'
  7296. this.extend = false
  7297. if (typeof text == 'string') {
  7298. text = this.splitLines(text)
  7299. }
  7300. updateDoc(this, { from: start, to: start, text: text })
  7301. setSelection(this, simpleSelection(start), sel_dontScroll)
  7302. }
  7303. Doc.prototype = createObj(BranchChunk.prototype, {
  7304. constructor: Doc,
  7305. // Iterate over the document. Supports two forms -- with only one
  7306. // argument, it calls that for each line in the document. With
  7307. // three, it iterates over the range given by the first two (with
  7308. // the second being non-inclusive).
  7309. iter: function (from, to, op) {
  7310. if (op) {
  7311. this.iterN(from - this.first, to - from, op)
  7312. } else {
  7313. this.iterN(this.first, this.first + this.size, from)
  7314. }
  7315. },
  7316. // Non-public interface for adding and removing lines.
  7317. insert: function (at, lines) {
  7318. var height = 0
  7319. for (var i = 0; i < lines.length; ++i) {
  7320. height += lines[i].height
  7321. }
  7322. this.insertInner(at - this.first, lines, height)
  7323. },
  7324. remove: function (at, n) {
  7325. this.removeInner(at - this.first, n)
  7326. },
  7327. // From here, the methods are part of the public interface. Most
  7328. // are also available from CodeMirror (editor) instances.
  7329. getValue: function (lineSep) {
  7330. var lines = getLines(this, this.first, this.first + this.size)
  7331. if (lineSep === false) {
  7332. return lines
  7333. }
  7334. return lines.join(lineSep || this.lineSeparator())
  7335. },
  7336. setValue: docMethodOp(function (code) {
  7337. var top = Pos(this.first, 0),
  7338. last = this.first + this.size - 1
  7339. makeChange(this, { from: top, to: Pos(last, getLine(this, last).text.length), text: this.splitLines(code), origin: 'setValue', full: true }, true)
  7340. if (this.cm) {
  7341. scrollToCoords(this.cm, 0, 0)
  7342. }
  7343. setSelection(this, simpleSelection(top), sel_dontScroll)
  7344. }),
  7345. replaceRange: function (code, from, to, origin) {
  7346. from = clipPos(this, from)
  7347. to = to ? clipPos(this, to) : from
  7348. replaceRange(this, code, from, to, origin)
  7349. },
  7350. getRange: function (from, to, lineSep) {
  7351. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  7352. if (lineSep === false) {
  7353. return lines
  7354. }
  7355. if (lineSep === '') {
  7356. return lines.join('')
  7357. }
  7358. return lines.join(lineSep || this.lineSeparator())
  7359. },
  7360. getLine: function (line) {
  7361. var l = this.getLineHandle(line)
  7362. return l && l.text
  7363. },
  7364. getLineHandle: function (line) {
  7365. if (isLine(this, line)) {
  7366. return getLine(this, line)
  7367. }
  7368. },
  7369. getLineNumber: function (line) {
  7370. return lineNo(line)
  7371. },
  7372. getLineHandleVisualStart: function (line) {
  7373. if (typeof line == 'number') {
  7374. line = getLine(this, line)
  7375. }
  7376. return visualLine(line)
  7377. },
  7378. lineCount: function () {
  7379. return this.size
  7380. },
  7381. firstLine: function () {
  7382. return this.first
  7383. },
  7384. lastLine: function () {
  7385. return this.first + this.size - 1
  7386. },
  7387. clipPos: function (pos) {
  7388. return clipPos(this, pos)
  7389. },
  7390. getCursor: function (start) {
  7391. var range = this.sel.primary(),
  7392. pos
  7393. if (start == null || start == 'head') {
  7394. pos = range.head
  7395. } else if (start == 'anchor') {
  7396. pos = range.anchor
  7397. } else if (start == 'end' || start == 'to' || start === false) {
  7398. pos = range.to()
  7399. } else {
  7400. pos = range.from()
  7401. }
  7402. return pos
  7403. },
  7404. listSelections: function () {
  7405. return this.sel.ranges
  7406. },
  7407. somethingSelected: function () {
  7408. return this.sel.somethingSelected()
  7409. },
  7410. setCursor: docMethodOp(function (line, ch, options) {
  7411. setSimpleSelection(this, clipPos(this, typeof line == 'number' ? Pos(line, ch || 0) : line), null, options)
  7412. }),
  7413. setSelection: docMethodOp(function (anchor, head, options) {
  7414. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  7415. }),
  7416. extendSelection: docMethodOp(function (head, other, options) {
  7417. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  7418. }),
  7419. extendSelections: docMethodOp(function (heads, options) {
  7420. extendSelections(this, clipPosArray(this, heads), options)
  7421. }),
  7422. extendSelectionsBy: docMethodOp(function (f, options) {
  7423. var heads = map(this.sel.ranges, f)
  7424. extendSelections(this, clipPosArray(this, heads), options)
  7425. }),
  7426. setSelections: docMethodOp(function (ranges, primary, options) {
  7427. if (!ranges.length) {
  7428. return
  7429. }
  7430. var out = []
  7431. for (var i = 0; i < ranges.length; i++) {
  7432. out[i] = new Range(clipPos(this, ranges[i].anchor), clipPos(this, ranges[i].head || ranges[i].anchor))
  7433. }
  7434. if (primary == null) {
  7435. primary = Math.min(ranges.length - 1, this.sel.primIndex)
  7436. }
  7437. setSelection(this, normalizeSelection(this.cm, out, primary), options)
  7438. }),
  7439. addSelection: docMethodOp(function (anchor, head, options) {
  7440. var ranges = this.sel.ranges.slice(0)
  7441. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  7442. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options)
  7443. }),
  7444. getSelection: function (lineSep) {
  7445. var ranges = this.sel.ranges,
  7446. lines
  7447. for (var i = 0; i < ranges.length; i++) {
  7448. var sel = getBetween(this, ranges[i].from(), ranges[i].to())
  7449. lines = lines ? lines.concat(sel) : sel
  7450. }
  7451. if (lineSep === false) {
  7452. return lines
  7453. } else {
  7454. return lines.join(lineSep || this.lineSeparator())
  7455. }
  7456. },
  7457. getSelections: function (lineSep) {
  7458. var parts = [],
  7459. ranges = this.sel.ranges
  7460. for (var i = 0; i < ranges.length; i++) {
  7461. var sel = getBetween(this, ranges[i].from(), ranges[i].to())
  7462. if (lineSep !== false) {
  7463. sel = sel.join(lineSep || this.lineSeparator())
  7464. }
  7465. parts[i] = sel
  7466. }
  7467. return parts
  7468. },
  7469. replaceSelection: function (code, collapse, origin) {
  7470. var dup = []
  7471. for (var i = 0; i < this.sel.ranges.length; i++) {
  7472. dup[i] = code
  7473. }
  7474. this.replaceSelections(dup, collapse, origin || '+input')
  7475. },
  7476. replaceSelections: docMethodOp(function (code, collapse, origin) {
  7477. var changes = [],
  7478. sel = this.sel
  7479. for (var i = 0; i < sel.ranges.length; i++) {
  7480. var range = sel.ranges[i]
  7481. changes[i] = { from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin }
  7482. }
  7483. var newSel = collapse && collapse != 'end' && computeReplacedSel(this, changes, collapse)
  7484. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) {
  7485. makeChange(this, changes[i$1])
  7486. }
  7487. if (newSel) {
  7488. setSelectionReplaceHistory(this, newSel)
  7489. } else if (this.cm) {
  7490. ensureCursorVisible(this.cm)
  7491. }
  7492. }),
  7493. undo: docMethodOp(function () {
  7494. makeChangeFromHistory(this, 'undo')
  7495. }),
  7496. redo: docMethodOp(function () {
  7497. makeChangeFromHistory(this, 'redo')
  7498. }),
  7499. undoSelection: docMethodOp(function () {
  7500. makeChangeFromHistory(this, 'undo', true)
  7501. }),
  7502. redoSelection: docMethodOp(function () {
  7503. makeChangeFromHistory(this, 'redo', true)
  7504. }),
  7505. setExtending: function (val) {
  7506. this.extend = val
  7507. },
  7508. getExtending: function () {
  7509. return this.extend
  7510. },
  7511. historySize: function () {
  7512. var hist = this.history,
  7513. done = 0,
  7514. undone = 0
  7515. for (var i = 0; i < hist.done.length; i++) {
  7516. if (!hist.done[i].ranges) {
  7517. ++done
  7518. }
  7519. }
  7520. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) {
  7521. if (!hist.undone[i$1].ranges) {
  7522. ++undone
  7523. }
  7524. }
  7525. return { undo: done, redo: undone }
  7526. },
  7527. clearHistory: function () {
  7528. var this$1 = this
  7529. this.history = new History(this.history)
  7530. linkedDocs(
  7531. this,
  7532. function (doc) {
  7533. return (doc.history = this$1.history)
  7534. },
  7535. true
  7536. )
  7537. },
  7538. markClean: function () {
  7539. this.cleanGeneration = this.changeGeneration(true)
  7540. },
  7541. changeGeneration: function (forceSplit) {
  7542. if (forceSplit) {
  7543. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null
  7544. }
  7545. return this.history.generation
  7546. },
  7547. isClean: function (gen) {
  7548. return this.history.generation == (gen || this.cleanGeneration)
  7549. },
  7550. getHistory: function () {
  7551. return { done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone) }
  7552. },
  7553. setHistory: function (histData) {
  7554. var hist = (this.history = new History(this.history))
  7555. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  7556. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  7557. },
  7558. setGutterMarker: docMethodOp(function (line, gutterID, value) {
  7559. return changeLine(this, line, 'gutter', function (line) {
  7560. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  7561. markers[gutterID] = value
  7562. if (!value && isEmpty(markers)) {
  7563. line.gutterMarkers = null
  7564. }
  7565. return true
  7566. })
  7567. }),
  7568. clearGutter: docMethodOp(function (gutterID) {
  7569. var this$1 = this
  7570. this.iter(function (line) {
  7571. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  7572. changeLine(this$1, line, 'gutter', function () {
  7573. line.gutterMarkers[gutterID] = null
  7574. if (isEmpty(line.gutterMarkers)) {
  7575. line.gutterMarkers = null
  7576. }
  7577. return true
  7578. })
  7579. }
  7580. })
  7581. }),
  7582. lineInfo: function (line) {
  7583. var n
  7584. if (typeof line == 'number') {
  7585. if (!isLine(this, line)) {
  7586. return null
  7587. }
  7588. n = line
  7589. line = getLine(this, line)
  7590. if (!line) {
  7591. return null
  7592. }
  7593. } else {
  7594. n = lineNo(line)
  7595. if (n == null) {
  7596. return null
  7597. }
  7598. }
  7599. return { line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets }
  7600. },
  7601. addLineClass: docMethodOp(function (handle, where, cls) {
  7602. return changeLine(this, handle, where == 'gutter' ? 'gutter' : 'class', function (line) {
  7603. var prop = where == 'text' ? 'textClass' : where == 'background' ? 'bgClass' : where == 'gutter' ? 'gutterClass' : 'wrapClass'
  7604. if (!line[prop]) {
  7605. line[prop] = cls
  7606. } else if (classTest(cls).test(line[prop])) {
  7607. return false
  7608. } else {
  7609. line[prop] += ' ' + cls
  7610. }
  7611. return true
  7612. })
  7613. }),
  7614. removeLineClass: docMethodOp(function (handle, where, cls) {
  7615. return changeLine(this, handle, where == 'gutter' ? 'gutter' : 'class', function (line) {
  7616. var prop = where == 'text' ? 'textClass' : where == 'background' ? 'bgClass' : where == 'gutter' ? 'gutterClass' : 'wrapClass'
  7617. var cur = line[prop]
  7618. if (!cur) {
  7619. return false
  7620. } else if (cls == null) {
  7621. line[prop] = null
  7622. } else {
  7623. var found = cur.match(classTest(cls))
  7624. if (!found) {
  7625. return false
  7626. }
  7627. var end = found.index + found[0].length
  7628. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? '' : ' ') + cur.slice(end) || null
  7629. }
  7630. return true
  7631. })
  7632. }),
  7633. addLineWidget: docMethodOp(function (handle, node, options) {
  7634. return addLineWidget(this, handle, node, options)
  7635. }),
  7636. removeLineWidget: function (widget) {
  7637. widget.clear()
  7638. },
  7639. markText: function (from, to, options) {
  7640. return markText(this, clipPos(this, from), clipPos(this, to), options, (options && options.type) || 'range')
  7641. },
  7642. setBookmark: function (pos, options) {
  7643. var realOpts = {
  7644. replacedWith: options && (options.nodeType == null ? options.widget : options),
  7645. insertLeft: options && options.insertLeft,
  7646. clearWhenEmpty: false,
  7647. shared: options && options.shared,
  7648. handleMouseEvents: options && options.handleMouseEvents,
  7649. }
  7650. pos = clipPos(this, pos)
  7651. return markText(this, pos, pos, realOpts, 'bookmark')
  7652. },
  7653. findMarksAt: function (pos) {
  7654. pos = clipPos(this, pos)
  7655. var markers = [],
  7656. spans = getLine(this, pos.line).markedSpans
  7657. if (spans) {
  7658. for (var i = 0; i < spans.length; ++i) {
  7659. var span = spans[i]
  7660. if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) {
  7661. markers.push(span.marker.parent || span.marker)
  7662. }
  7663. }
  7664. }
  7665. return markers
  7666. },
  7667. findMarks: function (from, to, filter) {
  7668. from = clipPos(this, from)
  7669. to = clipPos(this, to)
  7670. var found = [],
  7671. lineNo = from.line
  7672. this.iter(from.line, to.line + 1, function (line) {
  7673. var spans = line.markedSpans
  7674. if (spans) {
  7675. for (var i = 0; i < spans.length; i++) {
  7676. var span = spans[i]
  7677. if (
  7678. !(
  7679. (span.to != null && lineNo == from.line && from.ch >= span.to) ||
  7680. (span.from == null && lineNo != from.line) ||
  7681. (span.from != null && lineNo == to.line && span.from >= to.ch)
  7682. ) &&
  7683. (!filter || filter(span.marker))
  7684. ) {
  7685. found.push(span.marker.parent || span.marker)
  7686. }
  7687. }
  7688. }
  7689. ++lineNo
  7690. })
  7691. return found
  7692. },
  7693. getAllMarks: function () {
  7694. var markers = []
  7695. this.iter(function (line) {
  7696. var sps = line.markedSpans
  7697. if (sps) {
  7698. for (var i = 0; i < sps.length; ++i) {
  7699. if (sps[i].from != null) {
  7700. markers.push(sps[i].marker)
  7701. }
  7702. }
  7703. }
  7704. })
  7705. return markers
  7706. },
  7707. posFromIndex: function (off) {
  7708. var ch,
  7709. lineNo = this.first,
  7710. sepSize = this.lineSeparator().length
  7711. this.iter(function (line) {
  7712. var sz = line.text.length + sepSize
  7713. if (sz > off) {
  7714. ch = off
  7715. return true
  7716. }
  7717. off -= sz
  7718. ++lineNo
  7719. })
  7720. return clipPos(this, Pos(lineNo, ch))
  7721. },
  7722. indexFromPos: function (coords) {
  7723. coords = clipPos(this, coords)
  7724. var index = coords.ch
  7725. if (coords.line < this.first || coords.ch < 0) {
  7726. return 0
  7727. }
  7728. var sepSize = this.lineSeparator().length
  7729. this.iter(this.first, coords.line, function (line) {
  7730. // iter aborts when callback returns a truthy value
  7731. index += line.text.length + sepSize
  7732. })
  7733. return index
  7734. },
  7735. copy: function (copyHistory) {
  7736. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction)
  7737. doc.scrollTop = this.scrollTop
  7738. doc.scrollLeft = this.scrollLeft
  7739. doc.sel = this.sel
  7740. doc.extend = false
  7741. if (copyHistory) {
  7742. doc.history.undoDepth = this.history.undoDepth
  7743. doc.setHistory(this.getHistory())
  7744. }
  7745. return doc
  7746. },
  7747. linkedDoc: function (options) {
  7748. if (!options) {
  7749. options = {}
  7750. }
  7751. var from = this.first,
  7752. to = this.first + this.size
  7753. if (options.from != null && options.from > from) {
  7754. from = options.from
  7755. }
  7756. if (options.to != null && options.to < to) {
  7757. to = options.to
  7758. }
  7759. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction)
  7760. if (options.sharedHist) {
  7761. copy.history = this.history
  7762. }
  7763. ;(this.linked || (this.linked = [])).push({ doc: copy, sharedHist: options.sharedHist })
  7764. copy.linked = [{ doc: this, isParent: true, sharedHist: options.sharedHist }]
  7765. copySharedMarkers(copy, findSharedMarkers(this))
  7766. return copy
  7767. },
  7768. unlinkDoc: function (other) {
  7769. if (other instanceof CodeMirror) {
  7770. other = other.doc
  7771. }
  7772. if (this.linked) {
  7773. for (var i = 0; i < this.linked.length; ++i) {
  7774. var link = this.linked[i]
  7775. if (link.doc != other) {
  7776. continue
  7777. }
  7778. this.linked.splice(i, 1)
  7779. other.unlinkDoc(this)
  7780. detachSharedMarkers(findSharedMarkers(this))
  7781. break
  7782. }
  7783. }
  7784. // If the histories were shared, split them again
  7785. if (other.history == this.history) {
  7786. var splitIds = [other.id]
  7787. linkedDocs(
  7788. other,
  7789. function (doc) {
  7790. return splitIds.push(doc.id)
  7791. },
  7792. true
  7793. )
  7794. other.history = new History(null)
  7795. other.history.done = copyHistoryArray(this.history.done, splitIds)
  7796. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  7797. }
  7798. },
  7799. iterLinkedDocs: function (f) {
  7800. linkedDocs(this, f)
  7801. },
  7802. getMode: function () {
  7803. return this.mode
  7804. },
  7805. getEditor: function () {
  7806. return this.cm
  7807. },
  7808. splitLines: function (str) {
  7809. if (this.lineSep) {
  7810. return str.split(this.lineSep)
  7811. }
  7812. return splitLinesAuto(str)
  7813. },
  7814. lineSeparator: function () {
  7815. return this.lineSep || '\n'
  7816. },
  7817. setDirection: docMethodOp(function (dir) {
  7818. if (dir != 'rtl') {
  7819. dir = 'ltr'
  7820. }
  7821. if (dir == this.direction) {
  7822. return
  7823. }
  7824. this.direction = dir
  7825. this.iter(function (line) {
  7826. return (line.order = null)
  7827. })
  7828. if (this.cm) {
  7829. directionChanged(this.cm)
  7830. }
  7831. }),
  7832. })
  7833. // Public alias.
  7834. Doc.prototype.eachLine = Doc.prototype.iter
  7835. // Kludge to work around strange IE behavior where it'll sometimes
  7836. // re-fire a series of drag-related events right after the drop (#1551)
  7837. var lastDrop = 0
  7838. function onDrop(e) {
  7839. var cm = this
  7840. clearDragCursor(cm)
  7841. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
  7842. return
  7843. }
  7844. e_preventDefault(e)
  7845. if (ie) {
  7846. lastDrop = +new Date()
  7847. }
  7848. var pos = posFromMouse(cm, e, true),
  7849. files = e.dataTransfer.files
  7850. if (!pos || cm.isReadOnly()) {
  7851. return
  7852. }
  7853. // Might be a file drop, in which case we simply extract the text
  7854. // and insert it.
  7855. if (files && files.length && window.FileReader && window.File) {
  7856. var n = files.length,
  7857. text = Array(n),
  7858. read = 0
  7859. var markAsReadAndPasteIfAllFilesAreRead = function () {
  7860. if (++read == n) {
  7861. operation(cm, function () {
  7862. pos = clipPos(cm.doc, pos)
  7863. var change = {
  7864. from: pos,
  7865. to: pos,
  7866. text: cm.doc.splitLines(
  7867. text
  7868. .filter(function (t) {
  7869. return t != null
  7870. })
  7871. .join(cm.doc.lineSeparator())
  7872. ),
  7873. origin: 'paste',
  7874. }
  7875. makeChange(cm.doc, change)
  7876. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))))
  7877. })()
  7878. }
  7879. }
  7880. var readTextFromFile = function (file, i) {
  7881. if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  7882. markAsReadAndPasteIfAllFilesAreRead()
  7883. return
  7884. }
  7885. var reader = new FileReader()
  7886. reader.onerror = function () {
  7887. return markAsReadAndPasteIfAllFilesAreRead()
  7888. }
  7889. reader.onload = function () {
  7890. var content = reader.result
  7891. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  7892. markAsReadAndPasteIfAllFilesAreRead()
  7893. return
  7894. }
  7895. text[i] = content
  7896. markAsReadAndPasteIfAllFilesAreRead()
  7897. }
  7898. reader.readAsText(file)
  7899. }
  7900. for (var i = 0; i < files.length; i++) {
  7901. readTextFromFile(files[i], i)
  7902. }
  7903. } else {
  7904. // Normal drop
  7905. // Don't do a replace if the drop happened inside of the selected text.
  7906. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  7907. cm.state.draggingText(e)
  7908. // Ensure the editor is re-focused
  7909. setTimeout(function () {
  7910. return cm.display.input.focus()
  7911. }, 20)
  7912. return
  7913. }
  7914. try {
  7915. var text$1 = e.dataTransfer.getData('Text')
  7916. if (text$1) {
  7917. var selected
  7918. if (cm.state.draggingText && !cm.state.draggingText.copy) {
  7919. selected = cm.listSelections()
  7920. }
  7921. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  7922. if (selected) {
  7923. for (var i$1 = 0; i$1 < selected.length; ++i$1) {
  7924. replaceRange(cm.doc, '', selected[i$1].anchor, selected[i$1].head, 'drag')
  7925. }
  7926. }
  7927. cm.replaceSelection(text$1, 'around', 'paste')
  7928. cm.display.input.focus()
  7929. }
  7930. } catch (e$1) {}
  7931. }
  7932. }
  7933. function onDragStart(cm, e) {
  7934. if (ie && (!cm.state.draggingText || +new Date() - lastDrop < 100)) {
  7935. e_stop(e)
  7936. return
  7937. }
  7938. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
  7939. return
  7940. }
  7941. e.dataTransfer.setData('Text', cm.getSelection())
  7942. e.dataTransfer.effectAllowed = 'copyMove'
  7943. // Use dummy image instead of default browsers image.
  7944. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  7945. if (e.dataTransfer.setDragImage && !safari) {
  7946. var img = elt('img', null, null, 'position: fixed; left: 0; top: 0;')
  7947. img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='
  7948. if (presto) {
  7949. img.width = img.height = 1
  7950. cm.display.wrapper.appendChild(img)
  7951. // Force a relayout, or Opera won't use our image for some obscure reason
  7952. img._top = img.offsetTop
  7953. }
  7954. e.dataTransfer.setDragImage(img, 0, 0)
  7955. if (presto) {
  7956. img.parentNode.removeChild(img)
  7957. }
  7958. }
  7959. }
  7960. function onDragOver(cm, e) {
  7961. var pos = posFromMouse(cm, e)
  7962. if (!pos) {
  7963. return
  7964. }
  7965. var frag = document.createDocumentFragment()
  7966. drawSelectionCursor(cm, pos, frag)
  7967. if (!cm.display.dragCursor) {
  7968. cm.display.dragCursor = elt('div', null, 'CodeMirror-cursors CodeMirror-dragcursors')
  7969. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  7970. }
  7971. removeChildrenAndAdd(cm.display.dragCursor, frag)
  7972. }
  7973. function clearDragCursor(cm) {
  7974. if (cm.display.dragCursor) {
  7975. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  7976. cm.display.dragCursor = null
  7977. }
  7978. }
  7979. // These must be handled carefully, because naively registering a
  7980. // handler for each editor will cause the editors to never be
  7981. // garbage collected.
  7982. function forEachCodeMirror(f) {
  7983. if (!document.getElementsByClassName) {
  7984. return
  7985. }
  7986. var byClass = document.getElementsByClassName('CodeMirror'),
  7987. editors = []
  7988. for (var i = 0; i < byClass.length; i++) {
  7989. var cm = byClass[i].CodeMirror
  7990. if (cm) {
  7991. editors.push(cm)
  7992. }
  7993. }
  7994. if (editors.length) {
  7995. editors[0].operation(function () {
  7996. for (var i = 0; i < editors.length; i++) {
  7997. f(editors[i])
  7998. }
  7999. })
  8000. }
  8001. }
  8002. var globalsRegistered = false
  8003. function ensureGlobalHandlers() {
  8004. if (globalsRegistered) {
  8005. return
  8006. }
  8007. registerGlobalHandlers()
  8008. globalsRegistered = true
  8009. }
  8010. function registerGlobalHandlers() {
  8011. // When the window resizes, we need to refresh active editors.
  8012. var resizeTimer
  8013. on(window, 'resize', function () {
  8014. if (resizeTimer == null) {
  8015. resizeTimer = setTimeout(function () {
  8016. resizeTimer = null
  8017. forEachCodeMirror(onResize)
  8018. }, 100)
  8019. }
  8020. })
  8021. // When the window loses focus, we want to show the editor as blurred
  8022. on(window, 'blur', function () {
  8023. return forEachCodeMirror(onBlur)
  8024. })
  8025. }
  8026. // Called when the window resizes
  8027. function onResize(cm) {
  8028. var d = cm.display
  8029. // Might be a text scaling operation, clear size caches.
  8030. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  8031. d.scrollbarsClipped = false
  8032. cm.setSize()
  8033. }
  8034. var keyNames = {
  8035. 3: 'Pause',
  8036. 8: 'Backspace',
  8037. 9: 'Tab',
  8038. 13: 'Enter',
  8039. 16: 'Shift',
  8040. 17: 'Ctrl',
  8041. 18: 'Alt',
  8042. 19: 'Pause',
  8043. 20: 'CapsLock',
  8044. 27: 'Esc',
  8045. 32: 'Space',
  8046. 33: 'PageUp',
  8047. 34: 'PageDown',
  8048. 35: 'End',
  8049. 36: 'Home',
  8050. 37: 'Left',
  8051. 38: 'Up',
  8052. 39: 'Right',
  8053. 40: 'Down',
  8054. 44: 'PrintScrn',
  8055. 45: 'Insert',
  8056. 46: 'Delete',
  8057. 59: ';',
  8058. 61: '=',
  8059. 91: 'Mod',
  8060. 92: 'Mod',
  8061. 93: 'Mod',
  8062. 106: '*',
  8063. 107: '=',
  8064. 109: '-',
  8065. 110: '.',
  8066. 111: '/',
  8067. 145: 'ScrollLock',
  8068. 173: '-',
  8069. 186: ';',
  8070. 187: '=',
  8071. 188: ',',
  8072. 189: '-',
  8073. 190: '.',
  8074. 191: '/',
  8075. 192: '`',
  8076. 219: '[',
  8077. 220: '\\',
  8078. 221: ']',
  8079. 222: "'",
  8080. 224: 'Mod',
  8081. 63232: 'Up',
  8082. 63233: 'Down',
  8083. 63234: 'Left',
  8084. 63235: 'Right',
  8085. 63272: 'Delete',
  8086. 63273: 'Home',
  8087. 63275: 'End',
  8088. 63276: 'PageUp',
  8089. 63277: 'PageDown',
  8090. 63302: 'Insert',
  8091. }
  8092. // Number keys
  8093. for (var i = 0; i < 10; i++) {
  8094. keyNames[i + 48] = keyNames[i + 96] = String(i)
  8095. }
  8096. // Alphabetic keys
  8097. for (var i$1 = 65; i$1 <= 90; i$1++) {
  8098. keyNames[i$1] = String.fromCharCode(i$1)
  8099. }
  8100. // Function keys
  8101. for (var i$2 = 1; i$2 <= 12; i$2++) {
  8102. keyNames[i$2 + 111] = keyNames[i$2 + 63235] = 'F' + i$2
  8103. }
  8104. var keyMap = {}
  8105. keyMap.basic = {
  8106. Left: 'goCharLeft',
  8107. Right: 'goCharRight',
  8108. Up: 'goLineUp',
  8109. Down: 'goLineDown',
  8110. End: 'goLineEnd',
  8111. Home: 'goLineStartSmart',
  8112. PageUp: 'goPageUp',
  8113. PageDown: 'goPageDown',
  8114. Delete: 'delCharAfter',
  8115. Backspace: 'delCharBefore',
  8116. 'Shift-Backspace': 'delCharBefore',
  8117. Tab: 'defaultTab',
  8118. 'Shift-Tab': 'indentAuto',
  8119. Enter: 'newlineAndIndent',
  8120. Insert: 'toggleOverwrite',
  8121. Esc: 'singleSelection',
  8122. }
  8123. // Note that the save and find-related commands aren't defined by
  8124. // default. User code or addons can define them. Unknown commands
  8125. // are simply ignored.
  8126. keyMap.pcDefault = {
  8127. 'Ctrl-A': 'selectAll',
  8128. 'Ctrl-D': 'deleteLine',
  8129. 'Ctrl-Z': 'undo',
  8130. 'Shift-Ctrl-Z': 'redo',
  8131. 'Ctrl-Y': 'redo',
  8132. 'Ctrl-Home': 'goDocStart',
  8133. 'Ctrl-End': 'goDocEnd',
  8134. 'Ctrl-Up': 'goLineUp',
  8135. 'Ctrl-Down': 'goLineDown',
  8136. 'Ctrl-Left': 'goGroupLeft',
  8137. 'Ctrl-Right': 'goGroupRight',
  8138. 'Alt-Left': 'goLineStart',
  8139. 'Alt-Right': 'goLineEnd',
  8140. 'Ctrl-Backspace': 'delGroupBefore',
  8141. 'Ctrl-Delete': 'delGroupAfter',
  8142. 'Ctrl-S': 'save',
  8143. 'Ctrl-F': 'find',
  8144. 'Ctrl-G': 'findNext',
  8145. 'Shift-Ctrl-G': 'findPrev',
  8146. 'Shift-Ctrl-F': 'replace',
  8147. 'Shift-Ctrl-R': 'replaceAll',
  8148. 'Ctrl-[': 'indentLess',
  8149. 'Ctrl-]': 'indentMore',
  8150. 'Ctrl-U': 'undoSelection',
  8151. 'Shift-Ctrl-U': 'redoSelection',
  8152. 'Alt-U': 'redoSelection',
  8153. fallthrough: 'basic',
  8154. }
  8155. // Very basic readline/emacs-style bindings, which are standard on Mac.
  8156. keyMap.emacsy = {
  8157. 'Ctrl-F': 'goCharRight',
  8158. 'Ctrl-B': 'goCharLeft',
  8159. 'Ctrl-P': 'goLineUp',
  8160. 'Ctrl-N': 'goLineDown',
  8161. 'Ctrl-A': 'goLineStart',
  8162. 'Ctrl-E': 'goLineEnd',
  8163. 'Ctrl-V': 'goPageDown',
  8164. 'Shift-Ctrl-V': 'goPageUp',
  8165. 'Ctrl-D': 'delCharAfter',
  8166. 'Ctrl-H': 'delCharBefore',
  8167. 'Alt-Backspace': 'delWordBefore',
  8168. 'Ctrl-K': 'killLine',
  8169. 'Ctrl-T': 'transposeChars',
  8170. 'Ctrl-O': 'openLine',
  8171. }
  8172. keyMap.macDefault = {
  8173. 'Cmd-A': 'selectAll',
  8174. 'Cmd-D': 'deleteLine',
  8175. 'Cmd-Z': 'undo',
  8176. 'Shift-Cmd-Z': 'redo',
  8177. 'Cmd-Y': 'redo',
  8178. 'Cmd-Home': 'goDocStart',
  8179. 'Cmd-Up': 'goDocStart',
  8180. 'Cmd-End': 'goDocEnd',
  8181. 'Cmd-Down': 'goDocEnd',
  8182. 'Alt-Left': 'goGroupLeft',
  8183. 'Alt-Right': 'goGroupRight',
  8184. 'Cmd-Left': 'goLineLeft',
  8185. 'Cmd-Right': 'goLineRight',
  8186. 'Alt-Backspace': 'delGroupBefore',
  8187. 'Ctrl-Alt-Backspace': 'delGroupAfter',
  8188. 'Alt-Delete': 'delGroupAfter',
  8189. 'Cmd-S': 'save',
  8190. 'Cmd-F': 'find',
  8191. 'Cmd-G': 'findNext',
  8192. 'Shift-Cmd-G': 'findPrev',
  8193. 'Cmd-Alt-F': 'replace',
  8194. 'Shift-Cmd-Alt-F': 'replaceAll',
  8195. 'Cmd-[': 'indentLess',
  8196. 'Cmd-]': 'indentMore',
  8197. 'Cmd-Backspace': 'delWrappedLineLeft',
  8198. 'Cmd-Delete': 'delWrappedLineRight',
  8199. 'Cmd-U': 'undoSelection',
  8200. 'Shift-Cmd-U': 'redoSelection',
  8201. 'Ctrl-Up': 'goDocStart',
  8202. 'Ctrl-Down': 'goDocEnd',
  8203. fallthrough: ['basic', 'emacsy'],
  8204. }
  8205. keyMap['default'] = mac ? keyMap.macDefault : keyMap.pcDefault
  8206. // KEYMAP DISPATCH
  8207. function normalizeKeyName(name) {
  8208. var parts = name.split(/-(?!$)/)
  8209. name = parts[parts.length - 1]
  8210. var alt, ctrl, shift, cmd
  8211. for (var i = 0; i < parts.length - 1; i++) {
  8212. var mod = parts[i]
  8213. if (/^(cmd|meta|m)$/i.test(mod)) {
  8214. cmd = true
  8215. } else if (/^a(lt)?$/i.test(mod)) {
  8216. alt = true
  8217. } else if (/^(c|ctrl|control)$/i.test(mod)) {
  8218. ctrl = true
  8219. } else if (/^s(hift)?$/i.test(mod)) {
  8220. shift = true
  8221. } else {
  8222. throw new Error('Unrecognized modifier name: ' + mod)
  8223. }
  8224. }
  8225. if (alt) {
  8226. name = 'Alt-' + name
  8227. }
  8228. if (ctrl) {
  8229. name = 'Ctrl-' + name
  8230. }
  8231. if (cmd) {
  8232. name = 'Cmd-' + name
  8233. }
  8234. if (shift) {
  8235. name = 'Shift-' + name
  8236. }
  8237. return name
  8238. }
  8239. // This is a kludge to keep keymaps mostly working as raw objects
  8240. // (backwards compatibility) while at the same time support features
  8241. // like normalization and multi-stroke key bindings. It compiles a
  8242. // new normalized keymap, and then updates the old object to reflect
  8243. // this.
  8244. function normalizeKeyMap(keymap) {
  8245. var copy = {}
  8246. for (var keyname in keymap) {
  8247. if (keymap.hasOwnProperty(keyname)) {
  8248. var value = keymap[keyname]
  8249. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) {
  8250. continue
  8251. }
  8252. if (value == '...') {
  8253. delete keymap[keyname]
  8254. continue
  8255. }
  8256. var keys = map(keyname.split(' '), normalizeKeyName)
  8257. for (var i = 0; i < keys.length; i++) {
  8258. var val = void 0,
  8259. name = void 0
  8260. if (i == keys.length - 1) {
  8261. name = keys.join(' ')
  8262. val = value
  8263. } else {
  8264. name = keys.slice(0, i + 1).join(' ')
  8265. val = '...'
  8266. }
  8267. var prev = copy[name]
  8268. if (!prev) {
  8269. copy[name] = val
  8270. } else if (prev != val) {
  8271. throw new Error('Inconsistent bindings for ' + name)
  8272. }
  8273. }
  8274. delete keymap[keyname]
  8275. }
  8276. }
  8277. for (var prop in copy) {
  8278. keymap[prop] = copy[prop]
  8279. }
  8280. return keymap
  8281. }
  8282. function lookupKey(key, map, handle, context) {
  8283. map = getKeyMap(map)
  8284. var found = map.call ? map.call(key, context) : map[key]
  8285. if (found === false) {
  8286. return 'nothing'
  8287. }
  8288. if (found === '...') {
  8289. return 'multi'
  8290. }
  8291. if (found != null && handle(found)) {
  8292. return 'handled'
  8293. }
  8294. if (map.fallthrough) {
  8295. if (Object.prototype.toString.call(map.fallthrough) != '[object Array]') {
  8296. return lookupKey(key, map.fallthrough, handle, context)
  8297. }
  8298. for (var i = 0; i < map.fallthrough.length; i++) {
  8299. var result = lookupKey(key, map.fallthrough[i], handle, context)
  8300. if (result) {
  8301. return result
  8302. }
  8303. }
  8304. }
  8305. }
  8306. // Modifier key presses don't count as 'real' key presses for the
  8307. // purpose of keymap fallthrough.
  8308. function isModifierKey(value) {
  8309. var name = typeof value == 'string' ? value : keyNames[value.keyCode]
  8310. return name == 'Ctrl' || name == 'Alt' || name == 'Shift' || name == 'Mod'
  8311. }
  8312. function addModifierNames(name, event, noShift) {
  8313. var base = name
  8314. if (event.altKey && base != 'Alt') {
  8315. name = 'Alt-' + name
  8316. }
  8317. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != 'Ctrl') {
  8318. name = 'Ctrl-' + name
  8319. }
  8320. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != 'Mod') {
  8321. name = 'Cmd-' + name
  8322. }
  8323. if (!noShift && event.shiftKey && base != 'Shift') {
  8324. name = 'Shift-' + name
  8325. }
  8326. return name
  8327. }
  8328. // Look up the name of a key as indicated by an event object.
  8329. function keyName(event, noShift) {
  8330. if (presto && event.keyCode == 34 && event['char']) {
  8331. return false
  8332. }
  8333. var name = keyNames[event.keyCode]
  8334. if (name == null || event.altGraphKey) {
  8335. return false
  8336. }
  8337. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  8338. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  8339. if (event.keyCode == 3 && event.code) {
  8340. name = event.code
  8341. }
  8342. return addModifierNames(name, event, noShift)
  8343. }
  8344. function getKeyMap(val) {
  8345. return typeof val == 'string' ? keyMap[val] : val
  8346. }
  8347. // Helper for deleting text near the selection(s), used to implement
  8348. // backspace, delete, and similar functionality.
  8349. function deleteNearSelection(cm, compute) {
  8350. var ranges = cm.doc.sel.ranges,
  8351. kill = []
  8352. // Build up a set of ranges to kill first, merging overlapping
  8353. // ranges.
  8354. for (var i = 0; i < ranges.length; i++) {
  8355. var toKill = compute(ranges[i])
  8356. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  8357. var replaced = kill.pop()
  8358. if (cmp(replaced.from, toKill.from) < 0) {
  8359. toKill.from = replaced.from
  8360. break
  8361. }
  8362. }
  8363. kill.push(toKill)
  8364. }
  8365. // Next, remove those actual ranges.
  8366. runInOp(cm, function () {
  8367. for (var i = kill.length - 1; i >= 0; i--) {
  8368. replaceRange(cm.doc, '', kill[i].from, kill[i].to, '+delete')
  8369. }
  8370. ensureCursorVisible(cm)
  8371. })
  8372. }
  8373. function moveCharLogically(line, ch, dir) {
  8374. var target = skipExtendingChars(line.text, ch + dir, dir)
  8375. return target < 0 || target > line.text.length ? null : target
  8376. }
  8377. function moveLogically(line, start, dir) {
  8378. var ch = moveCharLogically(line, start.ch, dir)
  8379. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? 'after' : 'before')
  8380. }
  8381. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  8382. if (visually) {
  8383. if (cm.doc.direction == 'rtl') {
  8384. dir = -dir
  8385. }
  8386. var order = getOrder(lineObj, cm.doc.direction)
  8387. if (order) {
  8388. var part = dir < 0 ? lst(order) : order[0]
  8389. var moveInStorageOrder = dir < 0 == (part.level == 1)
  8390. var sticky = moveInStorageOrder ? 'after' : 'before'
  8391. var ch
  8392. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  8393. // it could be that the last bidi part is not on the last visual line,
  8394. // since visual lines contain content order-consecutive chunks.
  8395. // Thus, in rtl, we are looking for the first (content-order) character
  8396. // in the rtl chunk that is on the last line (that is, the same line
  8397. // as the last (content-order) character).
  8398. if (part.level > 0 || cm.doc.direction == 'rtl') {
  8399. var prep = prepareMeasureForLine(cm, lineObj)
  8400. ch = dir < 0 ? lineObj.text.length - 1 : 0
  8401. var targetTop = measureCharPrepared(cm, prep, ch).top
  8402. ch = findFirst(
  8403. function (ch) {
  8404. return measureCharPrepared(cm, prep, ch).top == targetTop
  8405. },
  8406. dir < 0 == (part.level == 1) ? part.from : part.to - 1,
  8407. ch
  8408. )
  8409. if (sticky == 'before') {
  8410. ch = moveCharLogically(lineObj, ch, 1)
  8411. }
  8412. } else {
  8413. ch = dir < 0 ? part.to : part.from
  8414. }
  8415. return new Pos(lineNo, ch, sticky)
  8416. }
  8417. }
  8418. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? 'before' : 'after')
  8419. }
  8420. function moveVisually(cm, line, start, dir) {
  8421. var bidi = getOrder(line, cm.doc.direction)
  8422. if (!bidi) {
  8423. return moveLogically(line, start, dir)
  8424. }
  8425. if (start.ch >= line.text.length) {
  8426. start.ch = line.text.length
  8427. start.sticky = 'before'
  8428. } else if (start.ch <= 0) {
  8429. start.ch = 0
  8430. start.sticky = 'after'
  8431. }
  8432. var partPos = getBidiPartAt(bidi, start.ch, start.sticky),
  8433. part = bidi[partPos]
  8434. if (cm.doc.direction == 'ltr' && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  8435. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  8436. // nothing interesting happens.
  8437. return moveLogically(line, start, dir)
  8438. }
  8439. var mv = function (pos, dir) {
  8440. return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir)
  8441. }
  8442. var prep
  8443. var getWrappedLineExtent = function (ch) {
  8444. if (!cm.options.lineWrapping) {
  8445. return { begin: 0, end: line.text.length }
  8446. }
  8447. prep = prep || prepareMeasureForLine(cm, line)
  8448. return wrappedLineExtentChar(cm, line, prep, ch)
  8449. }
  8450. var wrappedLineExtent = getWrappedLineExtent(start.sticky == 'before' ? mv(start, -1) : start.ch)
  8451. if (cm.doc.direction == 'rtl' || part.level == 1) {
  8452. var moveInStorageOrder = (part.level == 1) == dir < 0
  8453. var ch = mv(start, moveInStorageOrder ? 1 : -1)
  8454. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  8455. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  8456. var sticky = moveInStorageOrder ? 'before' : 'after'
  8457. return new Pos(start.line, ch, sticky)
  8458. }
  8459. }
  8460. // Case 3: Could not move within this bidi part in this visual line, so leave
  8461. // the current bidi part
  8462. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  8463. var getRes = function (ch, moveInStorageOrder) {
  8464. return moveInStorageOrder ? new Pos(start.line, mv(ch, 1), 'before') : new Pos(start.line, ch, 'after')
  8465. }
  8466. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  8467. var part = bidi[partPos]
  8468. var moveInStorageOrder = dir > 0 == (part.level != 1)
  8469. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)
  8470. if (part.from <= ch && ch < part.to) {
  8471. return getRes(ch, moveInStorageOrder)
  8472. }
  8473. ch = moveInStorageOrder ? part.from : mv(part.to, -1)
  8474. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) {
  8475. return getRes(ch, moveInStorageOrder)
  8476. }
  8477. }
  8478. }
  8479. // Case 3a: Look for other bidi parts on the same visual line
  8480. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)
  8481. if (res) {
  8482. return res
  8483. }
  8484. // Case 3b: Look for other bidi parts on the next visual line
  8485. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)
  8486. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  8487. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))
  8488. if (res) {
  8489. return res
  8490. }
  8491. }
  8492. // Case 4: Nowhere to move
  8493. return null
  8494. }
  8495. // Commands are parameter-less actions that can be performed on an
  8496. // editor, mostly used for keybindings.
  8497. var commands = {
  8498. selectAll: selectAll,
  8499. singleSelection: function (cm) {
  8500. return cm.setSelection(cm.getCursor('anchor'), cm.getCursor('head'), sel_dontScroll)
  8501. },
  8502. killLine: function (cm) {
  8503. return deleteNearSelection(cm, function (range) {
  8504. if (range.empty()) {
  8505. var len = getLine(cm.doc, range.head.line).text.length
  8506. if (range.head.ch == len && range.head.line < cm.lastLine()) {
  8507. return { from: range.head, to: Pos(range.head.line + 1, 0) }
  8508. } else {
  8509. return { from: range.head, to: Pos(range.head.line, len) }
  8510. }
  8511. } else {
  8512. return { from: range.from(), to: range.to() }
  8513. }
  8514. })
  8515. },
  8516. deleteLine: function (cm) {
  8517. return deleteNearSelection(cm, function (range) {
  8518. return {
  8519. from: Pos(range.from().line, 0),
  8520. to: clipPos(cm.doc, Pos(range.to().line + 1, 0)),
  8521. }
  8522. })
  8523. },
  8524. delLineLeft: function (cm) {
  8525. return deleteNearSelection(cm, function (range) {
  8526. return {
  8527. from: Pos(range.from().line, 0),
  8528. to: range.from(),
  8529. }
  8530. })
  8531. },
  8532. delWrappedLineLeft: function (cm) {
  8533. return deleteNearSelection(cm, function (range) {
  8534. var top = cm.charCoords(range.head, 'div').top + 5
  8535. var leftPos = cm.coordsChar({ left: 0, top: top }, 'div')
  8536. return { from: leftPos, to: range.from() }
  8537. })
  8538. },
  8539. delWrappedLineRight: function (cm) {
  8540. return deleteNearSelection(cm, function (range) {
  8541. var top = cm.charCoords(range.head, 'div').top + 5
  8542. var rightPos = cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top }, 'div')
  8543. return { from: range.from(), to: rightPos }
  8544. })
  8545. },
  8546. undo: function (cm) {
  8547. return cm.undo()
  8548. },
  8549. redo: function (cm) {
  8550. return cm.redo()
  8551. },
  8552. undoSelection: function (cm) {
  8553. return cm.undoSelection()
  8554. },
  8555. redoSelection: function (cm) {
  8556. return cm.redoSelection()
  8557. },
  8558. goDocStart: function (cm) {
  8559. return cm.extendSelection(Pos(cm.firstLine(), 0))
  8560. },
  8561. goDocEnd: function (cm) {
  8562. return cm.extendSelection(Pos(cm.lastLine()))
  8563. },
  8564. goLineStart: function (cm) {
  8565. return cm.extendSelectionsBy(
  8566. function (range) {
  8567. return lineStart(cm, range.head.line)
  8568. },
  8569. { origin: '+move', bias: 1 }
  8570. )
  8571. },
  8572. goLineStartSmart: function (cm) {
  8573. return cm.extendSelectionsBy(
  8574. function (range) {
  8575. return lineStartSmart(cm, range.head)
  8576. },
  8577. { origin: '+move', bias: 1 }
  8578. )
  8579. },
  8580. goLineEnd: function (cm) {
  8581. return cm.extendSelectionsBy(
  8582. function (range) {
  8583. return lineEnd(cm, range.head.line)
  8584. },
  8585. { origin: '+move', bias: -1 }
  8586. )
  8587. },
  8588. goLineRight: function (cm) {
  8589. return cm.extendSelectionsBy(function (range) {
  8590. var top = cm.cursorCoords(range.head, 'div').top + 5
  8591. return cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top }, 'div')
  8592. }, sel_move)
  8593. },
  8594. goLineLeft: function (cm) {
  8595. return cm.extendSelectionsBy(function (range) {
  8596. var top = cm.cursorCoords(range.head, 'div').top + 5
  8597. return cm.coordsChar({ left: 0, top: top }, 'div')
  8598. }, sel_move)
  8599. },
  8600. goLineLeftSmart: function (cm) {
  8601. return cm.extendSelectionsBy(function (range) {
  8602. var top = cm.cursorCoords(range.head, 'div').top + 5
  8603. var pos = cm.coordsChar({ left: 0, top: top }, 'div')
  8604. if (pos.ch < cm.getLine(pos.line).search(/\S/)) {
  8605. return lineStartSmart(cm, range.head)
  8606. }
  8607. return pos
  8608. }, sel_move)
  8609. },
  8610. goLineUp: function (cm) {
  8611. return cm.moveV(-1, 'line')
  8612. },
  8613. goLineDown: function (cm) {
  8614. return cm.moveV(1, 'line')
  8615. },
  8616. goPageUp: function (cm) {
  8617. return cm.moveV(-1, 'page')
  8618. },
  8619. goPageDown: function (cm) {
  8620. return cm.moveV(1, 'page')
  8621. },
  8622. goCharLeft: function (cm) {
  8623. return cm.moveH(-1, 'char')
  8624. },
  8625. goCharRight: function (cm) {
  8626. return cm.moveH(1, 'char')
  8627. },
  8628. goColumnLeft: function (cm) {
  8629. return cm.moveH(-1, 'column')
  8630. },
  8631. goColumnRight: function (cm) {
  8632. return cm.moveH(1, 'column')
  8633. },
  8634. goWordLeft: function (cm) {
  8635. return cm.moveH(-1, 'word')
  8636. },
  8637. goGroupRight: function (cm) {
  8638. return cm.moveH(1, 'group')
  8639. },
  8640. goGroupLeft: function (cm) {
  8641. return cm.moveH(-1, 'group')
  8642. },
  8643. goWordRight: function (cm) {
  8644. return cm.moveH(1, 'word')
  8645. },
  8646. delCharBefore: function (cm) {
  8647. return cm.deleteH(-1, 'codepoint')
  8648. },
  8649. delCharAfter: function (cm) {
  8650. return cm.deleteH(1, 'char')
  8651. },
  8652. delWordBefore: function (cm) {
  8653. return cm.deleteH(-1, 'word')
  8654. },
  8655. delWordAfter: function (cm) {
  8656. return cm.deleteH(1, 'word')
  8657. },
  8658. delGroupBefore: function (cm) {
  8659. return cm.deleteH(-1, 'group')
  8660. },
  8661. delGroupAfter: function (cm) {
  8662. return cm.deleteH(1, 'group')
  8663. },
  8664. indentAuto: function (cm) {
  8665. return cm.indentSelection('smart')
  8666. },
  8667. indentMore: function (cm) {
  8668. return cm.indentSelection('add')
  8669. },
  8670. indentLess: function (cm) {
  8671. return cm.indentSelection('subtract')
  8672. },
  8673. insertTab: function (cm) {
  8674. return cm.replaceSelection('\t')
  8675. },
  8676. insertSoftTab: function (cm) {
  8677. var spaces = [],
  8678. ranges = cm.listSelections(),
  8679. tabSize = cm.options.tabSize
  8680. for (var i = 0; i < ranges.length; i++) {
  8681. var pos = ranges[i].from()
  8682. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  8683. spaces.push(spaceStr(tabSize - (col % tabSize)))
  8684. }
  8685. cm.replaceSelections(spaces)
  8686. },
  8687. defaultTab: function (cm) {
  8688. if (cm.somethingSelected()) {
  8689. cm.indentSelection('add')
  8690. } else {
  8691. cm.execCommand('insertTab')
  8692. }
  8693. },
  8694. // Swap the two chars left and right of each selection's head.
  8695. // Move cursor behind the two swapped characters afterwards.
  8696. //
  8697. // Doesn't consider line feeds a character.
  8698. // Doesn't scan more than one line above to find a character.
  8699. // Doesn't do anything on an empty line.
  8700. // Doesn't do anything with non-empty selections.
  8701. transposeChars: function (cm) {
  8702. return runInOp(cm, function () {
  8703. var ranges = cm.listSelections(),
  8704. newSel = []
  8705. for (var i = 0; i < ranges.length; i++) {
  8706. if (!ranges[i].empty()) {
  8707. continue
  8708. }
  8709. var cur = ranges[i].head,
  8710. line = getLine(cm.doc, cur.line).text
  8711. if (line) {
  8712. if (cur.ch == line.length) {
  8713. cur = new Pos(cur.line, cur.ch - 1)
  8714. }
  8715. if (cur.ch > 0) {
  8716. cur = new Pos(cur.line, cur.ch + 1)
  8717. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, '+transpose')
  8718. } else if (cur.line > cm.doc.first) {
  8719. var prev = getLine(cm.doc, cur.line - 1).text
  8720. if (prev) {
  8721. cur = new Pos(cur.line, 1)
  8722. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, '+transpose')
  8723. }
  8724. }
  8725. }
  8726. newSel.push(new Range(cur, cur))
  8727. }
  8728. cm.setSelections(newSel)
  8729. })
  8730. },
  8731. newlineAndIndent: function (cm) {
  8732. return runInOp(cm, function () {
  8733. var sels = cm.listSelections()
  8734. for (var i = sels.length - 1; i >= 0; i--) {
  8735. cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, '+input')
  8736. }
  8737. sels = cm.listSelections()
  8738. for (var i$1 = 0; i$1 < sels.length; i$1++) {
  8739. cm.indentLine(sels[i$1].from().line, null, true)
  8740. }
  8741. ensureCursorVisible(cm)
  8742. })
  8743. },
  8744. openLine: function (cm) {
  8745. return cm.replaceSelection('\n', 'start')
  8746. },
  8747. toggleOverwrite: function (cm) {
  8748. return cm.toggleOverwrite()
  8749. },
  8750. }
  8751. function lineStart(cm, lineN) {
  8752. var line = getLine(cm.doc, lineN)
  8753. var visual = visualLine(line)
  8754. if (visual != line) {
  8755. lineN = lineNo(visual)
  8756. }
  8757. return endOfLine(true, cm, visual, lineN, 1)
  8758. }
  8759. function lineEnd(cm, lineN) {
  8760. var line = getLine(cm.doc, lineN)
  8761. var visual = visualLineEnd(line)
  8762. if (visual != line) {
  8763. lineN = lineNo(visual)
  8764. }
  8765. return endOfLine(true, cm, line, lineN, -1)
  8766. }
  8767. function lineStartSmart(cm, pos) {
  8768. var start = lineStart(cm, pos.line)
  8769. var line = getLine(cm.doc, start.line)
  8770. var order = getOrder(line, cm.doc.direction)
  8771. if (!order || order[0].level == 0) {
  8772. var firstNonWS = Math.max(start.ch, line.text.search(/\S/))
  8773. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  8774. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  8775. }
  8776. return start
  8777. }
  8778. // Run a handler that was bound to a key.
  8779. function doHandleBinding(cm, bound, dropShift) {
  8780. if (typeof bound == 'string') {
  8781. bound = commands[bound]
  8782. if (!bound) {
  8783. return false
  8784. }
  8785. }
  8786. // Ensure previous input has been read, so that the handler sees a
  8787. // consistent view of the document
  8788. cm.display.input.ensurePolled()
  8789. var prevShift = cm.display.shift,
  8790. done = false
  8791. try {
  8792. if (cm.isReadOnly()) {
  8793. cm.state.suppressEdits = true
  8794. }
  8795. if (dropShift) {
  8796. cm.display.shift = false
  8797. }
  8798. done = bound(cm) != Pass
  8799. } finally {
  8800. cm.display.shift = prevShift
  8801. cm.state.suppressEdits = false
  8802. }
  8803. return done
  8804. }
  8805. function lookupKeyForEditor(cm, name, handle) {
  8806. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  8807. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  8808. if (result) {
  8809. return result
  8810. }
  8811. }
  8812. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) || lookupKey(name, cm.options.keyMap, handle, cm)
  8813. }
  8814. // Note that, despite the name, this function is also used to check
  8815. // for bound mouse clicks.
  8816. var stopSeq = new Delayed()
  8817. function dispatchKey(cm, name, e, handle) {
  8818. var seq = cm.state.keySeq
  8819. if (seq) {
  8820. if (isModifierKey(name)) {
  8821. return 'handled'
  8822. }
  8823. if (/\'$/.test(name)) {
  8824. cm.state.keySeq = null
  8825. } else {
  8826. stopSeq.set(50, function () {
  8827. if (cm.state.keySeq == seq) {
  8828. cm.state.keySeq = null
  8829. cm.display.input.reset()
  8830. }
  8831. })
  8832. }
  8833. if (dispatchKeyInner(cm, seq + ' ' + name, e, handle)) {
  8834. return true
  8835. }
  8836. }
  8837. return dispatchKeyInner(cm, name, e, handle)
  8838. }
  8839. function dispatchKeyInner(cm, name, e, handle) {
  8840. var result = lookupKeyForEditor(cm, name, handle)
  8841. if (result == 'multi') {
  8842. cm.state.keySeq = name
  8843. }
  8844. if (result == 'handled') {
  8845. signalLater(cm, 'keyHandled', cm, name, e)
  8846. }
  8847. if (result == 'handled' || result == 'multi') {
  8848. e_preventDefault(e)
  8849. restartBlink(cm)
  8850. }
  8851. return !!result
  8852. }
  8853. // Handle a key from the keydown event.
  8854. function handleKeyBinding(cm, e) {
  8855. var name = keyName(e, true)
  8856. if (!name) {
  8857. return false
  8858. }
  8859. if (e.shiftKey && !cm.state.keySeq) {
  8860. // First try to resolve full name (including 'Shift-'). Failing
  8861. // that, see if there is a cursor-motion command (starting with
  8862. // 'go') bound to the keyname without 'Shift-'.
  8863. return (
  8864. dispatchKey(cm, 'Shift-' + name, e, function (b) {
  8865. return doHandleBinding(cm, b, true)
  8866. }) ||
  8867. dispatchKey(cm, name, e, function (b) {
  8868. if (typeof b == 'string' ? /^go[A-Z]/.test(b) : b.motion) {
  8869. return doHandleBinding(cm, b)
  8870. }
  8871. })
  8872. )
  8873. } else {
  8874. return dispatchKey(cm, name, e, function (b) {
  8875. return doHandleBinding(cm, b)
  8876. })
  8877. }
  8878. }
  8879. // Handle a key from the keypress event
  8880. function handleCharBinding(cm, e, ch) {
  8881. return dispatchKey(cm, "'" + ch + "'", e, function (b) {
  8882. return doHandleBinding(cm, b, true)
  8883. })
  8884. }
  8885. var lastStoppedKey = null
  8886. function onKeyDown(e) {
  8887. var cm = this
  8888. if (e.target && e.target != cm.display.input.getField()) {
  8889. return
  8890. }
  8891. cm.curOp.focus = activeElt()
  8892. if (signalDOMEvent(cm, e)) {
  8893. return
  8894. }
  8895. // IE does strange things with escape.
  8896. if (ie && ie_version < 11 && e.keyCode == 27) {
  8897. e.returnValue = false
  8898. }
  8899. var code = e.keyCode
  8900. cm.display.shift = code == 16 || e.shiftKey
  8901. var handled = handleKeyBinding(cm, e)
  8902. if (presto) {
  8903. lastStoppedKey = handled ? code : null
  8904. // Opera has no cut event... we try to at least catch the key combo
  8905. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) {
  8906. cm.replaceSelection('', null, 'cut')
  8907. }
  8908. }
  8909. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) {
  8910. document.execCommand('cut')
  8911. }
  8912. // Turn mouse into crosshair when Alt is held on Mac.
  8913. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {
  8914. showCrossHair(cm)
  8915. }
  8916. }
  8917. function showCrossHair(cm) {
  8918. var lineDiv = cm.display.lineDiv
  8919. addClass(lineDiv, 'CodeMirror-crosshair')
  8920. function up(e) {
  8921. if (e.keyCode == 18 || !e.altKey) {
  8922. rmClass(lineDiv, 'CodeMirror-crosshair')
  8923. off(document, 'keyup', up)
  8924. off(document, 'mouseover', up)
  8925. }
  8926. }
  8927. on(document, 'keyup', up)
  8928. on(document, 'mouseover', up)
  8929. }
  8930. function onKeyUp(e) {
  8931. if (e.keyCode == 16) {
  8932. this.doc.sel.shift = false
  8933. }
  8934. signalDOMEvent(this, e)
  8935. }
  8936. function onKeyPress(e) {
  8937. var cm = this
  8938. if (e.target && e.target != cm.display.input.getField()) {
  8939. return
  8940. }
  8941. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || (e.ctrlKey && !e.altKey) || (mac && e.metaKey)) {
  8942. return
  8943. }
  8944. var keyCode = e.keyCode,
  8945. charCode = e.charCode
  8946. if (presto && keyCode == lastStoppedKey) {
  8947. lastStoppedKey = null
  8948. e_preventDefault(e)
  8949. return
  8950. }
  8951. if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) {
  8952. return
  8953. }
  8954. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  8955. // Some browsers fire keypress events for backspace
  8956. if (ch == '\x08') {
  8957. return
  8958. }
  8959. if (handleCharBinding(cm, e, ch)) {
  8960. return
  8961. }
  8962. cm.display.input.onKeyPress(e)
  8963. }
  8964. var DOUBLECLICK_DELAY = 400
  8965. var PastClick = function (time, pos, button) {
  8966. this.time = time
  8967. this.pos = pos
  8968. this.button = button
  8969. }
  8970. PastClick.prototype.compare = function (time, pos, button) {
  8971. return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button
  8972. }
  8973. var lastClick, lastDoubleClick
  8974. function clickRepeat(pos, button) {
  8975. var now = +new Date()
  8976. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  8977. lastClick = lastDoubleClick = null
  8978. return 'triple'
  8979. } else if (lastClick && lastClick.compare(now, pos, button)) {
  8980. lastDoubleClick = new PastClick(now, pos, button)
  8981. lastClick = null
  8982. return 'double'
  8983. } else {
  8984. lastClick = new PastClick(now, pos, button)
  8985. lastDoubleClick = null
  8986. return 'single'
  8987. }
  8988. }
  8989. // A mouse down can be a single click, double click, triple click,
  8990. // start of selection drag, start of text drag, new cursor
  8991. // (ctrl-click), rectangle drag (alt-drag), or xwin
  8992. // middle-click-paste. Or it might be a click on something we should
  8993. // not interfere with, such as a scrollbar or widget.
  8994. function onMouseDown(e) {
  8995. var cm = this,
  8996. display = cm.display
  8997. if (signalDOMEvent(cm, e) || (display.activeTouch && display.input.supportsTouch())) {
  8998. return
  8999. }
  9000. display.input.ensurePolled()
  9001. display.shift = e.shiftKey
  9002. if (eventInWidget(display, e)) {
  9003. if (!webkit) {
  9004. // Briefly turn off draggability, to allow widgets to do
  9005. // normal dragging things.
  9006. display.scroller.draggable = false
  9007. setTimeout(function () {
  9008. return (display.scroller.draggable = true)
  9009. }, 100)
  9010. }
  9011. return
  9012. }
  9013. if (clickInGutter(cm, e)) {
  9014. return
  9015. }
  9016. var pos = posFromMouse(cm, e),
  9017. button = e_button(e),
  9018. repeat = pos ? clickRepeat(pos, button) : 'single'
  9019. window.focus()
  9020. // #3261: make sure, that we're not starting a second selection
  9021. if (button == 1 && cm.state.selectingText) {
  9022. cm.state.selectingText(e)
  9023. }
  9024. if (pos && handleMappedButton(cm, button, pos, repeat, e)) {
  9025. return
  9026. }
  9027. if (button == 1) {
  9028. if (pos) {
  9029. leftButtonDown(cm, pos, repeat, e)
  9030. } else if (e_target(e) == display.scroller) {
  9031. e_preventDefault(e)
  9032. }
  9033. } else if (button == 2) {
  9034. if (pos) {
  9035. extendSelection(cm.doc, pos)
  9036. }
  9037. setTimeout(function () {
  9038. return display.input.focus()
  9039. }, 20)
  9040. } else if (button == 3) {
  9041. if (captureRightClick) {
  9042. cm.display.input.onContextMenu(e)
  9043. } else {
  9044. delayBlurEvent(cm)
  9045. }
  9046. }
  9047. }
  9048. function handleMappedButton(cm, button, pos, repeat, event) {
  9049. var name = 'Click'
  9050. if (repeat == 'double') {
  9051. name = 'Double' + name
  9052. } else if (repeat == 'triple') {
  9053. name = 'Triple' + name
  9054. }
  9055. name = (button == 1 ? 'Left' : button == 2 ? 'Middle' : 'Right') + name
  9056. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  9057. if (typeof bound == 'string') {
  9058. bound = commands[bound]
  9059. }
  9060. if (!bound) {
  9061. return false
  9062. }
  9063. var done = false
  9064. try {
  9065. if (cm.isReadOnly()) {
  9066. cm.state.suppressEdits = true
  9067. }
  9068. done = bound(cm, pos) != Pass
  9069. } finally {
  9070. cm.state.suppressEdits = false
  9071. }
  9072. return done
  9073. })
  9074. }
  9075. function configureMouse(cm, repeat, event) {
  9076. var option = cm.getOption('configureMouse')
  9077. var value = option ? option(cm, repeat, event) : {}
  9078. if (value.unit == null) {
  9079. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey
  9080. value.unit = rect ? 'rectangle' : repeat == 'single' ? 'char' : repeat == 'double' ? 'word' : 'line'
  9081. }
  9082. if (value.extend == null || cm.doc.extend) {
  9083. value.extend = cm.doc.extend || event.shiftKey
  9084. }
  9085. if (value.addNew == null) {
  9086. value.addNew = mac ? event.metaKey : event.ctrlKey
  9087. }
  9088. if (value.moveOnDrag == null) {
  9089. value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey)
  9090. }
  9091. return value
  9092. }
  9093. function leftButtonDown(cm, pos, repeat, event) {
  9094. if (ie) {
  9095. setTimeout(bind(ensureFocus, cm), 0)
  9096. } else {
  9097. cm.curOp.focus = activeElt()
  9098. }
  9099. var behavior = configureMouse(cm, repeat, event)
  9100. var sel = cm.doc.sel,
  9101. contained
  9102. if (
  9103. cm.options.dragDrop &&
  9104. dragAndDrop &&
  9105. !cm.isReadOnly() &&
  9106. repeat == 'single' &&
  9107. (contained = sel.contains(pos)) > -1 &&
  9108. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  9109. (cmp(contained.to(), pos) > 0 || pos.xRel < 0)
  9110. ) {
  9111. leftButtonStartDrag(cm, event, pos, behavior)
  9112. } else {
  9113. leftButtonSelect(cm, event, pos, behavior)
  9114. }
  9115. }
  9116. // Start a text drag. When it ends, see if any dragging actually
  9117. // happen, and treat as a click if it didn't.
  9118. function leftButtonStartDrag(cm, event, pos, behavior) {
  9119. var display = cm.display,
  9120. moved = false
  9121. var dragEnd = operation(cm, function (e) {
  9122. if (webkit) {
  9123. display.scroller.draggable = false
  9124. }
  9125. cm.state.draggingText = false
  9126. if (cm.state.delayingBlurEvent) {
  9127. if (cm.hasFocus()) {
  9128. cm.state.delayingBlurEvent = false
  9129. } else {
  9130. delayBlurEvent(cm)
  9131. }
  9132. }
  9133. off(display.wrapper.ownerDocument, 'mouseup', dragEnd)
  9134. off(display.wrapper.ownerDocument, 'mousemove', mouseMove)
  9135. off(display.scroller, 'dragstart', dragStart)
  9136. off(display.scroller, 'drop', dragEnd)
  9137. if (!moved) {
  9138. e_preventDefault(e)
  9139. if (!behavior.addNew) {
  9140. extendSelection(cm.doc, pos, null, null, behavior.extend)
  9141. }
  9142. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  9143. if ((webkit && !safari) || (ie && ie_version == 9)) {
  9144. setTimeout(function () {
  9145. display.wrapper.ownerDocument.body.focus({ preventScroll: true })
  9146. display.input.focus()
  9147. }, 20)
  9148. } else {
  9149. display.input.focus()
  9150. }
  9151. }
  9152. })
  9153. var mouseMove = function (e2) {
  9154. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10
  9155. }
  9156. var dragStart = function () {
  9157. return (moved = true)
  9158. }
  9159. // Let the drag handler handle this.
  9160. if (webkit) {
  9161. display.scroller.draggable = true
  9162. }
  9163. cm.state.draggingText = dragEnd
  9164. dragEnd.copy = !behavior.moveOnDrag
  9165. on(display.wrapper.ownerDocument, 'mouseup', dragEnd)
  9166. on(display.wrapper.ownerDocument, 'mousemove', mouseMove)
  9167. on(display.scroller, 'dragstart', dragStart)
  9168. on(display.scroller, 'drop', dragEnd)
  9169. cm.state.delayingBlurEvent = true
  9170. setTimeout(function () {
  9171. return display.input.focus()
  9172. }, 20)
  9173. // IE's approach to draggable
  9174. if (display.scroller.dragDrop) {
  9175. display.scroller.dragDrop()
  9176. }
  9177. }
  9178. function rangeForUnit(cm, pos, unit) {
  9179. if (unit == 'char') {
  9180. return new Range(pos, pos)
  9181. }
  9182. if (unit == 'word') {
  9183. return cm.findWordAt(pos)
  9184. }
  9185. if (unit == 'line') {
  9186. return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)))
  9187. }
  9188. var result = unit(cm, pos)
  9189. return new Range(result.from, result.to)
  9190. }
  9191. // Normal selection, as opposed to text dragging.
  9192. function leftButtonSelect(cm, event, start, behavior) {
  9193. if (ie) {
  9194. delayBlurEvent(cm)
  9195. }
  9196. var display = cm.display,
  9197. doc = cm.doc
  9198. e_preventDefault(event)
  9199. var ourRange,
  9200. ourIndex,
  9201. startSel = doc.sel,
  9202. ranges = startSel.ranges
  9203. if (behavior.addNew && !behavior.extend) {
  9204. ourIndex = doc.sel.contains(start)
  9205. if (ourIndex > -1) {
  9206. ourRange = ranges[ourIndex]
  9207. } else {
  9208. ourRange = new Range(start, start)
  9209. }
  9210. } else {
  9211. ourRange = doc.sel.primary()
  9212. ourIndex = doc.sel.primIndex
  9213. }
  9214. if (behavior.unit == 'rectangle') {
  9215. if (!behavior.addNew) {
  9216. ourRange = new Range(start, start)
  9217. }
  9218. start = posFromMouse(cm, event, true, true)
  9219. ourIndex = -1
  9220. } else {
  9221. var range = rangeForUnit(cm, start, behavior.unit)
  9222. if (behavior.extend) {
  9223. ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend)
  9224. } else {
  9225. ourRange = range
  9226. }
  9227. }
  9228. if (!behavior.addNew) {
  9229. ourIndex = 0
  9230. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  9231. startSel = doc.sel
  9232. } else if (ourIndex == -1) {
  9233. ourIndex = ranges.length
  9234. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), { scroll: false, origin: '*mouse' })
  9235. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == 'char' && !behavior.extend) {
  9236. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), { scroll: false, origin: '*mouse' })
  9237. startSel = doc.sel
  9238. } else {
  9239. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  9240. }
  9241. var lastPos = start
  9242. function extendTo(pos) {
  9243. if (cmp(lastPos, pos) == 0) {
  9244. return
  9245. }
  9246. lastPos = pos
  9247. if (behavior.unit == 'rectangle') {
  9248. var ranges = [],
  9249. tabSize = cm.options.tabSize
  9250. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  9251. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  9252. var left = Math.min(startCol, posCol),
  9253. right = Math.max(startCol, posCol)
  9254. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) {
  9255. var text = getLine(doc, line).text,
  9256. leftPos = findColumn(text, left, tabSize)
  9257. if (left == right) {
  9258. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)))
  9259. } else if (text.length > leftPos) {
  9260. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))))
  9261. }
  9262. }
  9263. if (!ranges.length) {
  9264. ranges.push(new Range(start, start))
  9265. }
  9266. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), { origin: '*mouse', scroll: false })
  9267. cm.scrollIntoView(pos)
  9268. } else {
  9269. var oldRange = ourRange
  9270. var range = rangeForUnit(cm, pos, behavior.unit)
  9271. var anchor = oldRange.anchor,
  9272. head
  9273. if (cmp(range.anchor, anchor) > 0) {
  9274. head = range.head
  9275. anchor = minPos(oldRange.from(), range.anchor)
  9276. } else {
  9277. head = range.anchor
  9278. anchor = maxPos(oldRange.to(), range.head)
  9279. }
  9280. var ranges$1 = startSel.ranges.slice(0)
  9281. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head))
  9282. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse)
  9283. }
  9284. }
  9285. var editorSize = display.wrapper.getBoundingClientRect()
  9286. // Used to ensure timeout re-tries don't fire when another extend
  9287. // happened in the meantime (clearTimeout isn't reliable -- at
  9288. // least on Chrome, the timeouts still happen even when cleared,
  9289. // if the clear happens after their scheduled firing time).
  9290. var counter = 0
  9291. function extend(e) {
  9292. var curCount = ++counter
  9293. var cur = posFromMouse(cm, e, true, behavior.unit == 'rectangle')
  9294. if (!cur) {
  9295. return
  9296. }
  9297. if (cmp(cur, lastPos) != 0) {
  9298. cm.curOp.focus = activeElt()
  9299. extendTo(cur)
  9300. var visible = visibleLines(display, doc)
  9301. if (cur.line >= visible.to || cur.line < visible.from) {
  9302. setTimeout(
  9303. operation(cm, function () {
  9304. if (counter == curCount) {
  9305. extend(e)
  9306. }
  9307. }),
  9308. 150
  9309. )
  9310. }
  9311. } else {
  9312. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  9313. if (outside) {
  9314. setTimeout(
  9315. operation(cm, function () {
  9316. if (counter != curCount) {
  9317. return
  9318. }
  9319. display.scroller.scrollTop += outside
  9320. extend(e)
  9321. }),
  9322. 50
  9323. )
  9324. }
  9325. }
  9326. }
  9327. function done(e) {
  9328. cm.state.selectingText = false
  9329. counter = Infinity
  9330. // If e is null or undefined we interpret this as someone trying
  9331. // to explicitly cancel the selection rather than the user
  9332. // letting go of the mouse button.
  9333. if (e) {
  9334. e_preventDefault(e)
  9335. display.input.focus()
  9336. }
  9337. off(display.wrapper.ownerDocument, 'mousemove', move)
  9338. off(display.wrapper.ownerDocument, 'mouseup', up)
  9339. doc.history.lastSelOrigin = null
  9340. }
  9341. var move = operation(cm, function (e) {
  9342. if (e.buttons === 0 || !e_button(e)) {
  9343. done(e)
  9344. } else {
  9345. extend(e)
  9346. }
  9347. })
  9348. var up = operation(cm, done)
  9349. cm.state.selectingText = up
  9350. on(display.wrapper.ownerDocument, 'mousemove', move)
  9351. on(display.wrapper.ownerDocument, 'mouseup', up)
  9352. }
  9353. // Used when mouse-selecting to adjust the anchor to the proper side
  9354. // of a bidi jump depending on the visual position of the head.
  9355. function bidiSimplify(cm, range) {
  9356. var anchor = range.anchor
  9357. var head = range.head
  9358. var anchorLine = getLine(cm.doc, anchor.line)
  9359. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) {
  9360. return range
  9361. }
  9362. var order = getOrder(anchorLine)
  9363. if (!order) {
  9364. return range
  9365. }
  9366. var index = getBidiPartAt(order, anchor.ch, anchor.sticky),
  9367. part = order[index]
  9368. if (part.from != anchor.ch && part.to != anchor.ch) {
  9369. return range
  9370. }
  9371. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1)
  9372. if (boundary == 0 || boundary == order.length) {
  9373. return range
  9374. }
  9375. // Compute the relative visual position of the head compared to the
  9376. // anchor (<0 is to the left, >0 to the right)
  9377. var leftSide
  9378. if (head.line != anchor.line) {
  9379. leftSide = (head.line - anchor.line) * (cm.doc.direction == 'ltr' ? 1 : -1) > 0
  9380. } else {
  9381. var headIndex = getBidiPartAt(order, head.ch, head.sticky)
  9382. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1)
  9383. if (headIndex == boundary - 1 || headIndex == boundary) {
  9384. leftSide = dir < 0
  9385. } else {
  9386. leftSide = dir > 0
  9387. }
  9388. }
  9389. var usePart = order[boundary + (leftSide ? -1 : 0)]
  9390. var from = leftSide == (usePart.level == 1)
  9391. var ch = from ? usePart.from : usePart.to,
  9392. sticky = from ? 'after' : 'before'
  9393. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  9394. }
  9395. // Determines whether an event happened in the gutter, and fires the
  9396. // handlers for the corresponding event.
  9397. function gutterEvent(cm, e, type, prevent) {
  9398. var mX, mY
  9399. if (e.touches) {
  9400. mX = e.touches[0].clientX
  9401. mY = e.touches[0].clientY
  9402. } else {
  9403. try {
  9404. mX = e.clientX
  9405. mY = e.clientY
  9406. } catch (e$1) {
  9407. return false
  9408. }
  9409. }
  9410. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) {
  9411. return false
  9412. }
  9413. if (prevent) {
  9414. e_preventDefault(e)
  9415. }
  9416. var display = cm.display
  9417. var lineBox = display.lineDiv.getBoundingClientRect()
  9418. if (mY > lineBox.bottom || !hasHandler(cm, type)) {
  9419. return e_defaultPrevented(e)
  9420. }
  9421. mY -= lineBox.top - display.viewOffset
  9422. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  9423. var g = display.gutters.childNodes[i]
  9424. if (g && g.getBoundingClientRect().right >= mX) {
  9425. var line = lineAtHeight(cm.doc, mY)
  9426. var gutter = cm.display.gutterSpecs[i]
  9427. signal(cm, type, cm, line, gutter.className, e)
  9428. return e_defaultPrevented(e)
  9429. }
  9430. }
  9431. }
  9432. function clickInGutter(cm, e) {
  9433. return gutterEvent(cm, e, 'gutterClick', true)
  9434. }
  9435. // CONTEXT MENU HANDLING
  9436. // To make the context menu work, we need to briefly unhide the
  9437. // textarea (making it as unobtrusive as possible) to let the
  9438. // right-click take effect on it.
  9439. function onContextMenu(cm, e) {
  9440. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) {
  9441. return
  9442. }
  9443. if (signalDOMEvent(cm, e, 'contextmenu')) {
  9444. return
  9445. }
  9446. if (!captureRightClick) {
  9447. cm.display.input.onContextMenu(e)
  9448. }
  9449. }
  9450. function contextMenuInGutter(cm, e) {
  9451. if (!hasHandler(cm, 'gutterContextMenu')) {
  9452. return false
  9453. }
  9454. return gutterEvent(cm, e, 'gutterContextMenu', false)
  9455. }
  9456. function themeChanged(cm) {
  9457. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, '') + cm.options.theme.replace(/(^|\s)\s*/g, ' cm-s-')
  9458. clearCaches(cm)
  9459. }
  9460. var Init = {
  9461. toString: function () {
  9462. return 'CodeMirror.Init'
  9463. },
  9464. }
  9465. var defaults = {}
  9466. var optionHandlers = {}
  9467. function defineOptions(CodeMirror) {
  9468. var optionHandlers = CodeMirror.optionHandlers
  9469. function option(name, deflt, handle, notOnInit) {
  9470. CodeMirror.defaults[name] = deflt
  9471. if (handle) {
  9472. optionHandlers[name] = notOnInit
  9473. ? function (cm, val, old) {
  9474. if (old != Init) {
  9475. handle(cm, val, old)
  9476. }
  9477. }
  9478. : handle
  9479. }
  9480. }
  9481. CodeMirror.defineOption = option
  9482. // Passed to option handlers when there is no old value.
  9483. CodeMirror.Init = Init
  9484. // These two are, on init, called from the constructor because they
  9485. // have to be initialized before the editor can start at all.
  9486. option(
  9487. 'value',
  9488. '',
  9489. function (cm, val) {
  9490. return cm.setValue(val)
  9491. },
  9492. true
  9493. )
  9494. option(
  9495. 'mode',
  9496. null,
  9497. function (cm, val) {
  9498. cm.doc.modeOption = val
  9499. loadMode(cm)
  9500. },
  9501. true
  9502. )
  9503. option('indentUnit', 2, loadMode, true)
  9504. option('indentWithTabs', false)
  9505. option('smartIndent', true)
  9506. option(
  9507. 'tabSize',
  9508. 4,
  9509. function (cm) {
  9510. resetModeState(cm)
  9511. clearCaches(cm)
  9512. regChange(cm)
  9513. },
  9514. true
  9515. )
  9516. option('lineSeparator', null, function (cm, val) {
  9517. cm.doc.lineSep = val
  9518. if (!val) {
  9519. return
  9520. }
  9521. var newBreaks = [],
  9522. lineNo = cm.doc.first
  9523. cm.doc.iter(function (line) {
  9524. for (var pos = 0; ; ) {
  9525. var found = line.text.indexOf(val, pos)
  9526. if (found == -1) {
  9527. break
  9528. }
  9529. pos = found + val.length
  9530. newBreaks.push(Pos(lineNo, found))
  9531. }
  9532. lineNo++
  9533. })
  9534. for (var i = newBreaks.length - 1; i >= 0; i--) {
  9535. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  9536. }
  9537. })
  9538. option('specialChars', /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  9539. cm.state.specialChars = new RegExp(val.source + (val.test('\t') ? '' : '|\t'), 'g')
  9540. if (old != Init) {
  9541. cm.refresh()
  9542. }
  9543. })
  9544. option(
  9545. 'specialCharPlaceholder',
  9546. defaultSpecialCharPlaceholder,
  9547. function (cm) {
  9548. return cm.refresh()
  9549. },
  9550. true
  9551. )
  9552. option('electricChars', true)
  9553. option(
  9554. 'inputStyle',
  9555. mobile ? 'contenteditable' : 'textarea',
  9556. function () {
  9557. throw new Error('inputStyle can not (yet) be changed in a running editor') // FIXME
  9558. },
  9559. true
  9560. )
  9561. option(
  9562. 'spellcheck',
  9563. false,
  9564. function (cm, val) {
  9565. return (cm.getInputField().spellcheck = val)
  9566. },
  9567. true
  9568. )
  9569. option(
  9570. 'autocorrect',
  9571. false,
  9572. function (cm, val) {
  9573. return (cm.getInputField().autocorrect = val)
  9574. },
  9575. true
  9576. )
  9577. option(
  9578. 'autocapitalize',
  9579. false,
  9580. function (cm, val) {
  9581. return (cm.getInputField().autocapitalize = val)
  9582. },
  9583. true
  9584. )
  9585. option('rtlMoveVisually', !windows)
  9586. option('wholeLineUpdateBefore', true)
  9587. option(
  9588. 'theme',
  9589. 'default',
  9590. function (cm) {
  9591. themeChanged(cm)
  9592. updateGutters(cm)
  9593. },
  9594. true
  9595. )
  9596. option('keyMap', 'default', function (cm, val, old) {
  9597. var next = getKeyMap(val)
  9598. var prev = old != Init && getKeyMap(old)
  9599. if (prev && prev.detach) {
  9600. prev.detach(cm, next)
  9601. }
  9602. if (next.attach) {
  9603. next.attach(cm, prev || null)
  9604. }
  9605. })
  9606. option('extraKeys', null)
  9607. option('configureMouse', null)
  9608. option('lineWrapping', false, wrappingChanged, true)
  9609. option(
  9610. 'gutters',
  9611. [],
  9612. function (cm, val) {
  9613. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers)
  9614. updateGutters(cm)
  9615. },
  9616. true
  9617. )
  9618. option(
  9619. 'fixedGutter',
  9620. true,
  9621. function (cm, val) {
  9622. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + 'px' : '0'
  9623. cm.refresh()
  9624. },
  9625. true
  9626. )
  9627. option(
  9628. 'coverGutterNextToScrollbar',
  9629. false,
  9630. function (cm) {
  9631. return updateScrollbars(cm)
  9632. },
  9633. true
  9634. )
  9635. option(
  9636. 'scrollbarStyle',
  9637. 'native',
  9638. function (cm) {
  9639. initScrollbars(cm)
  9640. updateScrollbars(cm)
  9641. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  9642. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  9643. },
  9644. true
  9645. )
  9646. option(
  9647. 'lineNumbers',
  9648. false,
  9649. function (cm, val) {
  9650. cm.display.gutterSpecs = getGutters(cm.options.gutters, val)
  9651. updateGutters(cm)
  9652. },
  9653. true
  9654. )
  9655. option('firstLineNumber', 1, updateGutters, true)
  9656. option(
  9657. 'lineNumberFormatter',
  9658. function (integer) {
  9659. return integer
  9660. },
  9661. updateGutters,
  9662. true
  9663. )
  9664. option('showCursorWhenSelecting', false, updateSelection, true)
  9665. option('resetSelectionOnContextMenu', true)
  9666. option('lineWiseCopyCut', true)
  9667. option('pasteLinesPerSelection', true)
  9668. option('selectionsMayTouch', false)
  9669. option('readOnly', false, function (cm, val) {
  9670. if (val == 'nocursor') {
  9671. onBlur(cm)
  9672. cm.display.input.blur()
  9673. }
  9674. cm.display.input.readOnlyChanged(val)
  9675. })
  9676. option('screenReaderLabel', null, function (cm, val) {
  9677. val = val === '' ? null : val
  9678. cm.display.input.screenReaderLabelChanged(val)
  9679. })
  9680. option(
  9681. 'disableInput',
  9682. false,
  9683. function (cm, val) {
  9684. if (!val) {
  9685. cm.display.input.reset()
  9686. }
  9687. },
  9688. true
  9689. )
  9690. option('dragDrop', true, dragDropChanged)
  9691. option('allowDropFileTypes', null)
  9692. option('cursorBlinkRate', 530)
  9693. option('cursorScrollMargin', 0)
  9694. option('cursorHeight', 1, updateSelection, true)
  9695. option('singleCursorHeightPerLine', true, updateSelection, true)
  9696. option('workTime', 100)
  9697. option('workDelay', 100)
  9698. option('flattenSpans', true, resetModeState, true)
  9699. option('addModeClass', false, resetModeState, true)
  9700. option('pollInterval', 100)
  9701. option('undoDepth', 200, function (cm, val) {
  9702. return (cm.doc.history.undoDepth = val)
  9703. })
  9704. option('historyEventDelay', 1250)
  9705. option(
  9706. 'viewportMargin',
  9707. 10,
  9708. function (cm) {
  9709. return cm.refresh()
  9710. },
  9711. true
  9712. )
  9713. option('maxHighlightLength', 10000, resetModeState, true)
  9714. option('moveInputWithCursor', true, function (cm, val) {
  9715. if (!val) {
  9716. cm.display.input.resetPosition()
  9717. }
  9718. })
  9719. option('tabindex', null, function (cm, val) {
  9720. return (cm.display.input.getField().tabIndex = val || '')
  9721. })
  9722. option('autofocus', null)
  9723. option(
  9724. 'direction',
  9725. 'ltr',
  9726. function (cm, val) {
  9727. return cm.doc.setDirection(val)
  9728. },
  9729. true
  9730. )
  9731. option('phrases', null)
  9732. }
  9733. function dragDropChanged(cm, value, old) {
  9734. var wasOn = old && old != Init
  9735. if (!value != !wasOn) {
  9736. var funcs = cm.display.dragFunctions
  9737. var toggle = value ? on : off
  9738. toggle(cm.display.scroller, 'dragstart', funcs.start)
  9739. toggle(cm.display.scroller, 'dragenter', funcs.enter)
  9740. toggle(cm.display.scroller, 'dragover', funcs.over)
  9741. toggle(cm.display.scroller, 'dragleave', funcs.leave)
  9742. toggle(cm.display.scroller, 'drop', funcs.drop)
  9743. }
  9744. }
  9745. function wrappingChanged(cm) {
  9746. if (cm.options.lineWrapping) {
  9747. addClass(cm.display.wrapper, 'CodeMirror-wrap')
  9748. cm.display.sizer.style.minWidth = ''
  9749. cm.display.sizerWidth = null
  9750. } else {
  9751. rmClass(cm.display.wrapper, 'CodeMirror-wrap')
  9752. findMaxLine(cm)
  9753. }
  9754. estimateLineHeights(cm)
  9755. regChange(cm)
  9756. clearCaches(cm)
  9757. setTimeout(function () {
  9758. return updateScrollbars(cm)
  9759. }, 100)
  9760. }
  9761. // A CodeMirror instance represents an editor. This is the object
  9762. // that user code is usually dealing with.
  9763. function CodeMirror(place, options) {
  9764. var this$1 = this
  9765. if (!(this instanceof CodeMirror)) {
  9766. return new CodeMirror(place, options)
  9767. }
  9768. this.options = options = options ? copyObj(options) : {}
  9769. // Determine effective options based on given values and defaults.
  9770. copyObj(defaults, options, false)
  9771. var doc = options.value
  9772. if (typeof doc == 'string') {
  9773. doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction)
  9774. } else if (options.mode) {
  9775. doc.modeOption = options.mode
  9776. }
  9777. this.doc = doc
  9778. var input = new CodeMirror.inputStyles[options.inputStyle](this)
  9779. var display = (this.display = new Display(place, doc, input, options))
  9780. display.wrapper.CodeMirror = this
  9781. themeChanged(this)
  9782. if (options.lineWrapping) {
  9783. this.display.wrapper.className += ' CodeMirror-wrap'
  9784. }
  9785. initScrollbars(this)
  9786. this.state = {
  9787. keyMaps: [], // stores maps added by addKeyMap
  9788. overlays: [], // highlighting overlays, as added by addOverlay
  9789. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  9790. overwrite: false,
  9791. delayingBlurEvent: false,
  9792. focused: false,
  9793. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  9794. pasteIncoming: -1,
  9795. cutIncoming: -1, // help recognize paste/cut edits in input.poll
  9796. selectingText: false,
  9797. draggingText: false,
  9798. highlight: new Delayed(), // stores highlight worker timeout
  9799. keySeq: null, // Unfinished key sequence
  9800. specialChars: null,
  9801. }
  9802. if (options.autofocus && !mobile) {
  9803. display.input.focus()
  9804. }
  9805. // Override magic textarea content restore that IE sometimes does
  9806. // on our hidden textarea on reload
  9807. if (ie && ie_version < 11) {
  9808. setTimeout(function () {
  9809. return this$1.display.input.reset(true)
  9810. }, 20)
  9811. }
  9812. registerEventHandlers(this)
  9813. ensureGlobalHandlers()
  9814. startOperation(this)
  9815. this.curOp.forceUpdate = true
  9816. attachDoc(this, doc)
  9817. if ((options.autofocus && !mobile) || this.hasFocus()) {
  9818. setTimeout(function () {
  9819. if (this$1.hasFocus() && !this$1.state.focused) {
  9820. onFocus(this$1)
  9821. }
  9822. }, 20)
  9823. } else {
  9824. onBlur(this)
  9825. }
  9826. for (var opt in optionHandlers) {
  9827. if (optionHandlers.hasOwnProperty(opt)) {
  9828. optionHandlers[opt](this, options[opt], Init)
  9829. }
  9830. }
  9831. maybeUpdateLineNumberWidth(this)
  9832. if (options.finishInit) {
  9833. options.finishInit(this)
  9834. }
  9835. for (var i = 0; i < initHooks.length; ++i) {
  9836. initHooks[i](this)
  9837. }
  9838. endOperation(this)
  9839. // Suppress optimizelegibility in Webkit, since it breaks text
  9840. // measuring on line wrapping boundaries.
  9841. if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == 'optimizelegibility') {
  9842. display.lineDiv.style.textRendering = 'auto'
  9843. }
  9844. }
  9845. // The default configuration options.
  9846. CodeMirror.defaults = defaults
  9847. // Functions to run when options are changed.
  9848. CodeMirror.optionHandlers = optionHandlers
  9849. // Attach the necessary event handlers when initializing the editor
  9850. function registerEventHandlers(cm) {
  9851. var d = cm.display
  9852. on(d.scroller, 'mousedown', operation(cm, onMouseDown))
  9853. // Older IE's will not fire a second mousedown for a double click
  9854. if (ie && ie_version < 11) {
  9855. on(
  9856. d.scroller,
  9857. 'dblclick',
  9858. operation(cm, function (e) {
  9859. if (signalDOMEvent(cm, e)) {
  9860. return
  9861. }
  9862. var pos = posFromMouse(cm, e)
  9863. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) {
  9864. return
  9865. }
  9866. e_preventDefault(e)
  9867. var word = cm.findWordAt(pos)
  9868. extendSelection(cm.doc, word.anchor, word.head)
  9869. })
  9870. )
  9871. } else {
  9872. on(d.scroller, 'dblclick', function (e) {
  9873. return signalDOMEvent(cm, e) || e_preventDefault(e)
  9874. })
  9875. }
  9876. // Some browsers fire contextmenu *after* opening the menu, at
  9877. // which point we can't mess with it anymore. Context menu is
  9878. // handled in onMouseDown for these browsers.
  9879. on(d.scroller, 'contextmenu', function (e) {
  9880. return onContextMenu(cm, e)
  9881. })
  9882. on(d.input.getField(), 'contextmenu', function (e) {
  9883. if (!d.scroller.contains(e.target)) {
  9884. onContextMenu(cm, e)
  9885. }
  9886. })
  9887. // Used to suppress mouse event handling when a touch happens
  9888. var touchFinished,
  9889. prevTouch = { end: 0 }
  9890. function finishTouch() {
  9891. if (d.activeTouch) {
  9892. touchFinished = setTimeout(function () {
  9893. return (d.activeTouch = null)
  9894. }, 1000)
  9895. prevTouch = d.activeTouch
  9896. prevTouch.end = +new Date()
  9897. }
  9898. }
  9899. function isMouseLikeTouchEvent(e) {
  9900. if (e.touches.length != 1) {
  9901. return false
  9902. }
  9903. var touch = e.touches[0]
  9904. return touch.radiusX <= 1 && touch.radiusY <= 1
  9905. }
  9906. function farAway(touch, other) {
  9907. if (other.left == null) {
  9908. return true
  9909. }
  9910. var dx = other.left - touch.left,
  9911. dy = other.top - touch.top
  9912. return dx * dx + dy * dy > 20 * 20
  9913. }
  9914. on(d.scroller, 'touchstart', function (e) {
  9915. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  9916. d.input.ensurePolled()
  9917. clearTimeout(touchFinished)
  9918. var now = +new Date()
  9919. d.activeTouch = { start: now, moved: false, prev: now - prevTouch.end <= 300 ? prevTouch : null }
  9920. if (e.touches.length == 1) {
  9921. d.activeTouch.left = e.touches[0].pageX
  9922. d.activeTouch.top = e.touches[0].pageY
  9923. }
  9924. }
  9925. })
  9926. on(d.scroller, 'touchmove', function () {
  9927. if (d.activeTouch) {
  9928. d.activeTouch.moved = true
  9929. }
  9930. })
  9931. on(d.scroller, 'touchend', function (e) {
  9932. var touch = d.activeTouch
  9933. if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date() - touch.start < 300) {
  9934. var pos = cm.coordsChar(d.activeTouch, 'page'),
  9935. range
  9936. if (!touch.prev || farAway(touch, touch.prev)) {
  9937. // Single tap
  9938. range = new Range(pos, pos)
  9939. } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) {
  9940. // Double tap
  9941. range = cm.findWordAt(pos)
  9942. } // Triple tap
  9943. else {
  9944. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)))
  9945. }
  9946. cm.setSelection(range.anchor, range.head)
  9947. cm.focus()
  9948. e_preventDefault(e)
  9949. }
  9950. finishTouch()
  9951. })
  9952. on(d.scroller, 'touchcancel', finishTouch)
  9953. // Sync scrolling between fake scrollbars and real scrollable
  9954. // area, ensure viewport is updated when scrolling.
  9955. on(d.scroller, 'scroll', function () {
  9956. if (d.scroller.clientHeight) {
  9957. updateScrollTop(cm, d.scroller.scrollTop)
  9958. setScrollLeft(cm, d.scroller.scrollLeft, true)
  9959. signal(cm, 'scroll', cm)
  9960. }
  9961. })
  9962. // Listen to wheel events in order to try and update the viewport on time.
  9963. on(d.scroller, 'mousewheel', function (e) {
  9964. return onScrollWheel(cm, e)
  9965. })
  9966. on(d.scroller, 'DOMMouseScroll', function (e) {
  9967. return onScrollWheel(cm, e)
  9968. })
  9969. // Prevent wrapper from ever scrolling
  9970. on(d.wrapper, 'scroll', function () {
  9971. return (d.wrapper.scrollTop = d.wrapper.scrollLeft = 0)
  9972. })
  9973. d.dragFunctions = {
  9974. enter: function (e) {
  9975. if (!signalDOMEvent(cm, e)) {
  9976. e_stop(e)
  9977. }
  9978. },
  9979. over: function (e) {
  9980. if (!signalDOMEvent(cm, e)) {
  9981. onDragOver(cm, e)
  9982. e_stop(e)
  9983. }
  9984. },
  9985. start: function (e) {
  9986. return onDragStart(cm, e)
  9987. },
  9988. drop: operation(cm, onDrop),
  9989. leave: function (e) {
  9990. if (!signalDOMEvent(cm, e)) {
  9991. clearDragCursor(cm)
  9992. }
  9993. },
  9994. }
  9995. var inp = d.input.getField()
  9996. on(inp, 'keyup', function (e) {
  9997. return onKeyUp.call(cm, e)
  9998. })
  9999. on(inp, 'keydown', operation(cm, onKeyDown))
  10000. on(inp, 'keypress', operation(cm, onKeyPress))
  10001. on(inp, 'focus', function (e) {
  10002. return onFocus(cm, e)
  10003. })
  10004. on(inp, 'blur', function (e) {
  10005. return onBlur(cm, e)
  10006. })
  10007. }
  10008. var initHooks = []
  10009. CodeMirror.defineInitHook = function (f) {
  10010. return initHooks.push(f)
  10011. }
  10012. // Indent the given line. The how parameter can be "smart",
  10013. // "add"/null, "subtract", or "prev". When aggressive is false
  10014. // (typically set to true for forced single-line indents), empty
  10015. // lines are not indented, and places where the mode returns Pass
  10016. // are left alone.
  10017. function indentLine(cm, n, how, aggressive) {
  10018. var doc = cm.doc,
  10019. state
  10020. if (how == null) {
  10021. how = 'add'
  10022. }
  10023. if (how == 'smart') {
  10024. // Fall back to "prev" when the mode doesn't have an indentation
  10025. // method.
  10026. if (!doc.mode.indent) {
  10027. how = 'prev'
  10028. } else {
  10029. state = getContextBefore(cm, n).state
  10030. }
  10031. }
  10032. var tabSize = cm.options.tabSize
  10033. var line = getLine(doc, n),
  10034. curSpace = countColumn(line.text, null, tabSize)
  10035. if (line.stateAfter) {
  10036. line.stateAfter = null
  10037. }
  10038. var curSpaceString = line.text.match(/^\s*/)[0],
  10039. indentation
  10040. if (!aggressive && !/\S/.test(line.text)) {
  10041. indentation = 0
  10042. how = 'not'
  10043. } else if (how == 'smart') {
  10044. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  10045. if (indentation == Pass || indentation > 150) {
  10046. if (!aggressive) {
  10047. return
  10048. }
  10049. how = 'prev'
  10050. }
  10051. }
  10052. if (how == 'prev') {
  10053. if (n > doc.first) {
  10054. indentation = countColumn(getLine(doc, n - 1).text, null, tabSize)
  10055. } else {
  10056. indentation = 0
  10057. }
  10058. } else if (how == 'add') {
  10059. indentation = curSpace + cm.options.indentUnit
  10060. } else if (how == 'subtract') {
  10061. indentation = curSpace - cm.options.indentUnit
  10062. } else if (typeof how == 'number') {
  10063. indentation = curSpace + how
  10064. }
  10065. indentation = Math.max(0, indentation)
  10066. var indentString = '',
  10067. pos = 0
  10068. if (cm.options.indentWithTabs) {
  10069. for (var i = Math.floor(indentation / tabSize); i; --i) {
  10070. pos += tabSize
  10071. indentString += '\t'
  10072. }
  10073. }
  10074. if (pos < indentation) {
  10075. indentString += spaceStr(indentation - pos)
  10076. }
  10077. if (indentString != curSpaceString) {
  10078. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), '+input')
  10079. line.stateAfter = null
  10080. return true
  10081. } else {
  10082. // Ensure that, if the cursor was in the whitespace at the start
  10083. // of the line, it is moved to the end of that space.
  10084. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  10085. var range = doc.sel.ranges[i$1]
  10086. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  10087. var pos$1 = Pos(n, curSpaceString.length)
  10088. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  10089. break
  10090. }
  10091. }
  10092. }
  10093. }
  10094. // This will be set to a {lineWise: bool, text: [string]} object, so
  10095. // that, when pasting, we know what kind of selections the copied
  10096. // text was made out of.
  10097. var lastCopied = null
  10098. function setLastCopied(newLastCopied) {
  10099. lastCopied = newLastCopied
  10100. }
  10101. function applyTextInput(cm, inserted, deleted, sel, origin) {
  10102. var doc = cm.doc
  10103. cm.display.shift = false
  10104. if (!sel) {
  10105. sel = doc.sel
  10106. }
  10107. var recent = +new Date() - 200
  10108. var paste = origin == 'paste' || cm.state.pasteIncoming > recent
  10109. var textLines = splitLinesAuto(inserted),
  10110. multiPaste = null
  10111. // When pasting N lines into N selections, insert one line per selection
  10112. if (paste && sel.ranges.length > 1) {
  10113. if (lastCopied && lastCopied.text.join('\n') == inserted) {
  10114. if (sel.ranges.length % lastCopied.text.length == 0) {
  10115. multiPaste = []
  10116. for (var i = 0; i < lastCopied.text.length; i++) {
  10117. multiPaste.push(doc.splitLines(lastCopied.text[i]))
  10118. }
  10119. }
  10120. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  10121. multiPaste = map(textLines, function (l) {
  10122. return [l]
  10123. })
  10124. }
  10125. }
  10126. var updateInput = cm.curOp.updateInput
  10127. // Normal behavior is to insert the new text into every selection
  10128. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  10129. var range = sel.ranges[i$1]
  10130. var from = range.from(),
  10131. to = range.to()
  10132. if (range.empty()) {
  10133. if (deleted && deleted > 0) {
  10134. // Handle deletion
  10135. from = Pos(from.line, from.ch - deleted)
  10136. } else if (cm.state.overwrite && !paste) {
  10137. // Handle overwrite
  10138. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length))
  10139. } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join('\n') == textLines.join('\n')) {
  10140. from = to = Pos(from.line, 0)
  10141. }
  10142. }
  10143. var changeEvent = {
  10144. from: from,
  10145. to: to,
  10146. text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  10147. origin: origin || (paste ? 'paste' : cm.state.cutIncoming > recent ? 'cut' : '+input'),
  10148. }
  10149. makeChange(cm.doc, changeEvent)
  10150. signalLater(cm, 'inputRead', cm, changeEvent)
  10151. }
  10152. if (inserted && !paste) {
  10153. triggerElectric(cm, inserted)
  10154. }
  10155. ensureCursorVisible(cm)
  10156. if (cm.curOp.updateInput < 2) {
  10157. cm.curOp.updateInput = updateInput
  10158. }
  10159. cm.curOp.typing = true
  10160. cm.state.pasteIncoming = cm.state.cutIncoming = -1
  10161. }
  10162. function handlePaste(e, cm) {
  10163. var pasted = e.clipboardData && e.clipboardData.getData('Text')
  10164. if (pasted) {
  10165. e.preventDefault()
  10166. if (!cm.isReadOnly() && !cm.options.disableInput) {
  10167. runInOp(cm, function () {
  10168. return applyTextInput(cm, pasted, 0, null, 'paste')
  10169. })
  10170. }
  10171. return true
  10172. }
  10173. }
  10174. function triggerElectric(cm, inserted) {
  10175. // When an 'electric' character is inserted, immediately trigger a reindent
  10176. if (!cm.options.electricChars || !cm.options.smartIndent) {
  10177. return
  10178. }
  10179. var sel = cm.doc.sel
  10180. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  10181. var range = sel.ranges[i]
  10182. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) {
  10183. continue
  10184. }
  10185. var mode = cm.getModeAt(range.head)
  10186. var indented = false
  10187. if (mode.electricChars) {
  10188. for (var j = 0; j < mode.electricChars.length; j++) {
  10189. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  10190. indented = indentLine(cm, range.head.line, 'smart')
  10191. break
  10192. }
  10193. }
  10194. } else if (mode.electricInput) {
  10195. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) {
  10196. indented = indentLine(cm, range.head.line, 'smart')
  10197. }
  10198. }
  10199. if (indented) {
  10200. signalLater(cm, 'electricInput', cm, range.head.line)
  10201. }
  10202. }
  10203. }
  10204. function copyableRanges(cm) {
  10205. var text = [],
  10206. ranges = []
  10207. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  10208. var line = cm.doc.sel.ranges[i].head.line
  10209. var lineRange = { anchor: Pos(line, 0), head: Pos(line + 1, 0) }
  10210. ranges.push(lineRange)
  10211. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  10212. }
  10213. return { text: text, ranges: ranges }
  10214. }
  10215. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  10216. field.setAttribute('autocorrect', autocorrect ? '' : 'off')
  10217. field.setAttribute('autocapitalize', autocapitalize ? '' : 'off')
  10218. field.setAttribute('spellcheck', !!spellcheck)
  10219. }
  10220. function hiddenTextarea() {
  10221. var te = elt('textarea', null, null, 'position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none')
  10222. var div = elt('div', [te], null, 'overflow: hidden; position: relative; width: 3px; height: 0px;')
  10223. // The textarea is kept positioned near the cursor to prevent the
  10224. // fact that it'll be scrolled into view on input from scrolling
  10225. // our fake cursor out of view. On webkit, when wrap=off, paste is
  10226. // very slow. So make the area wide instead.
  10227. if (webkit) {
  10228. te.style.width = '1000px'
  10229. } else {
  10230. te.setAttribute('wrap', 'off')
  10231. }
  10232. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  10233. if (ios) {
  10234. te.style.border = '1px solid black'
  10235. }
  10236. disableBrowserMagic(te)
  10237. return div
  10238. }
  10239. // The publicly visible API. Note that methodOp(f) means
  10240. // 'wrap f in an operation, performed on its `this` parameter'.
  10241. // This is not the complete set of editor methods. Most of the
  10242. // methods defined on the Doc type are also injected into
  10243. // CodeMirror.prototype, for backwards compatibility and
  10244. // convenience.
  10245. function addEditorMethods(CodeMirror) {
  10246. var optionHandlers = CodeMirror.optionHandlers
  10247. var helpers = (CodeMirror.helpers = {})
  10248. CodeMirror.prototype = {
  10249. constructor: CodeMirror,
  10250. focus: function () {
  10251. window.focus()
  10252. this.display.input.focus()
  10253. },
  10254. setOption: function (option, value) {
  10255. var options = this.options,
  10256. old = options[option]
  10257. if (options[option] == value && option != 'mode') {
  10258. return
  10259. }
  10260. options[option] = value
  10261. if (optionHandlers.hasOwnProperty(option)) {
  10262. operation(this, optionHandlers[option])(this, value, old)
  10263. }
  10264. signal(this, 'optionChange', this, option)
  10265. },
  10266. getOption: function (option) {
  10267. return this.options[option]
  10268. },
  10269. getDoc: function () {
  10270. return this.doc
  10271. },
  10272. addKeyMap: function (map, bottom) {
  10273. this.state.keyMaps[bottom ? 'push' : 'unshift'](getKeyMap(map))
  10274. },
  10275. removeKeyMap: function (map) {
  10276. var maps = this.state.keyMaps
  10277. for (var i = 0; i < maps.length; ++i) {
  10278. if (maps[i] == map || maps[i].name == map) {
  10279. maps.splice(i, 1)
  10280. return true
  10281. }
  10282. }
  10283. },
  10284. addOverlay: methodOp(function (spec, options) {
  10285. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  10286. if (mode.startState) {
  10287. throw new Error('Overlays may not be stateful.')
  10288. }
  10289. insertSorted(this.state.overlays, { mode: mode, modeSpec: spec, opaque: options && options.opaque, priority: (options && options.priority) || 0 }, function (overlay) {
  10290. return overlay.priority
  10291. })
  10292. this.state.modeGen++
  10293. regChange(this)
  10294. }),
  10295. removeOverlay: methodOp(function (spec) {
  10296. var overlays = this.state.overlays
  10297. for (var i = 0; i < overlays.length; ++i) {
  10298. var cur = overlays[i].modeSpec
  10299. if (cur == spec || (typeof spec == 'string' && cur.name == spec)) {
  10300. overlays.splice(i, 1)
  10301. this.state.modeGen++
  10302. regChange(this)
  10303. return
  10304. }
  10305. }
  10306. }),
  10307. indentLine: methodOp(function (n, dir, aggressive) {
  10308. if (typeof dir != 'string' && typeof dir != 'number') {
  10309. if (dir == null) {
  10310. dir = this.options.smartIndent ? 'smart' : 'prev'
  10311. } else {
  10312. dir = dir ? 'add' : 'subtract'
  10313. }
  10314. }
  10315. if (isLine(this.doc, n)) {
  10316. indentLine(this, n, dir, aggressive)
  10317. }
  10318. }),
  10319. indentSelection: methodOp(function (how) {
  10320. var ranges = this.doc.sel.ranges,
  10321. end = -1
  10322. for (var i = 0; i < ranges.length; i++) {
  10323. var range = ranges[i]
  10324. if (!range.empty()) {
  10325. var from = range.from(),
  10326. to = range.to()
  10327. var start = Math.max(end, from.line)
  10328. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  10329. for (var j = start; j < end; ++j) {
  10330. indentLine(this, j, how)
  10331. }
  10332. var newRanges = this.doc.sel.ranges
  10333. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) {
  10334. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll)
  10335. }
  10336. } else if (range.head.line > end) {
  10337. indentLine(this, range.head.line, how, true)
  10338. end = range.head.line
  10339. if (i == this.doc.sel.primIndex) {
  10340. ensureCursorVisible(this)
  10341. }
  10342. }
  10343. }
  10344. }),
  10345. // Fetch the parser token for a given character. Useful for hacks
  10346. // that want to inspect the mode state (say, for completion).
  10347. getTokenAt: function (pos, precise) {
  10348. return takeToken(this, pos, precise)
  10349. },
  10350. getLineTokens: function (line, precise) {
  10351. return takeToken(this, Pos(line), precise, true)
  10352. },
  10353. getTokenTypeAt: function (pos) {
  10354. pos = clipPos(this.doc, pos)
  10355. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  10356. var before = 0,
  10357. after = (styles.length - 1) / 2,
  10358. ch = pos.ch
  10359. var type
  10360. if (ch == 0) {
  10361. type = styles[2]
  10362. } else {
  10363. for (;;) {
  10364. var mid = (before + after) >> 1
  10365. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) {
  10366. after = mid
  10367. } else if (styles[mid * 2 + 1] < ch) {
  10368. before = mid + 1
  10369. } else {
  10370. type = styles[mid * 2 + 2]
  10371. break
  10372. }
  10373. }
  10374. }
  10375. var cut = type ? type.indexOf('overlay ') : -1
  10376. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  10377. },
  10378. getModeAt: function (pos) {
  10379. var mode = this.doc.mode
  10380. if (!mode.innerMode) {
  10381. return mode
  10382. }
  10383. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  10384. },
  10385. getHelper: function (pos, type) {
  10386. return this.getHelpers(pos, type)[0]
  10387. },
  10388. getHelpers: function (pos, type) {
  10389. var found = []
  10390. if (!helpers.hasOwnProperty(type)) {
  10391. return found
  10392. }
  10393. var help = helpers[type],
  10394. mode = this.getModeAt(pos)
  10395. if (typeof mode[type] == 'string') {
  10396. if (help[mode[type]]) {
  10397. found.push(help[mode[type]])
  10398. }
  10399. } else if (mode[type]) {
  10400. for (var i = 0; i < mode[type].length; i++) {
  10401. var val = help[mode[type][i]]
  10402. if (val) {
  10403. found.push(val)
  10404. }
  10405. }
  10406. } else if (mode.helperType && help[mode.helperType]) {
  10407. found.push(help[mode.helperType])
  10408. } else if (help[mode.name]) {
  10409. found.push(help[mode.name])
  10410. }
  10411. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  10412. var cur = help._global[i$1]
  10413. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) {
  10414. found.push(cur.val)
  10415. }
  10416. }
  10417. return found
  10418. },
  10419. getStateAfter: function (line, precise) {
  10420. var doc = this.doc
  10421. line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line)
  10422. return getContextBefore(this, line + 1, precise).state
  10423. },
  10424. cursorCoords: function (start, mode) {
  10425. var pos,
  10426. range = this.doc.sel.primary()
  10427. if (start == null) {
  10428. pos = range.head
  10429. } else if (typeof start == 'object') {
  10430. pos = clipPos(this.doc, start)
  10431. } else {
  10432. pos = start ? range.from() : range.to()
  10433. }
  10434. return cursorCoords(this, pos, mode || 'page')
  10435. },
  10436. charCoords: function (pos, mode) {
  10437. return charCoords(this, clipPos(this.doc, pos), mode || 'page')
  10438. },
  10439. coordsChar: function (coords, mode) {
  10440. coords = fromCoordSystem(this, coords, mode || 'page')
  10441. return coordsChar(this, coords.left, coords.top)
  10442. },
  10443. lineAtHeight: function (height, mode) {
  10444. height = fromCoordSystem(this, { top: height, left: 0 }, mode || 'page').top
  10445. return lineAtHeight(this.doc, height + this.display.viewOffset)
  10446. },
  10447. heightAtLine: function (line, mode, includeWidgets) {
  10448. var end = false,
  10449. lineObj
  10450. if (typeof line == 'number') {
  10451. var last = this.doc.first + this.doc.size - 1
  10452. if (line < this.doc.first) {
  10453. line = this.doc.first
  10454. } else if (line > last) {
  10455. line = last
  10456. end = true
  10457. }
  10458. lineObj = getLine(this.doc, line)
  10459. } else {
  10460. lineObj = line
  10461. }
  10462. return intoCoordSystem(this, lineObj, { top: 0, left: 0 }, mode || 'page', includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0)
  10463. },
  10464. defaultTextHeight: function () {
  10465. return textHeight(this.display)
  10466. },
  10467. defaultCharWidth: function () {
  10468. return charWidth(this.display)
  10469. },
  10470. getViewport: function () {
  10471. return { from: this.display.viewFrom, to: this.display.viewTo }
  10472. },
  10473. addWidget: function (pos, node, scroll, vert, horiz) {
  10474. var display = this.display
  10475. pos = cursorCoords(this, clipPos(this.doc, pos))
  10476. var top = pos.bottom,
  10477. left = pos.left
  10478. node.style.position = 'absolute'
  10479. node.setAttribute('cm-ignore-events', 'true')
  10480. this.display.input.setUneditable(node)
  10481. display.sizer.appendChild(node)
  10482. if (vert == 'over') {
  10483. top = pos.top
  10484. } else if (vert == 'above' || vert == 'near') {
  10485. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  10486. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  10487. // Default to positioning above (if specified and possible); otherwise default to positioning below
  10488. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {
  10489. top = pos.top - node.offsetHeight
  10490. } else if (pos.bottom + node.offsetHeight <= vspace) {
  10491. top = pos.bottom
  10492. }
  10493. if (left + node.offsetWidth > hspace) {
  10494. left = hspace - node.offsetWidth
  10495. }
  10496. }
  10497. node.style.top = top + 'px'
  10498. node.style.left = node.style.right = ''
  10499. if (horiz == 'right') {
  10500. left = display.sizer.clientWidth - node.offsetWidth
  10501. node.style.right = '0px'
  10502. } else {
  10503. if (horiz == 'left') {
  10504. left = 0
  10505. } else if (horiz == 'middle') {
  10506. left = (display.sizer.clientWidth - node.offsetWidth) / 2
  10507. }
  10508. node.style.left = left + 'px'
  10509. }
  10510. if (scroll) {
  10511. scrollIntoView(this, { left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight })
  10512. }
  10513. },
  10514. triggerOnKeyDown: methodOp(onKeyDown),
  10515. triggerOnKeyPress: methodOp(onKeyPress),
  10516. triggerOnKeyUp: onKeyUp,
  10517. triggerOnMouseDown: methodOp(onMouseDown),
  10518. execCommand: function (cmd) {
  10519. if (commands.hasOwnProperty(cmd)) {
  10520. return commands[cmd].call(null, this)
  10521. }
  10522. },
  10523. triggerElectric: methodOp(function (text) {
  10524. triggerElectric(this, text)
  10525. }),
  10526. findPosH: function (from, amount, unit, visually) {
  10527. var dir = 1
  10528. if (amount < 0) {
  10529. dir = -1
  10530. amount = -amount
  10531. }
  10532. var cur = clipPos(this.doc, from)
  10533. for (var i = 0; i < amount; ++i) {
  10534. cur = findPosH(this.doc, cur, dir, unit, visually)
  10535. if (cur.hitSide) {
  10536. break
  10537. }
  10538. }
  10539. return cur
  10540. },
  10541. moveH: methodOp(function (dir, unit) {
  10542. var this$1 = this
  10543. this.extendSelectionsBy(function (range) {
  10544. if (this$1.display.shift || this$1.doc.extend || range.empty()) {
  10545. return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually)
  10546. } else {
  10547. return dir < 0 ? range.from() : range.to()
  10548. }
  10549. }, sel_move)
  10550. }),
  10551. deleteH: methodOp(function (dir, unit) {
  10552. var sel = this.doc.sel,
  10553. doc = this.doc
  10554. if (sel.somethingSelected()) {
  10555. doc.replaceSelection('', null, '+delete')
  10556. } else {
  10557. deleteNearSelection(this, function (range) {
  10558. var other = findPosH(doc, range.head, dir, unit, false)
  10559. return dir < 0 ? { from: other, to: range.head } : { from: range.head, to: other }
  10560. })
  10561. }
  10562. }),
  10563. findPosV: function (from, amount, unit, goalColumn) {
  10564. var dir = 1,
  10565. x = goalColumn
  10566. if (amount < 0) {
  10567. dir = -1
  10568. amount = -amount
  10569. }
  10570. var cur = clipPos(this.doc, from)
  10571. for (var i = 0; i < amount; ++i) {
  10572. var coords = cursorCoords(this, cur, 'div')
  10573. if (x == null) {
  10574. x = coords.left
  10575. } else {
  10576. coords.left = x
  10577. }
  10578. cur = findPosV(this, coords, dir, unit)
  10579. if (cur.hitSide) {
  10580. break
  10581. }
  10582. }
  10583. return cur
  10584. },
  10585. moveV: methodOp(function (dir, unit) {
  10586. var this$1 = this
  10587. var doc = this.doc,
  10588. goals = []
  10589. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  10590. doc.extendSelectionsBy(function (range) {
  10591. if (collapse) {
  10592. return dir < 0 ? range.from() : range.to()
  10593. }
  10594. var headPos = cursorCoords(this$1, range.head, 'div')
  10595. if (range.goalColumn != null) {
  10596. headPos.left = range.goalColumn
  10597. }
  10598. goals.push(headPos.left)
  10599. var pos = findPosV(this$1, headPos, dir, unit)
  10600. if (unit == 'page' && range == doc.sel.primary()) {
  10601. addToScrollTop(this$1, charCoords(this$1, pos, 'div').top - headPos.top)
  10602. }
  10603. return pos
  10604. }, sel_move)
  10605. if (goals.length) {
  10606. for (var i = 0; i < doc.sel.ranges.length; i++) {
  10607. doc.sel.ranges[i].goalColumn = goals[i]
  10608. }
  10609. }
  10610. }),
  10611. // Find the word at the given position (as returned by coordsChar).
  10612. findWordAt: function (pos) {
  10613. var doc = this.doc,
  10614. line = getLine(doc, pos.line).text
  10615. var start = pos.ch,
  10616. end = pos.ch
  10617. if (line) {
  10618. var helper = this.getHelper(pos, 'wordChars')
  10619. if ((pos.sticky == 'before' || end == line.length) && start) {
  10620. --start
  10621. } else {
  10622. ++end
  10623. }
  10624. var startChar = line.charAt(start)
  10625. var check = isWordChar(startChar, helper)
  10626. ? function (ch) {
  10627. return isWordChar(ch, helper)
  10628. }
  10629. : /\s/.test(startChar)
  10630. ? function (ch) {
  10631. return /\s/.test(ch)
  10632. }
  10633. : function (ch) {
  10634. return !/\s/.test(ch) && !isWordChar(ch)
  10635. }
  10636. while (start > 0 && check(line.charAt(start - 1))) {
  10637. --start
  10638. }
  10639. while (end < line.length && check(line.charAt(end))) {
  10640. ++end
  10641. }
  10642. }
  10643. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  10644. },
  10645. toggleOverwrite: function (value) {
  10646. if (value != null && value == this.state.overwrite) {
  10647. return
  10648. }
  10649. if ((this.state.overwrite = !this.state.overwrite)) {
  10650. addClass(this.display.cursorDiv, 'CodeMirror-overwrite')
  10651. } else {
  10652. rmClass(this.display.cursorDiv, 'CodeMirror-overwrite')
  10653. }
  10654. signal(this, 'overwriteToggle', this, this.state.overwrite)
  10655. },
  10656. hasFocus: function () {
  10657. return this.display.input.getField() == activeElt()
  10658. },
  10659. isReadOnly: function () {
  10660. return !!(this.options.readOnly || this.doc.cantEdit)
  10661. },
  10662. scrollTo: methodOp(function (x, y) {
  10663. scrollToCoords(this, x, y)
  10664. }),
  10665. getScrollInfo: function () {
  10666. var scroller = this.display.scroller
  10667. return {
  10668. left: scroller.scrollLeft,
  10669. top: scroller.scrollTop,
  10670. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  10671. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  10672. clientHeight: displayHeight(this),
  10673. clientWidth: displayWidth(this),
  10674. }
  10675. },
  10676. scrollIntoView: methodOp(function (range, margin) {
  10677. if (range == null) {
  10678. range = { from: this.doc.sel.primary().head, to: null }
  10679. if (margin == null) {
  10680. margin = this.options.cursorScrollMargin
  10681. }
  10682. } else if (typeof range == 'number') {
  10683. range = { from: Pos(range, 0), to: null }
  10684. } else if (range.from == null) {
  10685. range = { from: range, to: null }
  10686. }
  10687. if (!range.to) {
  10688. range.to = range.from
  10689. }
  10690. range.margin = margin || 0
  10691. if (range.from.line != null) {
  10692. scrollToRange(this, range)
  10693. } else {
  10694. scrollToCoordsRange(this, range.from, range.to, range.margin)
  10695. }
  10696. }),
  10697. setSize: methodOp(function (width, height) {
  10698. var this$1 = this
  10699. var interpret = function (val) {
  10700. return typeof val == 'number' || /^\d+$/.test(String(val)) ? val + 'px' : val
  10701. }
  10702. if (width != null) {
  10703. this.display.wrapper.style.width = interpret(width)
  10704. }
  10705. if (height != null) {
  10706. this.display.wrapper.style.height = interpret(height)
  10707. }
  10708. if (this.options.lineWrapping) {
  10709. clearLineMeasurementCache(this)
  10710. }
  10711. var lineNo = this.display.viewFrom
  10712. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  10713. if (line.widgets) {
  10714. for (var i = 0; i < line.widgets.length; i++) {
  10715. if (line.widgets[i].noHScroll) {
  10716. regLineChange(this$1, lineNo, 'widget')
  10717. break
  10718. }
  10719. }
  10720. }
  10721. ++lineNo
  10722. })
  10723. this.curOp.forceUpdate = true
  10724. signal(this, 'refresh', this)
  10725. }),
  10726. operation: function (f) {
  10727. return runInOp(this, f)
  10728. },
  10729. startOperation: function () {
  10730. return startOperation(this)
  10731. },
  10732. endOperation: function () {
  10733. return endOperation(this)
  10734. },
  10735. refresh: methodOp(function () {
  10736. var oldHeight = this.display.cachedTextHeight
  10737. regChange(this)
  10738. this.curOp.forceUpdate = true
  10739. clearCaches(this)
  10740. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop)
  10741. updateGutterSpace(this.display)
  10742. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) {
  10743. estimateLineHeights(this)
  10744. }
  10745. signal(this, 'refresh', this)
  10746. }),
  10747. swapDoc: methodOp(function (doc) {
  10748. var old = this.doc
  10749. old.cm = null
  10750. // Cancel the current text selection if any (#5821)
  10751. if (this.state.selectingText) {
  10752. this.state.selectingText()
  10753. }
  10754. attachDoc(this, doc)
  10755. clearCaches(this)
  10756. this.display.input.reset()
  10757. scrollToCoords(this, doc.scrollLeft, doc.scrollTop)
  10758. this.curOp.forceScroll = true
  10759. signalLater(this, 'swapDoc', this, old)
  10760. return old
  10761. }),
  10762. phrase: function (phraseText) {
  10763. var phrases = this.options.phrases
  10764. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  10765. },
  10766. getInputField: function () {
  10767. return this.display.input.getField()
  10768. },
  10769. getWrapperElement: function () {
  10770. return this.display.wrapper
  10771. },
  10772. getScrollerElement: function () {
  10773. return this.display.scroller
  10774. },
  10775. getGutterElement: function () {
  10776. return this.display.gutters
  10777. },
  10778. }
  10779. eventMixin(CodeMirror)
  10780. CodeMirror.registerHelper = function (type, name, value) {
  10781. if (!helpers.hasOwnProperty(type)) {
  10782. helpers[type] = CodeMirror[type] = { _global: [] }
  10783. }
  10784. helpers[type][name] = value
  10785. }
  10786. CodeMirror.registerGlobalHelper = function (type, name, predicate, value) {
  10787. CodeMirror.registerHelper(type, name, value)
  10788. helpers[type]._global.push({ pred: predicate, val: value })
  10789. }
  10790. }
  10791. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  10792. // right), unit can be "codepoint", "char", "column" (like char, but
  10793. // doesn't cross line boundaries), "word" (across next word), or
  10794. // "group" (to the start of next group of word or
  10795. // non-word-non-whitespace chars). The visually param controls
  10796. // whether, in right-to-left text, direction 1 means to move towards
  10797. // the next index in the string, or towards the character to the right
  10798. // of the current position. The resulting position will have a
  10799. // hitSide=true property if it reached the end of the document.
  10800. function findPosH(doc, pos, dir, unit, visually) {
  10801. var oldPos = pos
  10802. var origDir = dir
  10803. var lineObj = getLine(doc, pos.line)
  10804. var lineDir = visually && doc.direction == 'rtl' ? -dir : dir
  10805. function findNextLine() {
  10806. var l = pos.line + lineDir
  10807. if (l < doc.first || l >= doc.first + doc.size) {
  10808. return false
  10809. }
  10810. pos = new Pos(l, pos.ch, pos.sticky)
  10811. return (lineObj = getLine(doc, l))
  10812. }
  10813. function moveOnce(boundToLine) {
  10814. var next
  10815. if (unit == 'codepoint') {
  10816. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1))
  10817. if (isNaN(ch)) {
  10818. next = null
  10819. } else {
  10820. var astral = dir > 0 ? ch >= 0xd800 && ch < 0xdc00 : ch >= 0xdc00 && ch < 0xdfff
  10821. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir)
  10822. }
  10823. } else if (visually) {
  10824. next = moveVisually(doc.cm, lineObj, pos, dir)
  10825. } else {
  10826. next = moveLogically(lineObj, pos, dir)
  10827. }
  10828. if (next == null) {
  10829. if (!boundToLine && findNextLine()) {
  10830. pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir)
  10831. } else {
  10832. return false
  10833. }
  10834. } else {
  10835. pos = next
  10836. }
  10837. return true
  10838. }
  10839. if (unit == 'char' || unit == 'codepoint') {
  10840. moveOnce()
  10841. } else if (unit == 'column') {
  10842. moveOnce(true)
  10843. } else if (unit == 'word' || unit == 'group') {
  10844. var sawType = null,
  10845. group = unit == 'group'
  10846. var helper = doc.cm && doc.cm.getHelper(pos, 'wordChars')
  10847. for (var first = true; ; first = false) {
  10848. if (dir < 0 && !moveOnce(!first)) {
  10849. break
  10850. }
  10851. var cur = lineObj.text.charAt(pos.ch) || '\n'
  10852. var type = isWordChar(cur, helper) ? 'w' : group && cur == '\n' ? 'n' : !group || /\s/.test(cur) ? null : 'p'
  10853. if (group && !first && !type) {
  10854. type = 's'
  10855. }
  10856. if (sawType && sawType != type) {
  10857. if (dir < 0) {
  10858. dir = 1
  10859. moveOnce()
  10860. pos.sticky = 'after'
  10861. }
  10862. break
  10863. }
  10864. if (type) {
  10865. sawType = type
  10866. }
  10867. if (dir > 0 && !moveOnce(!first)) {
  10868. break
  10869. }
  10870. }
  10871. }
  10872. var result = skipAtomic(doc, pos, oldPos, origDir, true)
  10873. if (equalCursorPos(oldPos, result)) {
  10874. result.hitSide = true
  10875. }
  10876. return result
  10877. }
  10878. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  10879. // "page" or "line". The resulting position will have a hitSide=true
  10880. // property if it reached the end of the document.
  10881. function findPosV(cm, pos, dir, unit) {
  10882. var doc = cm.doc,
  10883. x = pos.left,
  10884. y
  10885. if (unit == 'page') {
  10886. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  10887. var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3)
  10888. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  10889. } else if (unit == 'line') {
  10890. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  10891. }
  10892. var target
  10893. for (;;) {
  10894. target = coordsChar(cm, x, y)
  10895. if (!target.outside) {
  10896. break
  10897. }
  10898. if (dir < 0 ? y <= 0 : y >= doc.height) {
  10899. target.hitSide = true
  10900. break
  10901. }
  10902. y += dir * 5
  10903. }
  10904. return target
  10905. }
  10906. // CONTENTEDITABLE INPUT STYLE
  10907. var ContentEditableInput = function (cm) {
  10908. this.cm = cm
  10909. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  10910. this.polling = new Delayed()
  10911. this.composing = null
  10912. this.gracePeriod = false
  10913. this.readDOMTimeout = null
  10914. }
  10915. ContentEditableInput.prototype.init = function (display) {
  10916. var this$1 = this
  10917. var input = this,
  10918. cm = input.cm
  10919. var div = (input.div = display.lineDiv)
  10920. div.contentEditable = true
  10921. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize)
  10922. function belongsToInput(e) {
  10923. for (var t = e.target; t; t = t.parentNode) {
  10924. if (t == div) {
  10925. return true
  10926. }
  10927. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) {
  10928. break
  10929. }
  10930. }
  10931. return false
  10932. }
  10933. on(div, 'paste', function (e) {
  10934. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) {
  10935. return
  10936. }
  10937. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  10938. if (ie_version <= 11) {
  10939. setTimeout(
  10940. operation(cm, function () {
  10941. return this$1.updateFromDOM()
  10942. }),
  10943. 20
  10944. )
  10945. }
  10946. })
  10947. on(div, 'compositionstart', function (e) {
  10948. this$1.composing = { data: e.data, done: false }
  10949. })
  10950. on(div, 'compositionupdate', function (e) {
  10951. if (!this$1.composing) {
  10952. this$1.composing = { data: e.data, done: false }
  10953. }
  10954. })
  10955. on(div, 'compositionend', function (e) {
  10956. if (this$1.composing) {
  10957. if (e.data != this$1.composing.data) {
  10958. this$1.readFromDOMSoon()
  10959. }
  10960. this$1.composing.done = true
  10961. }
  10962. })
  10963. on(div, 'touchstart', function () {
  10964. return input.forceCompositionEnd()
  10965. })
  10966. on(div, 'input', function () {
  10967. if (!this$1.composing) {
  10968. this$1.readFromDOMSoon()
  10969. }
  10970. })
  10971. function onCopyCut(e) {
  10972. if (!belongsToInput(e) || signalDOMEvent(cm, e)) {
  10973. return
  10974. }
  10975. if (cm.somethingSelected()) {
  10976. setLastCopied({ lineWise: false, text: cm.getSelections() })
  10977. if (e.type == 'cut') {
  10978. cm.replaceSelection('', null, 'cut')
  10979. }
  10980. } else if (!cm.options.lineWiseCopyCut) {
  10981. return
  10982. } else {
  10983. var ranges = copyableRanges(cm)
  10984. setLastCopied({ lineWise: true, text: ranges.text })
  10985. if (e.type == 'cut') {
  10986. cm.operation(function () {
  10987. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  10988. cm.replaceSelection('', null, 'cut')
  10989. })
  10990. }
  10991. }
  10992. if (e.clipboardData) {
  10993. e.clipboardData.clearData()
  10994. var content = lastCopied.text.join('\n')
  10995. // iOS exposes the clipboard API, but seems to discard content inserted into it
  10996. e.clipboardData.setData('Text', content)
  10997. if (e.clipboardData.getData('Text') == content) {
  10998. e.preventDefault()
  10999. return
  11000. }
  11001. }
  11002. // Old-fashioned briefly-focus-a-textarea hack
  11003. var kludge = hiddenTextarea(),
  11004. te = kludge.firstChild
  11005. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  11006. te.value = lastCopied.text.join('\n')
  11007. var hadFocus = activeElt()
  11008. selectInput(te)
  11009. setTimeout(function () {
  11010. cm.display.lineSpace.removeChild(kludge)
  11011. hadFocus.focus()
  11012. if (hadFocus == div) {
  11013. input.showPrimarySelection()
  11014. }
  11015. }, 50)
  11016. }
  11017. on(div, 'copy', onCopyCut)
  11018. on(div, 'cut', onCopyCut)
  11019. }
  11020. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  11021. // Label for screenreaders, accessibility
  11022. if (label) {
  11023. this.div.setAttribute('aria-label', label)
  11024. } else {
  11025. this.div.removeAttribute('aria-label')
  11026. }
  11027. }
  11028. ContentEditableInput.prototype.prepareSelection = function () {
  11029. var result = prepareSelection(this.cm, false)
  11030. result.focus = activeElt() == this.div
  11031. return result
  11032. }
  11033. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  11034. if (!info || !this.cm.display.view.length) {
  11035. return
  11036. }
  11037. if (info.focus || takeFocus) {
  11038. this.showPrimarySelection()
  11039. }
  11040. this.showMultipleSelections(info)
  11041. }
  11042. ContentEditableInput.prototype.getSelection = function () {
  11043. return this.cm.display.wrapper.ownerDocument.getSelection()
  11044. }
  11045. ContentEditableInput.prototype.showPrimarySelection = function () {
  11046. var sel = this.getSelection(),
  11047. cm = this.cm,
  11048. prim = cm.doc.sel.primary()
  11049. var from = prim.from(),
  11050. to = prim.to()
  11051. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  11052. sel.removeAllRanges()
  11053. return
  11054. }
  11055. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  11056. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset)
  11057. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) {
  11058. return
  11059. }
  11060. var view = cm.display.view
  11061. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || { node: view[0].measure.map[2], offset: 0 }
  11062. var end = to.line < cm.display.viewTo && posToDOM(cm, to)
  11063. if (!end) {
  11064. var measure = view[view.length - 1].measure
  11065. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  11066. end = { node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3] }
  11067. }
  11068. if (!start || !end) {
  11069. sel.removeAllRanges()
  11070. return
  11071. }
  11072. var old = sel.rangeCount && sel.getRangeAt(0),
  11073. rng
  11074. try {
  11075. rng = range(start.node, start.offset, end.offset, end.node)
  11076. } catch (e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  11077. if (rng) {
  11078. if (!gecko && cm.state.focused) {
  11079. sel.collapse(start.node, start.offset)
  11080. if (!rng.collapsed) {
  11081. sel.removeAllRanges()
  11082. sel.addRange(rng)
  11083. }
  11084. } else {
  11085. sel.removeAllRanges()
  11086. sel.addRange(rng)
  11087. }
  11088. if (old && sel.anchorNode == null) {
  11089. sel.addRange(old)
  11090. } else if (gecko) {
  11091. this.startGracePeriod()
  11092. }
  11093. }
  11094. this.rememberSelection()
  11095. }
  11096. ContentEditableInput.prototype.startGracePeriod = function () {
  11097. var this$1 = this
  11098. clearTimeout(this.gracePeriod)
  11099. this.gracePeriod = setTimeout(function () {
  11100. this$1.gracePeriod = false
  11101. if (this$1.selectionChanged()) {
  11102. this$1.cm.operation(function () {
  11103. return (this$1.cm.curOp.selectionChanged = true)
  11104. })
  11105. }
  11106. }, 20)
  11107. }
  11108. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  11109. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  11110. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  11111. }
  11112. ContentEditableInput.prototype.rememberSelection = function () {
  11113. var sel = this.getSelection()
  11114. this.lastAnchorNode = sel.anchorNode
  11115. this.lastAnchorOffset = sel.anchorOffset
  11116. this.lastFocusNode = sel.focusNode
  11117. this.lastFocusOffset = sel.focusOffset
  11118. }
  11119. ContentEditableInput.prototype.selectionInEditor = function () {
  11120. var sel = this.getSelection()
  11121. if (!sel.rangeCount) {
  11122. return false
  11123. }
  11124. var node = sel.getRangeAt(0).commonAncestorContainer
  11125. return contains(this.div, node)
  11126. }
  11127. ContentEditableInput.prototype.focus = function () {
  11128. if (this.cm.options.readOnly != 'nocursor') {
  11129. if (!this.selectionInEditor() || activeElt() != this.div) {
  11130. this.showSelection(this.prepareSelection(), true)
  11131. }
  11132. this.div.focus()
  11133. }
  11134. }
  11135. ContentEditableInput.prototype.blur = function () {
  11136. this.div.blur()
  11137. }
  11138. ContentEditableInput.prototype.getField = function () {
  11139. return this.div
  11140. }
  11141. ContentEditableInput.prototype.supportsTouch = function () {
  11142. return true
  11143. }
  11144. ContentEditableInput.prototype.receivedFocus = function () {
  11145. var this$1 = this
  11146. var input = this
  11147. if (this.selectionInEditor()) {
  11148. setTimeout(function () {
  11149. return this$1.pollSelection()
  11150. }, 20)
  11151. } else {
  11152. runInOp(this.cm, function () {
  11153. return (input.cm.curOp.selectionChanged = true)
  11154. })
  11155. }
  11156. function poll() {
  11157. if (input.cm.state.focused) {
  11158. input.pollSelection()
  11159. input.polling.set(input.cm.options.pollInterval, poll)
  11160. }
  11161. }
  11162. this.polling.set(this.cm.options.pollInterval, poll)
  11163. }
  11164. ContentEditableInput.prototype.selectionChanged = function () {
  11165. var sel = this.getSelection()
  11166. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  11167. }
  11168. ContentEditableInput.prototype.pollSelection = function () {
  11169. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) {
  11170. return
  11171. }
  11172. var sel = this.getSelection(),
  11173. cm = this.cm
  11174. // On Android Chrome (version 56, at least), backspacing into an
  11175. // uneditable block element will put the cursor in that element,
  11176. // and then, because it's not editable, hide the virtual keyboard.
  11177. // Because Android doesn't allow us to actually detect backspace
  11178. // presses in a sane way, this code checks for when that happens
  11179. // and simulates a backspace press in this case.
  11180. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  11181. this.cm.triggerOnKeyDown({ type: 'keydown', keyCode: 8, preventDefault: Math.abs })
  11182. this.blur()
  11183. this.focus()
  11184. return
  11185. }
  11186. if (this.composing) {
  11187. return
  11188. }
  11189. this.rememberSelection()
  11190. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  11191. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  11192. if (anchor && head) {
  11193. runInOp(cm, function () {
  11194. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  11195. if (anchor.bad || head.bad) {
  11196. cm.curOp.selectionChanged = true
  11197. }
  11198. })
  11199. }
  11200. }
  11201. ContentEditableInput.prototype.pollContent = function () {
  11202. if (this.readDOMTimeout != null) {
  11203. clearTimeout(this.readDOMTimeout)
  11204. this.readDOMTimeout = null
  11205. }
  11206. var cm = this.cm,
  11207. display = cm.display,
  11208. sel = cm.doc.sel.primary()
  11209. var from = sel.from(),
  11210. to = sel.to()
  11211. if (from.ch == 0 && from.line > cm.firstLine()) {
  11212. from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length)
  11213. }
  11214. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) {
  11215. to = Pos(to.line + 1, 0)
  11216. }
  11217. if (from.line < display.viewFrom || to.line > display.viewTo - 1) {
  11218. return false
  11219. }
  11220. var fromIndex, fromLine, fromNode
  11221. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  11222. fromLine = lineNo(display.view[0].line)
  11223. fromNode = display.view[0].node
  11224. } else {
  11225. fromLine = lineNo(display.view[fromIndex].line)
  11226. fromNode = display.view[fromIndex - 1].node.nextSibling
  11227. }
  11228. var toIndex = findViewIndex(cm, to.line)
  11229. var toLine, toNode
  11230. if (toIndex == display.view.length - 1) {
  11231. toLine = display.viewTo - 1
  11232. toNode = display.lineDiv.lastChild
  11233. } else {
  11234. toLine = lineNo(display.view[toIndex + 1].line) - 1
  11235. toNode = display.view[toIndex + 1].node.previousSibling
  11236. }
  11237. if (!fromNode) {
  11238. return false
  11239. }
  11240. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  11241. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  11242. while (newText.length > 1 && oldText.length > 1) {
  11243. if (lst(newText) == lst(oldText)) {
  11244. newText.pop()
  11245. oldText.pop()
  11246. toLine--
  11247. } else if (newText[0] == oldText[0]) {
  11248. newText.shift()
  11249. oldText.shift()
  11250. fromLine++
  11251. } else {
  11252. break
  11253. }
  11254. }
  11255. var cutFront = 0,
  11256. cutEnd = 0
  11257. var newTop = newText[0],
  11258. oldTop = oldText[0],
  11259. maxCutFront = Math.min(newTop.length, oldTop.length)
  11260. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {
  11261. ++cutFront
  11262. }
  11263. var newBot = lst(newText),
  11264. oldBot = lst(oldText)
  11265. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0))
  11266. while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  11267. ++cutEnd
  11268. }
  11269. // Try to move start of change to start of selection if ambiguous
  11270. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  11271. while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  11272. cutFront--
  11273. cutEnd++
  11274. }
  11275. }
  11276. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, '')
  11277. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, '')
  11278. var chFrom = Pos(fromLine, cutFront)
  11279. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  11280. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  11281. replaceRange(cm.doc, newText, chFrom, chTo, '+input')
  11282. return true
  11283. }
  11284. }
  11285. ContentEditableInput.prototype.ensurePolled = function () {
  11286. this.forceCompositionEnd()
  11287. }
  11288. ContentEditableInput.prototype.reset = function () {
  11289. this.forceCompositionEnd()
  11290. }
  11291. ContentEditableInput.prototype.forceCompositionEnd = function () {
  11292. if (!this.composing) {
  11293. return
  11294. }
  11295. clearTimeout(this.readDOMTimeout)
  11296. this.composing = null
  11297. this.updateFromDOM()
  11298. this.div.blur()
  11299. this.div.focus()
  11300. }
  11301. ContentEditableInput.prototype.readFromDOMSoon = function () {
  11302. var this$1 = this
  11303. if (this.readDOMTimeout != null) {
  11304. return
  11305. }
  11306. this.readDOMTimeout = setTimeout(function () {
  11307. this$1.readDOMTimeout = null
  11308. if (this$1.composing) {
  11309. if (this$1.composing.done) {
  11310. this$1.composing = null
  11311. } else {
  11312. return
  11313. }
  11314. }
  11315. this$1.updateFromDOM()
  11316. }, 80)
  11317. }
  11318. ContentEditableInput.prototype.updateFromDOM = function () {
  11319. var this$1 = this
  11320. if (this.cm.isReadOnly() || !this.pollContent()) {
  11321. runInOp(this.cm, function () {
  11322. return regChange(this$1.cm)
  11323. })
  11324. }
  11325. }
  11326. ContentEditableInput.prototype.setUneditable = function (node) {
  11327. node.contentEditable = 'false'
  11328. }
  11329. ContentEditableInput.prototype.onKeyPress = function (e) {
  11330. if (e.charCode == 0 || this.composing) {
  11331. return
  11332. }
  11333. e.preventDefault()
  11334. if (!this.cm.isReadOnly()) {
  11335. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0)
  11336. }
  11337. }
  11338. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  11339. this.div.contentEditable = String(val != 'nocursor')
  11340. }
  11341. ContentEditableInput.prototype.onContextMenu = function () {}
  11342. ContentEditableInput.prototype.resetPosition = function () {}
  11343. ContentEditableInput.prototype.needsContentAttribute = true
  11344. function posToDOM(cm, pos) {
  11345. var view = findViewForLine(cm, pos.line)
  11346. if (!view || view.hidden) {
  11347. return null
  11348. }
  11349. var line = getLine(cm.doc, pos.line)
  11350. var info = mapFromLineView(view, line, pos.line)
  11351. var order = getOrder(line, cm.doc.direction),
  11352. side = 'left'
  11353. if (order) {
  11354. var partPos = getBidiPartAt(order, pos.ch)
  11355. side = partPos % 2 ? 'right' : 'left'
  11356. }
  11357. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  11358. result.offset = result.collapse == 'right' ? result.end : result.start
  11359. return result
  11360. }
  11361. function isInGutter(node) {
  11362. for (var scan = node; scan; scan = scan.parentNode) {
  11363. if (/CodeMirror-gutter-wrapper/.test(scan.className)) {
  11364. return true
  11365. }
  11366. }
  11367. return false
  11368. }
  11369. function badPos(pos, bad) {
  11370. if (bad) {
  11371. pos.bad = true
  11372. }
  11373. return pos
  11374. }
  11375. function domTextBetween(cm, from, to, fromLine, toLine) {
  11376. var text = '',
  11377. closing = false,
  11378. lineSep = cm.doc.lineSeparator(),
  11379. extraLinebreak = false
  11380. function recognizeMarker(id) {
  11381. return function (marker) {
  11382. return marker.id == id
  11383. }
  11384. }
  11385. function close() {
  11386. if (closing) {
  11387. text += lineSep
  11388. if (extraLinebreak) {
  11389. text += lineSep
  11390. }
  11391. closing = extraLinebreak = false
  11392. }
  11393. }
  11394. function addText(str) {
  11395. if (str) {
  11396. close()
  11397. text += str
  11398. }
  11399. }
  11400. function walk(node) {
  11401. if (node.nodeType == 1) {
  11402. var cmText = node.getAttribute('cm-text')
  11403. if (cmText) {
  11404. addText(cmText)
  11405. return
  11406. }
  11407. var markerID = node.getAttribute('cm-marker'),
  11408. range
  11409. if (markerID) {
  11410. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  11411. if (found.length && (range = found[0].find(0))) {
  11412. addText(getBetween(cm.doc, range.from, range.to).join(lineSep))
  11413. }
  11414. return
  11415. }
  11416. if (node.getAttribute('contenteditable') == 'false') {
  11417. return
  11418. }
  11419. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName)
  11420. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) {
  11421. return
  11422. }
  11423. if (isBlock) {
  11424. close()
  11425. }
  11426. for (var i = 0; i < node.childNodes.length; i++) {
  11427. walk(node.childNodes[i])
  11428. }
  11429. if (/^(pre|p)$/i.test(node.nodeName)) {
  11430. extraLinebreak = true
  11431. }
  11432. if (isBlock) {
  11433. closing = true
  11434. }
  11435. } else if (node.nodeType == 3) {
  11436. addText(node.nodeValue.replace(/\u200b/g, '').replace(/\u00a0/g, ' '))
  11437. }
  11438. }
  11439. for (;;) {
  11440. walk(from)
  11441. if (from == to) {
  11442. break
  11443. }
  11444. from = from.nextSibling
  11445. extraLinebreak = false
  11446. }
  11447. return text
  11448. }
  11449. function domToPos(cm, node, offset) {
  11450. var lineNode
  11451. if (node == cm.display.lineDiv) {
  11452. lineNode = cm.display.lineDiv.childNodes[offset]
  11453. if (!lineNode) {
  11454. return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true)
  11455. }
  11456. node = null
  11457. offset = 0
  11458. } else {
  11459. for (lineNode = node; ; lineNode = lineNode.parentNode) {
  11460. if (!lineNode || lineNode == cm.display.lineDiv) {
  11461. return null
  11462. }
  11463. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) {
  11464. break
  11465. }
  11466. }
  11467. }
  11468. for (var i = 0; i < cm.display.view.length; i++) {
  11469. var lineView = cm.display.view[i]
  11470. if (lineView.node == lineNode) {
  11471. return locateNodeInLineView(lineView, node, offset)
  11472. }
  11473. }
  11474. }
  11475. function locateNodeInLineView(lineView, node, offset) {
  11476. var wrapper = lineView.text.firstChild,
  11477. bad = false
  11478. if (!node || !contains(wrapper, node)) {
  11479. return badPos(Pos(lineNo(lineView.line), 0), true)
  11480. }
  11481. if (node == wrapper) {
  11482. bad = true
  11483. node = wrapper.childNodes[offset]
  11484. offset = 0
  11485. if (!node) {
  11486. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  11487. return badPos(Pos(lineNo(line), line.text.length), bad)
  11488. }
  11489. }
  11490. var textNode = node.nodeType == 3 ? node : null,
  11491. topNode = node
  11492. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  11493. textNode = node.firstChild
  11494. if (offset) {
  11495. offset = textNode.nodeValue.length
  11496. }
  11497. }
  11498. while (topNode.parentNode != wrapper) {
  11499. topNode = topNode.parentNode
  11500. }
  11501. var measure = lineView.measure,
  11502. maps = measure.maps
  11503. function find(textNode, topNode, offset) {
  11504. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  11505. var map = i < 0 ? measure.map : maps[i]
  11506. for (var j = 0; j < map.length; j += 3) {
  11507. var curNode = map[j + 2]
  11508. if (curNode == textNode || curNode == topNode) {
  11509. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  11510. var ch = map[j] + offset
  11511. if (offset < 0 || curNode != textNode) {
  11512. ch = map[j + (offset ? 1 : 0)]
  11513. }
  11514. return Pos(line, ch)
  11515. }
  11516. }
  11517. }
  11518. }
  11519. var found = find(textNode, topNode, offset)
  11520. if (found) {
  11521. return badPos(found, bad)
  11522. }
  11523. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  11524. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  11525. found = find(after, after.firstChild, 0)
  11526. if (found) {
  11527. return badPos(Pos(found.line, found.ch - dist), bad)
  11528. } else {
  11529. dist += after.textContent.length
  11530. }
  11531. }
  11532. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  11533. found = find(before, before.firstChild, -1)
  11534. if (found) {
  11535. return badPos(Pos(found.line, found.ch + dist$1), bad)
  11536. } else {
  11537. dist$1 += before.textContent.length
  11538. }
  11539. }
  11540. }
  11541. // TEXTAREA INPUT STYLE
  11542. var TextareaInput = function (cm) {
  11543. this.cm = cm
  11544. // See input.poll and input.reset
  11545. this.prevInput = ''
  11546. // Flag that indicates whether we expect input to appear real soon
  11547. // now (after some event like 'keypress' or 'input') and are
  11548. // polling intensively.
  11549. this.pollingFast = false
  11550. // Self-resetting timeout for the poller
  11551. this.polling = new Delayed()
  11552. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  11553. this.hasSelection = false
  11554. this.composing = null
  11555. }
  11556. TextareaInput.prototype.init = function (display) {
  11557. var this$1 = this
  11558. var input = this,
  11559. cm = this.cm
  11560. this.createField(display)
  11561. var te = this.textarea
  11562. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild)
  11563. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  11564. if (ios) {
  11565. te.style.width = '0px'
  11566. }
  11567. on(te, 'input', function () {
  11568. if (ie && ie_version >= 9 && this$1.hasSelection) {
  11569. this$1.hasSelection = null
  11570. }
  11571. input.poll()
  11572. })
  11573. on(te, 'paste', function (e) {
  11574. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) {
  11575. return
  11576. }
  11577. cm.state.pasteIncoming = +new Date()
  11578. input.fastPoll()
  11579. })
  11580. function prepareCopyCut(e) {
  11581. if (signalDOMEvent(cm, e)) {
  11582. return
  11583. }
  11584. if (cm.somethingSelected()) {
  11585. setLastCopied({ lineWise: false, text: cm.getSelections() })
  11586. } else if (!cm.options.lineWiseCopyCut) {
  11587. return
  11588. } else {
  11589. var ranges = copyableRanges(cm)
  11590. setLastCopied({ lineWise: true, text: ranges.text })
  11591. if (e.type == 'cut') {
  11592. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  11593. } else {
  11594. input.prevInput = ''
  11595. te.value = ranges.text.join('\n')
  11596. selectInput(te)
  11597. }
  11598. }
  11599. if (e.type == 'cut') {
  11600. cm.state.cutIncoming = +new Date()
  11601. }
  11602. }
  11603. on(te, 'cut', prepareCopyCut)
  11604. on(te, 'copy', prepareCopyCut)
  11605. on(display.scroller, 'paste', function (e) {
  11606. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) {
  11607. return
  11608. }
  11609. if (!te.dispatchEvent) {
  11610. cm.state.pasteIncoming = +new Date()
  11611. input.focus()
  11612. return
  11613. }
  11614. // Pass the `paste` event to the textarea so it's handled by its event listener.
  11615. var event = new Event('paste')
  11616. event.clipboardData = e.clipboardData
  11617. te.dispatchEvent(event)
  11618. })
  11619. // Prevent normal selection in the editor (we handle our own)
  11620. on(display.lineSpace, 'selectstart', function (e) {
  11621. if (!eventInWidget(display, e)) {
  11622. e_preventDefault(e)
  11623. }
  11624. })
  11625. on(te, 'compositionstart', function () {
  11626. var start = cm.getCursor('from')
  11627. if (input.composing) {
  11628. input.composing.range.clear()
  11629. }
  11630. input.composing = {
  11631. start: start,
  11632. range: cm.markText(start, cm.getCursor('to'), { className: 'CodeMirror-composing' }),
  11633. }
  11634. })
  11635. on(te, 'compositionend', function () {
  11636. if (input.composing) {
  11637. input.poll()
  11638. input.composing.range.clear()
  11639. input.composing = null
  11640. }
  11641. })
  11642. }
  11643. TextareaInput.prototype.createField = function (_display) {
  11644. // Wraps and hides input textarea
  11645. this.wrapper = hiddenTextarea()
  11646. // The semihidden textarea that is focused when the editor is
  11647. // focused, and receives input.
  11648. this.textarea = this.wrapper.firstChild
  11649. }
  11650. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  11651. // Label for screenreaders, accessibility
  11652. if (label) {
  11653. this.textarea.setAttribute('aria-label', label)
  11654. } else {
  11655. this.textarea.removeAttribute('aria-label')
  11656. }
  11657. }
  11658. TextareaInput.prototype.prepareSelection = function () {
  11659. // Redraw the selection and/or cursor
  11660. var cm = this.cm,
  11661. display = cm.display,
  11662. doc = cm.doc
  11663. var result = prepareSelection(cm)
  11664. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  11665. if (cm.options.moveInputWithCursor) {
  11666. var headPos = cursorCoords(cm, doc.sel.primary().head, 'div')
  11667. var wrapOff = display.wrapper.getBoundingClientRect(),
  11668. lineOff = display.lineDiv.getBoundingClientRect()
  11669. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top))
  11670. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left))
  11671. }
  11672. return result
  11673. }
  11674. TextareaInput.prototype.showSelection = function (drawn) {
  11675. var cm = this.cm,
  11676. display = cm.display
  11677. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  11678. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  11679. if (drawn.teTop != null) {
  11680. this.wrapper.style.top = drawn.teTop + 'px'
  11681. this.wrapper.style.left = drawn.teLeft + 'px'
  11682. }
  11683. }
  11684. // Reset the input to correspond to the selection (or to be empty,
  11685. // when not typing and nothing is selected)
  11686. TextareaInput.prototype.reset = function (typing) {
  11687. if (this.contextMenuPending || this.composing) {
  11688. return
  11689. }
  11690. var cm = this.cm
  11691. if (cm.somethingSelected()) {
  11692. this.prevInput = ''
  11693. var content = cm.getSelection()
  11694. this.textarea.value = content
  11695. if (cm.state.focused) {
  11696. selectInput(this.textarea)
  11697. }
  11698. if (ie && ie_version >= 9) {
  11699. this.hasSelection = content
  11700. }
  11701. } else if (!typing) {
  11702. this.prevInput = this.textarea.value = ''
  11703. if (ie && ie_version >= 9) {
  11704. this.hasSelection = null
  11705. }
  11706. }
  11707. }
  11708. TextareaInput.prototype.getField = function () {
  11709. return this.textarea
  11710. }
  11711. TextareaInput.prototype.supportsTouch = function () {
  11712. return false
  11713. }
  11714. TextareaInput.prototype.focus = function () {
  11715. if (this.cm.options.readOnly != 'nocursor' && (!mobile || activeElt() != this.textarea)) {
  11716. try {
  11717. this.textarea.focus()
  11718. } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  11719. }
  11720. }
  11721. TextareaInput.prototype.blur = function () {
  11722. this.textarea.blur()
  11723. }
  11724. TextareaInput.prototype.resetPosition = function () {
  11725. this.wrapper.style.top = this.wrapper.style.left = 0
  11726. }
  11727. TextareaInput.prototype.receivedFocus = function () {
  11728. this.slowPoll()
  11729. }
  11730. // Poll for input changes, using the normal rate of polling. This
  11731. // runs as long as the editor is focused.
  11732. TextareaInput.prototype.slowPoll = function () {
  11733. var this$1 = this
  11734. if (this.pollingFast) {
  11735. return
  11736. }
  11737. this.polling.set(this.cm.options.pollInterval, function () {
  11738. this$1.poll()
  11739. if (this$1.cm.state.focused) {
  11740. this$1.slowPoll()
  11741. }
  11742. })
  11743. }
  11744. // When an event has just come in that is likely to add or change
  11745. // something in the input textarea, we poll faster, to ensure that
  11746. // the change appears on the screen quickly.
  11747. TextareaInput.prototype.fastPoll = function () {
  11748. var missed = false,
  11749. input = this
  11750. input.pollingFast = true
  11751. function p() {
  11752. var changed = input.poll()
  11753. if (!changed && !missed) {
  11754. missed = true
  11755. input.polling.set(60, p)
  11756. } else {
  11757. input.pollingFast = false
  11758. input.slowPoll()
  11759. }
  11760. }
  11761. input.polling.set(20, p)
  11762. }
  11763. // Read input from the textarea, and update the document to match.
  11764. // When something is selected, it is present in the textarea, and
  11765. // selected (unless it is huge, in which case a placeholder is
  11766. // used). When nothing is selected, the cursor sits after previously
  11767. // seen text (can be empty), which is stored in prevInput (we must
  11768. // not reset the textarea when typing, because that breaks IME).
  11769. TextareaInput.prototype.poll = function () {
  11770. var this$1 = this
  11771. var cm = this.cm,
  11772. input = this.textarea,
  11773. prevInput = this.prevInput
  11774. // Since this is called a *lot*, try to bail out as cheaply as
  11775. // possible when it is clear that nothing happened. hasSelection
  11776. // will be the case when there is a lot of text in the textarea,
  11777. // in which case reading its value would be expensive.
  11778. if (this.contextMenuPending || !cm.state.focused || (hasSelection(input) && !prevInput && !this.composing) || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) {
  11779. return false
  11780. }
  11781. var text = input.value
  11782. // If nothing changed, bail.
  11783. if (text == prevInput && !cm.somethingSelected()) {
  11784. return false
  11785. }
  11786. // Work around nonsensical selection resetting in IE9/10, and
  11787. // inexplicable appearance of private area unicode characters on
  11788. // some key combos in Mac (#2689).
  11789. if ((ie && ie_version >= 9 && this.hasSelection === text) || (mac && /[\uf700-\uf7ff]/.test(text))) {
  11790. cm.display.input.reset()
  11791. return false
  11792. }
  11793. if (cm.doc.sel == cm.display.selForContextMenu) {
  11794. var first = text.charCodeAt(0)
  11795. if (first == 0x200b && !prevInput) {
  11796. prevInput = '\u200b'
  11797. }
  11798. if (first == 0x21da) {
  11799. this.reset()
  11800. return this.cm.execCommand('undo')
  11801. }
  11802. }
  11803. // Find the part of the input that is actually new
  11804. var same = 0,
  11805. l = Math.min(prevInput.length, text.length)
  11806. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) {
  11807. ++same
  11808. }
  11809. runInOp(cm, function () {
  11810. applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1.composing ? '*compose' : null)
  11811. // Don't leave long text in the textarea, since it makes further polling slow
  11812. if (text.length > 1000 || text.indexOf('\n') > -1) {
  11813. input.value = this$1.prevInput = ''
  11814. } else {
  11815. this$1.prevInput = text
  11816. }
  11817. if (this$1.composing) {
  11818. this$1.composing.range.clear()
  11819. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor('to'), { className: 'CodeMirror-composing' })
  11820. }
  11821. })
  11822. return true
  11823. }
  11824. TextareaInput.prototype.ensurePolled = function () {
  11825. if (this.pollingFast && this.poll()) {
  11826. this.pollingFast = false
  11827. }
  11828. }
  11829. TextareaInput.prototype.onKeyPress = function () {
  11830. if (ie && ie_version >= 9) {
  11831. this.hasSelection = null
  11832. }
  11833. this.fastPoll()
  11834. }
  11835. TextareaInput.prototype.onContextMenu = function (e) {
  11836. var input = this,
  11837. cm = input.cm,
  11838. display = cm.display,
  11839. te = input.textarea
  11840. if (input.contextMenuPending) {
  11841. input.contextMenuPending()
  11842. }
  11843. var pos = posFromMouse(cm, e),
  11844. scrollPos = display.scroller.scrollTop
  11845. if (!pos || presto) {
  11846. return
  11847. } // Opera is difficult.
  11848. // Reset the current text selection only if the click is done outside of the selection
  11849. // and 'resetSelectionOnContextMenu' option is true.
  11850. var reset = cm.options.resetSelectionOnContextMenu
  11851. if (reset && cm.doc.sel.contains(pos) == -1) {
  11852. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll)
  11853. }
  11854. var oldCSS = te.style.cssText,
  11855. oldWrapperCSS = input.wrapper.style.cssText
  11856. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect()
  11857. input.wrapper.style.cssText = 'position: static'
  11858. te.style.cssText =
  11859. 'position: absolute; width: 30px; height: 30px;\n top: ' +
  11860. (e.clientY - wrapperBox.top - 5) +
  11861. 'px; left: ' +
  11862. (e.clientX - wrapperBox.left - 5) +
  11863. 'px;\n z-index: 1000; background: ' +
  11864. (ie ? 'rgba(255, 255, 255, .05)' : 'transparent') +
  11865. ';\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);'
  11866. var oldScrollY
  11867. if (webkit) {
  11868. oldScrollY = window.scrollY
  11869. } // Work around Chrome issue (#2712)
  11870. display.input.focus()
  11871. if (webkit) {
  11872. window.scrollTo(null, oldScrollY)
  11873. }
  11874. display.input.reset()
  11875. // Adds "Select all" to context menu in FF
  11876. if (!cm.somethingSelected()) {
  11877. te.value = input.prevInput = ' '
  11878. }
  11879. input.contextMenuPending = rehide
  11880. display.selForContextMenu = cm.doc.sel
  11881. clearTimeout(display.detectingSelectAll)
  11882. // Select-all will be greyed out if there's nothing to select, so
  11883. // this adds a zero-width space so that we can later check whether
  11884. // it got selected.
  11885. function prepareSelectAllHack() {
  11886. if (te.selectionStart != null) {
  11887. var selected = cm.somethingSelected()
  11888. var extval = '\u200b' + (selected ? te.value : '')
  11889. te.value = '\u21da' // Used to catch context-menu undo
  11890. te.value = extval
  11891. input.prevInput = selected ? '' : '\u200b'
  11892. te.selectionStart = 1
  11893. te.selectionEnd = extval.length
  11894. // Re-set this, in case some other handler touched the
  11895. // selection in the meantime.
  11896. display.selForContextMenu = cm.doc.sel
  11897. }
  11898. }
  11899. function rehide() {
  11900. if (input.contextMenuPending != rehide) {
  11901. return
  11902. }
  11903. input.contextMenuPending = false
  11904. input.wrapper.style.cssText = oldWrapperCSS
  11905. te.style.cssText = oldCSS
  11906. if (ie && ie_version < 9) {
  11907. display.scrollbars.setScrollTop((display.scroller.scrollTop = scrollPos))
  11908. }
  11909. // Try to detect the user choosing select-all
  11910. if (te.selectionStart != null) {
  11911. if (!ie || (ie && ie_version < 9)) {
  11912. prepareSelectAllHack()
  11913. }
  11914. var i = 0,
  11915. poll = function () {
  11916. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == '\u200b') {
  11917. operation(cm, selectAll)(cm)
  11918. } else if (i++ < 10) {
  11919. display.detectingSelectAll = setTimeout(poll, 500)
  11920. } else {
  11921. display.selForContextMenu = null
  11922. display.input.reset()
  11923. }
  11924. }
  11925. display.detectingSelectAll = setTimeout(poll, 200)
  11926. }
  11927. }
  11928. if (ie && ie_version >= 9) {
  11929. prepareSelectAllHack()
  11930. }
  11931. if (captureRightClick) {
  11932. e_stop(e)
  11933. var mouseup = function () {
  11934. off(window, 'mouseup', mouseup)
  11935. setTimeout(rehide, 20)
  11936. }
  11937. on(window, 'mouseup', mouseup)
  11938. } else {
  11939. setTimeout(rehide, 50)
  11940. }
  11941. }
  11942. TextareaInput.prototype.readOnlyChanged = function (val) {
  11943. if (!val) {
  11944. this.reset()
  11945. }
  11946. this.textarea.disabled = val == 'nocursor'
  11947. this.textarea.readOnly = !!val
  11948. }
  11949. TextareaInput.prototype.setUneditable = function () {}
  11950. TextareaInput.prototype.needsContentAttribute = false
  11951. function fromTextArea(textarea, options) {
  11952. options = options ? copyObj(options) : {}
  11953. options.value = textarea.value
  11954. if (!options.tabindex && textarea.tabIndex) {
  11955. options.tabindex = textarea.tabIndex
  11956. }
  11957. if (!options.placeholder && textarea.placeholder) {
  11958. options.placeholder = textarea.placeholder
  11959. }
  11960. // Set autofocus to true if this textarea is focused, or if it has
  11961. // autofocus and no other element is focused.
  11962. if (options.autofocus == null) {
  11963. var hasFocus = activeElt()
  11964. options.autofocus = hasFocus == textarea || (textarea.getAttribute('autofocus') != null && hasFocus == document.body)
  11965. }
  11966. function save() {
  11967. textarea.value = cm.getValue()
  11968. }
  11969. var realSubmit
  11970. if (textarea.form) {
  11971. on(textarea.form, 'submit', save)
  11972. // Deplorable hack to make the submit method do the right thing.
  11973. if (!options.leaveSubmitMethodAlone) {
  11974. var form = textarea.form
  11975. realSubmit = form.submit
  11976. try {
  11977. var wrappedSubmit = (form.submit = function () {
  11978. save()
  11979. form.submit = realSubmit
  11980. form.submit()
  11981. form.submit = wrappedSubmit
  11982. })
  11983. } catch (e) {}
  11984. }
  11985. }
  11986. options.finishInit = function (cm) {
  11987. cm.save = save
  11988. cm.getTextArea = function () {
  11989. return textarea
  11990. }
  11991. cm.toTextArea = function () {
  11992. cm.toTextArea = isNaN // Prevent this from being ran twice
  11993. save()
  11994. textarea.parentNode.removeChild(cm.getWrapperElement())
  11995. textarea.style.display = ''
  11996. if (textarea.form) {
  11997. off(textarea.form, 'submit', save)
  11998. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == 'function') {
  11999. textarea.form.submit = realSubmit
  12000. }
  12001. }
  12002. }
  12003. }
  12004. textarea.style.display = 'none'
  12005. var cm = CodeMirror(function (node) {
  12006. return textarea.parentNode.insertBefore(node, textarea.nextSibling)
  12007. }, options)
  12008. return cm
  12009. }
  12010. function addLegacyProps(CodeMirror) {
  12011. CodeMirror.off = off
  12012. CodeMirror.on = on
  12013. CodeMirror.wheelEventPixels = wheelEventPixels
  12014. CodeMirror.Doc = Doc
  12015. CodeMirror.splitLines = splitLinesAuto
  12016. CodeMirror.countColumn = countColumn
  12017. CodeMirror.findColumn = findColumn
  12018. CodeMirror.isWordChar = isWordCharBasic
  12019. CodeMirror.Pass = Pass
  12020. CodeMirror.signal = signal
  12021. CodeMirror.Line = Line
  12022. CodeMirror.changeEnd = changeEnd
  12023. CodeMirror.scrollbarModel = scrollbarModel
  12024. CodeMirror.Pos = Pos
  12025. CodeMirror.cmpPos = cmp
  12026. CodeMirror.modes = modes
  12027. CodeMirror.mimeModes = mimeModes
  12028. CodeMirror.resolveMode = resolveMode
  12029. CodeMirror.getMode = getMode
  12030. CodeMirror.modeExtensions = modeExtensions
  12031. CodeMirror.extendMode = extendMode
  12032. CodeMirror.copyState = copyState
  12033. CodeMirror.startState = startState
  12034. CodeMirror.innerMode = innerMode
  12035. CodeMirror.commands = commands
  12036. CodeMirror.keyMap = keyMap
  12037. CodeMirror.keyName = keyName
  12038. CodeMirror.isModifierKey = isModifierKey
  12039. CodeMirror.lookupKey = lookupKey
  12040. CodeMirror.normalizeKeyMap = normalizeKeyMap
  12041. CodeMirror.StringStream = StringStream
  12042. CodeMirror.SharedTextMarker = SharedTextMarker
  12043. CodeMirror.TextMarker = TextMarker
  12044. CodeMirror.LineWidget = LineWidget
  12045. CodeMirror.e_preventDefault = e_preventDefault
  12046. CodeMirror.e_stopPropagation = e_stopPropagation
  12047. CodeMirror.e_stop = e_stop
  12048. CodeMirror.addClass = addClass
  12049. CodeMirror.contains = contains
  12050. CodeMirror.rmClass = rmClass
  12051. CodeMirror.keyNames = keyNames
  12052. }
  12053. // EDITOR CONSTRUCTOR
  12054. defineOptions(CodeMirror)
  12055. addEditorMethods(CodeMirror)
  12056. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  12057. var dontDelegate = 'iter insert remove copy getEditor constructor'.split(' ')
  12058. for (var prop in Doc.prototype) {
  12059. if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) {
  12060. CodeMirror.prototype[prop] = (function (method) {
  12061. return function () {
  12062. return method.apply(this.doc, arguments)
  12063. }
  12064. })(Doc.prototype[prop])
  12065. }
  12066. }
  12067. eventMixin(Doc)
  12068. CodeMirror.inputStyles = { textarea: TextareaInput, contenteditable: ContentEditableInput }
  12069. // Extra arguments are stored as the mode's dependencies, which is
  12070. // used by (legacy) mechanisms like loadmode.js to automatically
  12071. // load a mode. (Preferred mechanism is the require/define calls.)
  12072. CodeMirror.defineMode = function (name /*, mode, …*/) {
  12073. if (!CodeMirror.defaults.mode && name != 'null') {
  12074. CodeMirror.defaults.mode = name
  12075. }
  12076. defineMode.apply(this, arguments)
  12077. }
  12078. CodeMirror.defineMIME = defineMIME
  12079. // Minimal default mode.
  12080. CodeMirror.defineMode('null', function () {
  12081. return {
  12082. token: function (stream) {
  12083. return stream.skipToEnd()
  12084. },
  12085. }
  12086. })
  12087. CodeMirror.defineMIME('text/plain', 'null')
  12088. // EXTENSIONS
  12089. CodeMirror.defineExtension = function (name, func) {
  12090. CodeMirror.prototype[name] = func
  12091. }
  12092. CodeMirror.defineDocExtension = function (name, func) {
  12093. Doc.prototype[name] = func
  12094. }
  12095. CodeMirror.fromTextArea = fromTextArea
  12096. addLegacyProps(CodeMirror)
  12097. CodeMirror.version = '5.65.2'
  12098. return CodeMirror
  12099. })