codemirror.js 439 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/5/LICENSE
  3. // This is CodeMirror (https://codemirror.net/5), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global = global || self, global.CodeMirror = factory());
  12. }(this, (function () {
  13. 'use strict';
  14. // Kludges for bugs and behavior differences that can't be feature
  15. // detected are enabled based on userAgent etc sniffing.
  16. var userAgent = navigator.userAgent;
  17. var platform = navigator.platform;
  18. var gecko = /gecko\/\d/i.test(userAgent);
  19. var ie_upto10 = /MSIE \d/.test(userAgent);
  20. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  21. var edge = /Edge\/(\d+)/.exec(userAgent);
  22. var ie = ie_upto10 || ie_11up || edge;
  23. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  24. var webkit = !edge && /WebKit\//.test(userAgent);
  25. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  26. var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent);
  27. var chrome_version = chrome && +chrome[1];
  28. var presto = /Opera\//.test(userAgent);
  29. var safari = /Apple Computer/.test(navigator.vendor);
  30. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  31. var phantom = /PhantomJS/.test(userAgent);
  32. var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  33. var android = /Android/.test(userAgent);
  34. // This is woefully incomplete. Suggestions for alternative methods welcome.
  35. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  36. var mac = ios || /Mac/.test(platform);
  37. var chromeOS = /\bCrOS\b/.test(userAgent);
  38. var windows = /win/i.test(platform);
  39. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  40. if (presto_version) { presto_version = Number(presto_version[1]); }
  41. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  42. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  43. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  44. var captureRightClick = gecko || (ie && ie_version >= 9);
  45. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  46. var rmClass = function (node, cls) {
  47. var current = node.className;
  48. var match = classTest(cls).exec(current);
  49. if (match) {
  50. var after = current.slice(match.index + match[0].length);
  51. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  52. }
  53. };
  54. function removeChildren(e) {
  55. for (var count = e.childNodes.length; count > 0; --count)
  56. { e.removeChild(e.firstChild); }
  57. return e
  58. }
  59. function removeChildrenAndAdd(parent, e) {
  60. return removeChildren(parent).appendChild(e)
  61. }
  62. function elt(tag, content, className, style) {
  63. var e = document.createElement(tag);
  64. if (className) { e.className = className; }
  65. if (style) { e.style.cssText = style; }
  66. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  67. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  68. return e
  69. }
  70. // wrapper for elt, which removes the elt from the accessibility tree
  71. function eltP(tag, content, className, style) {
  72. var e = elt(tag, content, className, style);
  73. e.setAttribute("role", "presentation");
  74. return e
  75. }
  76. var range;
  77. if (document.createRange) {
  78. range = function (node, start, end, endNode) {
  79. var r = document.createRange();
  80. r.setEnd(endNode || node, end);
  81. r.setStart(node, start);
  82. return r
  83. };
  84. }
  85. else {
  86. range = function (node, start, end) {
  87. var r = document.body.createTextRange();
  88. try { r.moveToElementText(node.parentNode); }
  89. catch (e) { return r }
  90. r.collapse(true);
  91. r.moveEnd("character", end);
  92. r.moveStart("character", start);
  93. return r
  94. };
  95. }
  96. function contains(parent, child) {
  97. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  98. { child = child.parentNode; }
  99. if (parent.contains)
  100. { return parent.contains(child) }
  101. do {
  102. if (child.nodeType == 11) { child = child.host; }
  103. if (child == parent) { return true }
  104. } while (child = child.parentNode)
  105. }
  106. function activeElt(doc) {
  107. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  108. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  109. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  110. var activeElement;
  111. try {
  112. activeElement = doc.activeElement;
  113. } catch (e) {
  114. activeElement = doc.body || null;
  115. }
  116. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  117. { activeElement = activeElement.shadowRoot.activeElement; }
  118. return activeElement
  119. }
  120. function addClass(node, cls) {
  121. var current = node.className;
  122. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  123. }
  124. function joinClasses(a, b) {
  125. var as = a.split(" ");
  126. for (var i = 0; i < as.length; i++)
  127. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  128. return b
  129. }
  130. var selectInput = function (node) { node.select(); };
  131. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  132. { selectInput = function (node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  133. else if (ie) // Suppress mysterious IE10 errors
  134. { selectInput = function (node) { try { node.select(); } catch (_e) { } }; }
  135. function doc(cm) { return cm.display.wrapper.ownerDocument }
  136. function win(cm) { return doc(cm).defaultView }
  137. function bind(f) {
  138. var args = Array.prototype.slice.call(arguments, 1);
  139. return function () { return f.apply(null, args) }
  140. }
  141. function copyObj(obj, target, overwrite) {
  142. if (!target) { target = {}; }
  143. for (var prop in obj) {
  144. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  145. { target[prop] = obj[prop]; }
  146. }
  147. return target
  148. }
  149. // Counts the column offset in a string, taking tabs into account.
  150. // Used mostly to find indentation.
  151. function countColumn(string, end, tabSize, startIndex, startValue) {
  152. if (end == null) {
  153. end = string.search(/[^\s\u00a0]/);
  154. if (end == -1) { end = string.length; }
  155. }
  156. for (var i = startIndex || 0, n = startValue || 0; ;) {
  157. var nextTab = string.indexOf("\t", i);
  158. if (nextTab < 0 || nextTab >= end)
  159. { return n + (end - i) }
  160. n += nextTab - i;
  161. n += tabSize - (n % tabSize);
  162. i = nextTab + 1;
  163. }
  164. }
  165. var Delayed = function () {
  166. this.id = null;
  167. this.f = null;
  168. this.time = 0;
  169. this.handler = bind(this.onTimeout, this);
  170. };
  171. Delayed.prototype.onTimeout = function (self) {
  172. self.id = 0;
  173. if (self.time <= +new Date) {
  174. self.f();
  175. } else {
  176. setTimeout(self.handler, self.time - +new Date);
  177. }
  178. };
  179. Delayed.prototype.set = function (ms, f) {
  180. this.f = f;
  181. var time = +new Date + ms;
  182. if (!this.id || time < this.time) {
  183. clearTimeout(this.id);
  184. this.id = setTimeout(this.handler, ms);
  185. this.time = time;
  186. }
  187. };
  188. function indexOf(array, elt) {
  189. for (var i = 0; i < array.length; ++i)
  190. { if (array[i] == elt) { return i } }
  191. return -1
  192. }
  193. // Number of pixels added to scroller and sizer to hide scrollbar
  194. var scrollerGap = 50;
  195. // Returned or thrown by various protocols to signal 'I'm not
  196. // handling this'.
  197. var Pass = { toString: function () { return "CodeMirror.Pass" } };
  198. // Reused option objects for setSelection & friends
  199. var sel_dontScroll = { scroll: false }, sel_mouse = { origin: "*mouse" }, sel_move = { origin: "+move" };
  200. // The inverse of countColumn -- find the offset that corresponds to
  201. // a particular column.
  202. function findColumn(string, goal, tabSize) {
  203. for (var pos = 0, col = 0; ;) {
  204. var nextTab = string.indexOf("\t", pos);
  205. if (nextTab == -1) { nextTab = string.length; }
  206. var skipped = nextTab - pos;
  207. if (nextTab == string.length || col + skipped >= goal)
  208. { return pos + Math.min(skipped, goal - col) }
  209. col += nextTab - pos;
  210. col += tabSize - (col % tabSize);
  211. pos = nextTab + 1;
  212. if (col >= goal) { return pos }
  213. }
  214. }
  215. var spaceStrs = [""];
  216. function spaceStr(n) {
  217. while (spaceStrs.length <= n)
  218. { spaceStrs.push(lst(spaceStrs) + " "); }
  219. return spaceStrs[n]
  220. }
  221. function lst(arr) { return arr[arr.length - 1] }
  222. function map(array, f) {
  223. var out = [];
  224. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  225. return out
  226. }
  227. function insertSorted(array, value, score) {
  228. var pos = 0, priority = score(value);
  229. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  230. array.splice(pos, 0, value);
  231. }
  232. function nothing() { }
  233. function createObj(base, props) {
  234. var inst;
  235. if (Object.create) {
  236. inst = Object.create(base);
  237. } else {
  238. nothing.prototype = base;
  239. inst = new nothing();
  240. }
  241. if (props) { copyObj(props, inst); }
  242. return inst
  243. }
  244. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  245. function isWordCharBasic(ch) {
  246. return /\w/.test(ch) || ch > "\x80" &&
  247. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  248. }
  249. function isWordChar(ch, helper) {
  250. if (!helper) { return isWordCharBasic(ch) }
  251. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  252. return helper.test(ch)
  253. }
  254. function isEmpty(obj) {
  255. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  256. return true
  257. }
  258. // Extending unicode characters. A series of a non-extending char +
  259. // any number of extending chars is treated as a single unit as far
  260. // as editing and measuring is concerned. This is not fully correct,
  261. // since some scripts/fonts/browsers also treat other configurations
  262. // of code points as a group.
  263. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
  264. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  265. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  266. function skipExtendingChars(str, pos, dir) {
  267. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  268. return pos
  269. }
  270. // Returns the value from the range [`from`; `to`] that satisfies
  271. // `pred` and is closest to `from`. Assumes that at least `to`
  272. // satisfies `pred`. Supports `from` being greater than `to`.
  273. function findFirst(pred, from, to) {
  274. // At any point we are certain `to` satisfies `pred`, don't know
  275. // whether `from` does.
  276. var dir = from > to ? -1 : 1;
  277. for (; ;) {
  278. if (from == to) { return from }
  279. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  280. if (mid == from) { return pred(mid) ? from : to }
  281. if (pred(mid)) { to = mid; }
  282. else { from = mid + dir; }
  283. }
  284. }
  285. // BIDI HELPERS
  286. function iterateBidiSections(order, from, to, f) {
  287. if (!order) { return f(from, to, "ltr", 0) }
  288. var found = false;
  289. for (var i = 0; i < order.length; ++i) {
  290. var part = order[i];
  291. if (part.from < to && part.to > from || from == to && part.to == from) {
  292. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  293. found = true;
  294. }
  295. }
  296. if (!found) { f(from, to, "ltr"); }
  297. }
  298. var bidiOther = null;
  299. function getBidiPartAt(order, ch, sticky) {
  300. var found;
  301. bidiOther = null;
  302. for (var i = 0; i < order.length; ++i) {
  303. var cur = order[i];
  304. if (cur.from < ch && cur.to > ch) { return i }
  305. if (cur.to == ch) {
  306. if (cur.from != cur.to && sticky == "before") { found = i; }
  307. else { bidiOther = i; }
  308. }
  309. if (cur.from == ch) {
  310. if (cur.from != cur.to && sticky != "before") { found = i; }
  311. else { bidiOther = i; }
  312. }
  313. }
  314. return found != null ? found : bidiOther
  315. }
  316. // Bidirectional ordering algorithm
  317. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  318. // that this (partially) implements.
  319. // One-char codes used for character types:
  320. // L (L): Left-to-Right
  321. // R (R): Right-to-Left
  322. // r (AL): Right-to-Left Arabic
  323. // 1 (EN): European Number
  324. // + (ES): European Number Separator
  325. // % (ET): European Number Terminator
  326. // n (AN): Arabic Number
  327. // , (CS): Common Number Separator
  328. // m (NSM): Non-Spacing Mark
  329. // b (BN): Boundary Neutral
  330. // s (B): Paragraph Separator
  331. // t (S): Segment Separator
  332. // w (WS): Whitespace
  333. // N (ON): Other Neutrals
  334. // Returns null if characters are ordered as they appear
  335. // (left-to-right), or an array of sections ({from, to, level}
  336. // objects) in the order in which they occur visually.
  337. var bidiOrdering = (function () {
  338. // Character types for codepoints 0 to 0xff
  339. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  340. // Character types for codepoints 0x600 to 0x6f9
  341. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  342. function charType(code) {
  343. if (code <= 0xf7) { return lowTypes.charAt(code) }
  344. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  345. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  346. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  347. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  348. else if (code == 0x200c) { return "b" }
  349. else { return "L" }
  350. }
  351. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  352. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  353. function BidiSpan(level, from, to) {
  354. this.level = level;
  355. this.from = from; this.to = to;
  356. }
  357. return function (str, direction) {
  358. var outerType = direction == "ltr" ? "L" : "R";
  359. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  360. var len = str.length, types = [];
  361. for (var i = 0; i < len; ++i)
  362. { types.push(charType(str.charCodeAt(i))); }
  363. // W1. Examine each non-spacing mark (NSM) in the level run, and
  364. // change the type of the NSM to the type of the previous
  365. // character. If the NSM is at the start of the level run, it will
  366. // get the type of sor.
  367. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  368. var type = types[i$1];
  369. if (type == "m") { types[i$1] = prev; }
  370. else { prev = type; }
  371. }
  372. // W2. Search backwards from each instance of a European number
  373. // until the first strong type (R, L, AL, or sor) is found. If an
  374. // AL is found, change the type of the European number to Arabic
  375. // number.
  376. // W3. Change all ALs to R.
  377. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  378. var type$1 = types[i$2];
  379. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  380. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  381. }
  382. // W4. A single European separator between two European numbers
  383. // changes to a European number. A single common separator between
  384. // two numbers of the same type changes to that type.
  385. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  386. var type$2 = types[i$3];
  387. if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") { types[i$3] = "1"; }
  388. else if (type$2 == "," && prev$1 == types[i$3 + 1] &&
  389. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  390. prev$1 = type$2;
  391. }
  392. // W5. A sequence of European terminators adjacent to European
  393. // numbers changes to all European numbers.
  394. // W6. Otherwise, separators and terminators change to Other
  395. // Neutral.
  396. for (var i$4 = 0; i$4 < len; ++i$4) {
  397. var type$3 = types[i$4];
  398. if (type$3 == ",") { types[i$4] = "N"; }
  399. else if (type$3 == "%") {
  400. var end = (void 0);
  401. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) { }
  402. var replace = (i$4 && types[i$4 - 1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  403. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  404. i$4 = end - 1;
  405. }
  406. }
  407. // W7. Search backwards from each instance of a European number
  408. // until the first strong type (R, L, or sor) is found. If an L is
  409. // found, then change the type of the European number to L.
  410. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  411. var type$4 = types[i$5];
  412. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  413. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  414. }
  415. // N1. A sequence of neutrals takes the direction of the
  416. // surrounding strong text if the text on both sides has the same
  417. // direction. European and Arabic numbers act as if they were R in
  418. // terms of their influence on neutrals. Start-of-level-run (sor)
  419. // and end-of-level-run (eor) are used at level run boundaries.
  420. // N2. Any remaining neutrals take the embedding direction.
  421. for (var i$6 = 0; i$6 < len; ++i$6) {
  422. if (isNeutral.test(types[i$6])) {
  423. var end$1 = (void 0);
  424. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]) ; ++end$1) { }
  425. var before = (i$6 ? types[i$6 - 1] : outerType) == "L";
  426. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  427. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  428. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  429. i$6 = end$1 - 1;
  430. }
  431. }
  432. // Here we depart from the documented algorithm, in order to avoid
  433. // building up an actual levels array. Since there are only three
  434. // levels (0, 1, 2) in an implementation that doesn't take
  435. // explicit embedding into account, we can build up the order on
  436. // the fly, without following the level-based algorithm.
  437. var order = [], m;
  438. for (var i$7 = 0; i$7 < len;) {
  439. if (countsAsLeft.test(types[i$7])) {
  440. var start = i$7;
  441. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]) ; ++i$7) { }
  442. order.push(new BidiSpan(0, start, i$7));
  443. } else {
  444. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  445. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) { }
  446. for (var j$2 = pos; j$2 < i$7;) {
  447. if (countsAsNum.test(types[j$2])) {
  448. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  449. var nstart = j$2;
  450. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]) ; ++j$2) { }
  451. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  452. at += isRTL;
  453. pos = j$2;
  454. } else { ++j$2; }
  455. }
  456. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  457. }
  458. }
  459. if (direction == "ltr") {
  460. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  461. order[0].from = m[0].length;
  462. order.unshift(new BidiSpan(0, 0, m[0].length));
  463. }
  464. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  465. lst(order).to -= m[0].length;
  466. order.push(new BidiSpan(0, len - m[0].length, len));
  467. }
  468. }
  469. return direction == "rtl" ? order.reverse() : order
  470. }
  471. })();
  472. // Get the bidi ordering for the given line (and cache it). Returns
  473. // false for lines that are fully left-to-right, and an array of
  474. // BidiSpan objects otherwise.
  475. function getOrder(line, direction) {
  476. var order = line.order;
  477. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  478. return order
  479. }
  480. // EVENT HANDLING
  481. // Lightweight event framework. on/off also work on DOM nodes,
  482. // registering native DOM handlers.
  483. var noHandlers = [];
  484. var on = function (emitter, type, f) {
  485. if (emitter.addEventListener) {
  486. emitter.addEventListener(type, f, false);
  487. } else if (emitter.attachEvent) {
  488. emitter.attachEvent("on" + type, f);
  489. } else {
  490. var map = emitter._handlers || (emitter._handlers = {});
  491. map[type] = (map[type] || noHandlers).concat(f);
  492. }
  493. };
  494. function getHandlers(emitter, type) {
  495. return emitter._handlers && emitter._handlers[type] || noHandlers
  496. }
  497. function off(emitter, type, f) {
  498. if (emitter.removeEventListener) {
  499. emitter.removeEventListener(type, f, false);
  500. } else if (emitter.detachEvent) {
  501. emitter.detachEvent("on" + type, f);
  502. } else {
  503. var map = emitter._handlers, arr = map && map[type];
  504. if (arr) {
  505. var index = indexOf(arr, f);
  506. if (index > -1)
  507. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  508. }
  509. }
  510. }
  511. function signal(emitter, type /*, values...*/) {
  512. var handlers = getHandlers(emitter, type);
  513. if (!handlers.length) { return }
  514. var args = Array.prototype.slice.call(arguments, 2);
  515. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  516. }
  517. // The DOM events that CodeMirror handles can be overridden by
  518. // registering a (non-DOM) handler on the editor for the event name,
  519. // and preventDefault-ing the event in that handler.
  520. function signalDOMEvent(cm, e, override) {
  521. if (typeof e == "string")
  522. { e = { type: e, preventDefault: function () { this.defaultPrevented = true; } }; }
  523. signal(cm, override || e.type, cm, e);
  524. return e_defaultPrevented(e) || e.codemirrorIgnore
  525. }
  526. function signalCursorActivity(cm) {
  527. var arr = cm._handlers && cm._handlers.cursorActivity;
  528. if (!arr) { return }
  529. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  530. for (var i = 0; i < arr.length; ++i) {
  531. if (indexOf(set, arr[i]) == -1)
  532. { set.push(arr[i]); }
  533. }
  534. }
  535. function hasHandler(emitter, type) {
  536. return getHandlers(emitter, type).length > 0
  537. }
  538. // Add on and off methods to a constructor's prototype, to make
  539. // registering events on such objects more convenient.
  540. function eventMixin(ctor) {
  541. ctor.prototype.on = function (type, f) { on(this, type, f); };
  542. ctor.prototype.off = function (type, f) { off(this, type, f); };
  543. }
  544. // Due to the fact that we still support jurassic IE versions, some
  545. // compatibility wrappers are needed.
  546. function e_preventDefault(e) {
  547. if (e.preventDefault) { e.preventDefault(); }
  548. else { e.returnValue = false; }
  549. }
  550. function e_stopPropagation(e) {
  551. if (e.stopPropagation) { e.stopPropagation(); }
  552. else { e.cancelBubble = true; }
  553. }
  554. function e_defaultPrevented(e) {
  555. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  556. }
  557. function e_stop(e) { e_preventDefault(e); e_stopPropagation(e); }
  558. function e_target(e) { return e.target || e.srcElement }
  559. function e_button(e) {
  560. var b = e.which;
  561. if (b == null) {
  562. if (e.button & 1) { b = 1; }
  563. else if (e.button & 2) { b = 3; }
  564. else if (e.button & 4) { b = 2; }
  565. }
  566. if (mac && e.ctrlKey && b == 1) { b = 3; }
  567. return b
  568. }
  569. // Detect drag-and-drop
  570. var dragAndDrop = function () {
  571. // There is *some* kind of drag-and-drop support in IE6-8, but I
  572. // couldn't get it to work yet.
  573. if (ie && ie_version < 9) { return false }
  574. var div = elt('div');
  575. return "draggable" in div || "dragDrop" in div
  576. }();
  577. var zwspSupported;
  578. function zeroWidthElement(measure) {
  579. if (zwspSupported == null) {
  580. var test = elt("span", "\u200b");
  581. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  582. if (measure.firstChild.offsetHeight != 0)
  583. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  584. }
  585. var node = zwspSupported ? elt("span", "\u200b") :
  586. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  587. node.setAttribute("cm-text", "");
  588. return node
  589. }
  590. // Feature-detect IE's crummy client rect reporting for bidi text
  591. var badBidiRects;
  592. function hasBadBidiRects(measure) {
  593. if (badBidiRects != null) { return badBidiRects }
  594. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  595. var r0 = range(txt, 0, 1).getBoundingClientRect();
  596. var r1 = range(txt, 1, 2).getBoundingClientRect();
  597. removeChildren(measure);
  598. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  599. return badBidiRects = (r1.right - r0.right < 3)
  600. }
  601. // See if "".split is the broken IE version, if so, provide an
  602. // alternative way to split lines.
  603. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  604. var pos = 0, result = [], l = string.length;
  605. while (pos <= l) {
  606. var nl = string.indexOf("\n", pos);
  607. if (nl == -1) { nl = string.length; }
  608. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  609. var rt = line.indexOf("\r");
  610. if (rt != -1) {
  611. result.push(line.slice(0, rt));
  612. pos += rt + 1;
  613. } else {
  614. result.push(line);
  615. pos = nl + 1;
  616. }
  617. }
  618. return result
  619. } : function (string) { return string.split(/\r\n?|\n/); };
  620. var hasSelection = window.getSelection ? function (te) {
  621. try { return te.selectionStart != te.selectionEnd }
  622. catch (e) { return false }
  623. } : function (te) {
  624. var range;
  625. try { range = te.ownerDocument.selection.createRange(); }
  626. catch (e) { }
  627. if (!range || range.parentElement() != te) { return false }
  628. return range.compareEndPoints("StartToEnd", range) != 0
  629. };
  630. var hasCopyEvent = (function () {
  631. var e = elt("div");
  632. if ("oncopy" in e) { return true }
  633. e.setAttribute("oncopy", "return;");
  634. return typeof e.oncopy == "function"
  635. })();
  636. var badZoomedRects = null;
  637. function hasBadZoomedRects(measure) {
  638. if (badZoomedRects != null) { return badZoomedRects }
  639. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  640. var normal = node.getBoundingClientRect();
  641. var fromRange = range(node, 0, 1).getBoundingClientRect();
  642. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  643. }
  644. // Known modes, by name and by MIME
  645. var modes = {}, mimeModes = {};
  646. // Extra arguments are stored as the mode's dependencies, which is
  647. // used by (legacy) mechanisms like loadmode.js to automatically
  648. // load a mode. (Preferred mechanism is the require/define calls.)
  649. function defineMode(name, mode) {
  650. if (arguments.length > 2)
  651. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  652. modes[name] = mode;
  653. }
  654. function defineMIME(mime, spec) {
  655. mimeModes[mime] = spec;
  656. }
  657. // Given a MIME type, a {name, ...options} config object, or a name
  658. // string, return a mode config object.
  659. function resolveMode(spec) {
  660. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  661. spec = mimeModes[spec];
  662. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  663. var found = mimeModes[spec.name];
  664. if (typeof found == "string") { found = { name: found }; }
  665. spec = createObj(found, spec);
  666. spec.name = found.name;
  667. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  668. return resolveMode("application/xml")
  669. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  670. return resolveMode("application/json")
  671. }
  672. if (typeof spec == "string") { return { name: spec } }
  673. else { return spec || { name: "null" } }
  674. }
  675. // Given a mode spec (anything that resolveMode accepts), find and
  676. // initialize an actual mode object.
  677. function getMode(options, spec) {
  678. spec = resolveMode(spec);
  679. var mfactory = modes[spec.name];
  680. if (!mfactory) { return getMode(options, "text/plain") }
  681. var modeObj = mfactory(options, spec);
  682. if (modeExtensions.hasOwnProperty(spec.name)) {
  683. var exts = modeExtensions[spec.name];
  684. for (var prop in exts) {
  685. if (!exts.hasOwnProperty(prop)) { continue }
  686. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  687. modeObj[prop] = exts[prop];
  688. }
  689. }
  690. modeObj.name = spec.name;
  691. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  692. if (spec.modeProps) {
  693. for (var prop$1 in spec.modeProps)
  694. { modeObj[prop$1] = spec.modeProps[prop$1]; }
  695. }
  696. return modeObj
  697. }
  698. // This can be used to attach properties to mode objects from
  699. // outside the actual mode definition.
  700. var modeExtensions = {};
  701. function extendMode(mode, properties) {
  702. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  703. copyObj(properties, exts);
  704. }
  705. function copyState(mode, state) {
  706. if (state === true) { return state }
  707. if (mode.copyState) { return mode.copyState(state) }
  708. var nstate = {};
  709. for (var n in state) {
  710. var val = state[n];
  711. if (val instanceof Array) { val = val.concat([]); }
  712. nstate[n] = val;
  713. }
  714. return nstate
  715. }
  716. // Given a mode and a state (for that mode), find the inner mode and
  717. // state at the position that the state refers to.
  718. function innerMode(mode, state) {
  719. var info;
  720. while (mode.innerMode) {
  721. info = mode.innerMode(state);
  722. if (!info || info.mode == mode) { break }
  723. state = info.state;
  724. mode = info.mode;
  725. }
  726. return info || { mode: mode, state: state }
  727. }
  728. function startState(mode, a1, a2) {
  729. return mode.startState ? mode.startState(a1, a2) : true
  730. }
  731. // STRING STREAM
  732. // Fed to the mode parsers, provides helper functions to make
  733. // parsers more succinct.
  734. var StringStream = function (string, tabSize, lineOracle) {
  735. this.pos = this.start = 0;
  736. this.string = string;
  737. this.tabSize = tabSize || 8;
  738. this.lastColumnPos = this.lastColumnValue = 0;
  739. this.lineStart = 0;
  740. this.lineOracle = lineOracle;
  741. };
  742. StringStream.prototype.eol = function () { return this.pos >= this.string.length };
  743. StringStream.prototype.sol = function () { return this.pos == this.lineStart };
  744. StringStream.prototype.peek = function () { return this.string.charAt(this.pos) || undefined };
  745. StringStream.prototype.next = function () {
  746. if (this.pos < this.string.length)
  747. { return this.string.charAt(this.pos++) }
  748. };
  749. StringStream.prototype.eat = function (match) {
  750. var ch = this.string.charAt(this.pos);
  751. var ok;
  752. if (typeof match == "string") { ok = ch == match; }
  753. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  754. if (ok) { ++this.pos; return ch }
  755. };
  756. StringStream.prototype.eatWhile = function (match) {
  757. var start = this.pos;
  758. while (this.eat(match)) { }
  759. return this.pos > start
  760. };
  761. StringStream.prototype.eatSpace = function () {
  762. var start = this.pos;
  763. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  764. return this.pos > start
  765. };
  766. StringStream.prototype.skipToEnd = function () { this.pos = this.string.length; };
  767. StringStream.prototype.skipTo = function (ch) {
  768. var found = this.string.indexOf(ch, this.pos);
  769. if (found > -1) { this.pos = found; return true }
  770. };
  771. StringStream.prototype.backUp = function (n) { this.pos -= n; };
  772. StringStream.prototype.column = function () {
  773. if (this.lastColumnPos < this.start) {
  774. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  775. this.lastColumnPos = this.start;
  776. }
  777. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  778. };
  779. StringStream.prototype.indentation = function () {
  780. return countColumn(this.string, null, this.tabSize) -
  781. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  782. };
  783. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  784. if (typeof pattern == "string") {
  785. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  786. var substr = this.string.substr(this.pos, pattern.length);
  787. if (cased(substr) == cased(pattern)) {
  788. if (consume !== false) { this.pos += pattern.length; }
  789. return true
  790. }
  791. } else {
  792. var match = this.string.slice(this.pos).match(pattern);
  793. if (match && match.index > 0) { return null }
  794. if (match && consume !== false) { this.pos += match[0].length; }
  795. return match
  796. }
  797. };
  798. StringStream.prototype.current = function () { return this.string.slice(this.start, this.pos) };
  799. StringStream.prototype.hideFirstChars = function (n, inner) {
  800. this.lineStart += n;
  801. try { return inner() }
  802. finally { this.lineStart -= n; }
  803. };
  804. StringStream.prototype.lookAhead = function (n) {
  805. var oracle = this.lineOracle;
  806. return oracle && oracle.lookAhead(n)
  807. };
  808. StringStream.prototype.baseToken = function () {
  809. var oracle = this.lineOracle;
  810. return oracle && oracle.baseToken(this.pos)
  811. };
  812. // Find the line object corresponding to the given line number.
  813. function getLine(doc, n) {
  814. n -= doc.first;
  815. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  816. var chunk = doc;
  817. while (!chunk.lines) {
  818. for (var i = 0; ; ++i) {
  819. var child = chunk.children[i], sz = child.chunkSize();
  820. if (n < sz) { chunk = child; break }
  821. n -= sz;
  822. }
  823. }
  824. return chunk.lines[n]
  825. }
  826. // Get the part of a document between two positions, as an array of
  827. // strings.
  828. function getBetween(doc, start, end) {
  829. var out = [], n = start.line;
  830. doc.iter(start.line, end.line + 1, function (line) {
  831. var text = line.text;
  832. if (n == end.line) { text = text.slice(0, end.ch); }
  833. if (n == start.line) { text = text.slice(start.ch); }
  834. out.push(text);
  835. ++n;
  836. });
  837. return out
  838. }
  839. // Get the lines between from and to, as array of strings.
  840. function getLines(doc, from, to) {
  841. var out = [];
  842. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  843. return out
  844. }
  845. // Update the height of a line, propagating the height change
  846. // upwards to parent nodes.
  847. function updateLineHeight(line, height) {
  848. var diff = height - line.height;
  849. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  850. }
  851. // Given a line object, find its line number by walking up through
  852. // its parent links.
  853. function lineNo(line) {
  854. if (line.parent == null) { return null }
  855. var cur = line.parent, no = indexOf(cur.lines, line);
  856. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  857. for (var i = 0; ; ++i) {
  858. if (chunk.children[i] == cur) { break }
  859. no += chunk.children[i].chunkSize();
  860. }
  861. }
  862. return no + cur.first
  863. }
  864. // Find the line at the given vertical position, using the height
  865. // information in the document tree.
  866. function lineAtHeight(chunk, h) {
  867. var n = chunk.first;
  868. outer: do {
  869. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  870. var child = chunk.children[i$1], ch = child.height;
  871. if (h < ch) { chunk = child; continue outer }
  872. h -= ch;
  873. n += child.chunkSize();
  874. }
  875. return n
  876. } while (!chunk.lines)
  877. var i = 0;
  878. for (; i < chunk.lines.length; ++i) {
  879. var line = chunk.lines[i], lh = line.height;
  880. if (h < lh) { break }
  881. h -= lh;
  882. }
  883. return n + i
  884. }
  885. function isLine(doc, l) { return l >= doc.first && l < doc.first + doc.size }
  886. function lineNumberFor(options, i) {
  887. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  888. }
  889. // A Pos instance represents a position within the text.
  890. function Pos(line, ch, sticky) {
  891. if (sticky === void 0) sticky = null;
  892. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  893. this.line = line;
  894. this.ch = ch;
  895. this.sticky = sticky;
  896. }
  897. // Compare two positions, return 0 if they are the same, a negative
  898. // number when a is less, and a positive number otherwise.
  899. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  900. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  901. function copyPos(x) { return Pos(x.line, x.ch) }
  902. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  903. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  904. // Most of the external API clips given positions to make sure they
  905. // actually exist within the document.
  906. function clipLine(doc, n) { return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1)) }
  907. function clipPos(doc, pos) {
  908. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  909. var last = doc.first + doc.size - 1;
  910. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  911. return clipToLen(pos, getLine(doc, pos.line).text.length)
  912. }
  913. function clipToLen(pos, linelen) {
  914. var ch = pos.ch;
  915. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  916. else if (ch < 0) { return Pos(pos.line, 0) }
  917. else { return pos }
  918. }
  919. function clipPosArray(doc, array) {
  920. var out = [];
  921. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  922. return out
  923. }
  924. var SavedContext = function (state, lookAhead) {
  925. this.state = state;
  926. this.lookAhead = lookAhead;
  927. };
  928. var Context = function (doc, state, line, lookAhead) {
  929. this.state = state;
  930. this.doc = doc;
  931. this.line = line;
  932. this.maxLookAhead = lookAhead || 0;
  933. this.baseTokens = null;
  934. this.baseTokenPos = 1;
  935. };
  936. Context.prototype.lookAhead = function (n) {
  937. var line = this.doc.getLine(this.line + n);
  938. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  939. return line
  940. };
  941. Context.prototype.baseToken = function (n) {
  942. if (!this.baseTokens) { return null }
  943. while (this.baseTokens[this.baseTokenPos] <= n)
  944. { this.baseTokenPos += 2; }
  945. var type = this.baseTokens[this.baseTokenPos + 1];
  946. return {
  947. type: type && type.replace(/( |^)overlay .*/, ""),
  948. size: this.baseTokens[this.baseTokenPos] - n
  949. }
  950. };
  951. Context.prototype.nextLine = function () {
  952. this.line++;
  953. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  954. };
  955. Context.fromSaved = function (doc, saved, line) {
  956. if (saved instanceof SavedContext)
  957. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  958. else
  959. { return new Context(doc, copyState(doc.mode, saved), line) }
  960. };
  961. Context.prototype.save = function (copy) {
  962. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  963. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  964. };
  965. // Compute a style array (an array starting with a mode generation
  966. // -- for invalidation -- followed by pairs of end positions and
  967. // style strings), which is used to highlight the tokens on the
  968. // line.
  969. function highlightLine(cm, line, context, forceToEnd) {
  970. // A styles array always starts with a number identifying the
  971. // mode/overlays that it is based on (for easy invalidation).
  972. var st = [cm.state.modeGen], lineClasses = {};
  973. // Compute the base array of styles
  974. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  975. lineClasses, forceToEnd);
  976. var state = context.state;
  977. // Run overlays, adjust style array.
  978. var loop = function (o) {
  979. context.baseTokens = st;
  980. var overlay = cm.state.overlays[o], i = 1, at = 0;
  981. context.state = true;
  982. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  983. var start = i;
  984. // Ensure there's a token end at the current position, and that i points at it
  985. while (at < end) {
  986. var i_end = st[i];
  987. if (i_end > end)
  988. { st.splice(i, 1, end, st[i + 1], i_end); }
  989. i += 2;
  990. at = Math.min(end, i_end);
  991. }
  992. if (!style) { return }
  993. if (overlay.opaque) {
  994. st.splice(start, i - start, end, "overlay " + style);
  995. i = start + 2;
  996. } else {
  997. for (; start < i; start += 2) {
  998. var cur = st[start + 1];
  999. st[start + 1] = (cur ? cur + " " : "") + "overlay " + style;
  1000. }
  1001. }
  1002. }, lineClasses);
  1003. context.state = state;
  1004. context.baseTokens = null;
  1005. context.baseTokenPos = 1;
  1006. };
  1007. for (var o = 0; o < cm.state.overlays.length; ++o) loop(o);
  1008. return { styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null }
  1009. }
  1010. function getLineStyles(cm, line, updateFrontier) {
  1011. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1012. var context = getContextBefore(cm, lineNo(line));
  1013. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  1014. var result = highlightLine(cm, line, context);
  1015. if (resetState) { context.state = resetState; }
  1016. line.stateAfter = context.save(!resetState);
  1017. line.styles = result.styles;
  1018. if (result.classes) { line.styleClasses = result.classes; }
  1019. else if (line.styleClasses) { line.styleClasses = null; }
  1020. if (updateFrontier === cm.doc.highlightFrontier)
  1021. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1022. }
  1023. return line.styles
  1024. }
  1025. function getContextBefore(cm, n, precise) {
  1026. var doc = cm.doc, display = cm.display;
  1027. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1028. var start = findStartLine(cm, n, precise);
  1029. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1030. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1031. doc.iter(start, n, function (line) {
  1032. processLine(cm, line.text, context);
  1033. var pos = context.line;
  1034. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1035. context.nextLine();
  1036. });
  1037. if (precise) { doc.modeFrontier = context.line; }
  1038. return context
  1039. }
  1040. // Lightweight form of highlight -- proceed over this line and
  1041. // update state, but don't save a style array. Used for lines that
  1042. // aren't currently visible.
  1043. function processLine(cm, text, context, startAt) {
  1044. var mode = cm.doc.mode;
  1045. var stream = new StringStream(text, cm.options.tabSize, context);
  1046. stream.start = stream.pos = startAt || 0;
  1047. if (text == "") { callBlankLine(mode, context.state); }
  1048. while (!stream.eol()) {
  1049. readToken(mode, stream, context.state);
  1050. stream.start = stream.pos;
  1051. }
  1052. }
  1053. function callBlankLine(mode, state) {
  1054. if (mode.blankLine) { return mode.blankLine(state) }
  1055. if (!mode.innerMode) { return }
  1056. var inner = innerMode(mode, state);
  1057. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1058. }
  1059. function readToken(mode, stream, state, inner) {
  1060. for (var i = 0; i < 10; i++) {
  1061. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1062. var style = mode.token(stream, state);
  1063. if (stream.pos > stream.start) { return style }
  1064. }
  1065. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1066. }
  1067. var Token = function (stream, type, state) {
  1068. this.start = stream.start; this.end = stream.pos;
  1069. this.string = stream.current();
  1070. this.type = type || null;
  1071. this.state = state;
  1072. };
  1073. // Utility for getTokenAt and getLineTokens
  1074. function takeToken(cm, pos, precise, asArray) {
  1075. var doc = cm.doc, mode = doc.mode, style;
  1076. pos = clipPos(doc, pos);
  1077. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1078. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1079. if (asArray) { tokens = []; }
  1080. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1081. stream.start = stream.pos;
  1082. style = readToken(mode, stream, context.state);
  1083. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1084. }
  1085. return asArray ? tokens : new Token(stream, style, context.state)
  1086. }
  1087. function extractLineClasses(type, output) {
  1088. if (type) {
  1089. for (; ;) {
  1090. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1091. if (!lineClass) { break }
  1092. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1093. var prop = lineClass[1] ? "bgClass" : "textClass";
  1094. if (output[prop] == null)
  1095. { output[prop] = lineClass[2]; }
  1096. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1097. { output[prop] += " " + lineClass[2]; }
  1098. }
  1099. }
  1100. return type
  1101. }
  1102. // Run the given mode's parser over a line, calling f for each token.
  1103. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1104. var flattenSpans = mode.flattenSpans;
  1105. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1106. var curStart = 0, curStyle = null;
  1107. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1108. var inner = cm.options.addModeClass && [null];
  1109. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1110. while (!stream.eol()) {
  1111. if (stream.pos > cm.options.maxHighlightLength) {
  1112. flattenSpans = false;
  1113. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1114. stream.pos = text.length;
  1115. style = null;
  1116. } else {
  1117. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1118. }
  1119. if (inner) {
  1120. var mName = inner[0].name;
  1121. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1122. }
  1123. if (!flattenSpans || curStyle != style) {
  1124. while (curStart < stream.start) {
  1125. curStart = Math.min(stream.start, curStart + 5000);
  1126. f(curStart, curStyle);
  1127. }
  1128. curStyle = style;
  1129. }
  1130. stream.start = stream.pos;
  1131. }
  1132. while (curStart < stream.pos) {
  1133. // Webkit seems to refuse to render text nodes longer than 57444
  1134. // characters, and returns inaccurate measurements in nodes
  1135. // starting around 5000 chars.
  1136. var pos = Math.min(stream.pos, curStart + 5000);
  1137. f(pos, curStyle);
  1138. curStart = pos;
  1139. }
  1140. }
  1141. // Finds the line to start with when starting a parse. Tries to
  1142. // find a line with a stateAfter, so that it can start with a
  1143. // valid state. If that fails, it returns the line with the
  1144. // smallest indentation, which tends to need the least context to
  1145. // parse correctly.
  1146. function findStartLine(cm, n, precise) {
  1147. var minindent, minline, doc = cm.doc;
  1148. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1149. for (var search = n; search > lim; --search) {
  1150. if (search <= doc.first) { return doc.first }
  1151. var line = getLine(doc, search - 1), after = line.stateAfter;
  1152. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1153. { return search }
  1154. var indented = countColumn(line.text, null, cm.options.tabSize);
  1155. if (minline == null || minindent > indented) {
  1156. minline = search - 1;
  1157. minindent = indented;
  1158. }
  1159. }
  1160. return minline
  1161. }
  1162. function retreatFrontier(doc, n) {
  1163. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1164. if (doc.highlightFrontier < n - 10) { return }
  1165. var start = doc.first;
  1166. for (var line = n - 1; line > start; line--) {
  1167. var saved = getLine(doc, line).stateAfter;
  1168. // change is on 3
  1169. // state on line 1 looked ahead 2 -- so saw 3
  1170. // test 1 + 2 < 3 should cover this
  1171. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1172. start = line + 1;
  1173. break
  1174. }
  1175. }
  1176. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1177. }
  1178. // Optimize some code when these features are not used.
  1179. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1180. function seeReadOnlySpans() {
  1181. sawReadOnlySpans = true;
  1182. }
  1183. function seeCollapsedSpans() {
  1184. sawCollapsedSpans = true;
  1185. }
  1186. // TEXTMARKER SPANS
  1187. function MarkedSpan(marker, from, to) {
  1188. this.marker = marker;
  1189. this.from = from; this.to = to;
  1190. }
  1191. // Search an array of spans for a span matching the given marker.
  1192. function getMarkedSpanFor(spans, marker) {
  1193. if (spans) {
  1194. for (var i = 0; i < spans.length; ++i) {
  1195. var span = spans[i];
  1196. if (span.marker == marker) { return span }
  1197. }
  1198. }
  1199. }
  1200. // Remove a span from an array, returning undefined if no spans are
  1201. // left (we don't store arrays for lines without spans).
  1202. function removeMarkedSpan(spans, span) {
  1203. var r;
  1204. for (var i = 0; i < spans.length; ++i)
  1205. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1206. return r
  1207. }
  1208. // Add a span to a line.
  1209. function addMarkedSpan(line, span, op) {
  1210. var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
  1211. if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
  1212. line.markedSpans.push(span);
  1213. } else {
  1214. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1215. if (inThisOp) { inThisOp.add(line.markedSpans); }
  1216. }
  1217. span.marker.attachLine(line);
  1218. }
  1219. // Used for the algorithm that adjusts markers for a change in the
  1220. // document. These functions cut an array of spans at a given
  1221. // character position, returning an array of remaining chunks (or
  1222. // undefined if nothing remains).
  1223. function markedSpansBefore(old, startCh, isInsert) {
  1224. var nw;
  1225. if (old) {
  1226. for (var i = 0; i < old.length; ++i) {
  1227. var span = old[i], marker = span.marker;
  1228. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1229. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1230. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1231. ; (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1232. }
  1233. }
  1234. }
  1235. return nw
  1236. }
  1237. function markedSpansAfter(old, endCh, isInsert) {
  1238. var nw;
  1239. if (old) {
  1240. for (var i = 0; i < old.length; ++i) {
  1241. var span = old[i], marker = span.marker;
  1242. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1243. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1244. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1245. ; (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1246. span.to == null ? null : span.to - endCh));
  1247. }
  1248. }
  1249. }
  1250. return nw
  1251. }
  1252. // Given a change object, compute the new set of marker spans that
  1253. // cover the line in which the change took place. Removes spans
  1254. // entirely within the change, reconnects spans belonging to the
  1255. // same marker that appear on both sides of the change, and cuts off
  1256. // spans partially within the change. Returns an array of span
  1257. // arrays with one element for each line in (after) the change.
  1258. function stretchSpansOverChange(doc, change) {
  1259. if (change.full) { return null }
  1260. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1261. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1262. if (!oldFirst && !oldLast) { return null }
  1263. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1264. // Get the spans that 'stick out' on both sides
  1265. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1266. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1267. // Next, merge those two ends
  1268. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1269. if (first) {
  1270. // Fix up .to properties of first
  1271. for (var i = 0; i < first.length; ++i) {
  1272. var span = first[i];
  1273. if (span.to == null) {
  1274. var found = getMarkedSpanFor(last, span.marker);
  1275. if (!found) { span.to = startCh; }
  1276. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1277. }
  1278. }
  1279. }
  1280. if (last) {
  1281. // Fix up .from in last (or move them into first in case of sameLine)
  1282. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1283. var span$1 = last[i$1];
  1284. if (span$1.to != null) { span$1.to += offset; }
  1285. if (span$1.from == null) {
  1286. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1287. if (!found$1) {
  1288. span$1.from = offset;
  1289. if (sameLine) { (first || (first = [])).push(span$1); }
  1290. }
  1291. } else {
  1292. span$1.from += offset;
  1293. if (sameLine) { (first || (first = [])).push(span$1); }
  1294. }
  1295. }
  1296. }
  1297. // Make sure we didn't create any zero-length spans
  1298. if (first) { first = clearEmptySpans(first); }
  1299. if (last && last != first) { last = clearEmptySpans(last); }
  1300. var newMarkers = [first];
  1301. if (!sameLine) {
  1302. // Fill gap with whole-line-spans
  1303. var gap = change.text.length - 2, gapMarkers;
  1304. if (gap > 0 && first) {
  1305. for (var i$2 = 0; i$2 < first.length; ++i$2) {
  1306. if (first[i$2].to == null)
  1307. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); }
  1308. }
  1309. }
  1310. for (var i$3 = 0; i$3 < gap; ++i$3)
  1311. { newMarkers.push(gapMarkers); }
  1312. newMarkers.push(last);
  1313. }
  1314. return newMarkers
  1315. }
  1316. // Remove spans that are empty and don't have a clearWhenEmpty
  1317. // option of false.
  1318. function clearEmptySpans(spans) {
  1319. for (var i = 0; i < spans.length; ++i) {
  1320. var span = spans[i];
  1321. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1322. { spans.splice(i--, 1); }
  1323. }
  1324. if (!spans.length) { return null }
  1325. return spans
  1326. }
  1327. // Used to 'clip' out readOnly ranges when making a change.
  1328. function removeReadOnlyRanges(doc, from, to) {
  1329. var markers = null;
  1330. doc.iter(from.line, to.line + 1, function (line) {
  1331. if (line.markedSpans) {
  1332. for (var i = 0; i < line.markedSpans.length; ++i) {
  1333. var mark = line.markedSpans[i].marker;
  1334. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1335. { (markers || (markers = [])).push(mark); }
  1336. }
  1337. }
  1338. });
  1339. if (!markers) { return null }
  1340. var parts = [{ from: from, to: to }];
  1341. for (var i = 0; i < markers.length; ++i) {
  1342. var mk = markers[i], m = mk.find(0);
  1343. for (var j = 0; j < parts.length; ++j) {
  1344. var p = parts[j];
  1345. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1346. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1347. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1348. { newParts.push({ from: p.from, to: m.from }); }
  1349. if (dto > 0 || !mk.inclusiveRight && !dto)
  1350. { newParts.push({ from: m.to, to: p.to }); }
  1351. parts.splice.apply(parts, newParts);
  1352. j += newParts.length - 3;
  1353. }
  1354. }
  1355. return parts
  1356. }
  1357. // Connect or disconnect spans from a line.
  1358. function detachMarkedSpans(line) {
  1359. var spans = line.markedSpans;
  1360. if (!spans) { return }
  1361. for (var i = 0; i < spans.length; ++i)
  1362. { spans[i].marker.detachLine(line); }
  1363. line.markedSpans = null;
  1364. }
  1365. function attachMarkedSpans(line, spans) {
  1366. if (!spans) { return }
  1367. for (var i = 0; i < spans.length; ++i)
  1368. { spans[i].marker.attachLine(line); }
  1369. line.markedSpans = spans;
  1370. }
  1371. // Helpers used when computing which overlapping collapsed span
  1372. // counts as the larger one.
  1373. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1374. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1375. // Returns a number indicating which of two overlapping collapsed
  1376. // spans is larger (and thus includes the other). Falls back to
  1377. // comparing ids when the spans cover exactly the same range.
  1378. function compareCollapsedMarkers(a, b) {
  1379. var lenDiff = a.lines.length - b.lines.length;
  1380. if (lenDiff != 0) { return lenDiff }
  1381. var aPos = a.find(), bPos = b.find();
  1382. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1383. if (fromCmp) { return -fromCmp }
  1384. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1385. if (toCmp) { return toCmp }
  1386. return b.id - a.id
  1387. }
  1388. // Find out whether a line ends or starts in a collapsed span. If
  1389. // so, return the marker for that span.
  1390. function collapsedSpanAtSide(line, start) {
  1391. var sps = sawCollapsedSpans && line.markedSpans, found;
  1392. if (sps) {
  1393. for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1394. sp = sps[i];
  1395. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1396. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1397. { found = sp.marker; }
  1398. }
  1399. }
  1400. return found
  1401. }
  1402. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1403. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1404. function collapsedSpanAround(line, ch) {
  1405. var sps = sawCollapsedSpans && line.markedSpans, found;
  1406. if (sps) {
  1407. for (var i = 0; i < sps.length; ++i) {
  1408. var sp = sps[i];
  1409. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1410. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1411. }
  1412. }
  1413. return found
  1414. }
  1415. // Test whether there exists a collapsed span that partially
  1416. // overlaps (covers the start or end, but not both) of a new span.
  1417. // Such overlap is not allowed.
  1418. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1419. var line = getLine(doc, lineNo);
  1420. var sps = sawCollapsedSpans && line.markedSpans;
  1421. if (sps) {
  1422. for (var i = 0; i < sps.length; ++i) {
  1423. var sp = sps[i];
  1424. if (!sp.marker.collapsed) { continue }
  1425. var found = sp.marker.find(0);
  1426. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1427. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1428. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1429. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1430. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1431. { return true }
  1432. }
  1433. }
  1434. }
  1435. // A visual line is a line as drawn on the screen. Folding, for
  1436. // example, can cause multiple logical lines to appear on the same
  1437. // visual line. This finds the start of the visual line that the
  1438. // given line is part of (usually that is the line itself).
  1439. function visualLine(line) {
  1440. var merged;
  1441. while (merged = collapsedSpanAtStart(line))
  1442. { line = merged.find(-1, true).line; }
  1443. return line
  1444. }
  1445. function visualLineEnd(line) {
  1446. var merged;
  1447. while (merged = collapsedSpanAtEnd(line))
  1448. { line = merged.find(1, true).line; }
  1449. return line
  1450. }
  1451. // Returns an array of logical lines that continue the visual line
  1452. // started by the argument, or undefined if there are no such lines.
  1453. function visualLineContinued(line) {
  1454. var merged, lines;
  1455. while (merged = collapsedSpanAtEnd(line)) {
  1456. line = merged.find(1, true).line
  1457. ; (lines || (lines = [])).push(line);
  1458. }
  1459. return lines
  1460. }
  1461. // Get the line number of the start of the visual line that the
  1462. // given line number is part of.
  1463. function visualLineNo(doc, lineN) {
  1464. var line = getLine(doc, lineN), vis = visualLine(line);
  1465. if (line == vis) { return lineN }
  1466. return lineNo(vis)
  1467. }
  1468. // Get the line number of the start of the next visual line after
  1469. // the given line.
  1470. function visualLineEndNo(doc, lineN) {
  1471. if (lineN > doc.lastLine()) { return lineN }
  1472. var line = getLine(doc, lineN), merged;
  1473. if (!lineIsHidden(doc, line)) { return lineN }
  1474. while (merged = collapsedSpanAtEnd(line))
  1475. { line = merged.find(1, true).line; }
  1476. return lineNo(line) + 1
  1477. }
  1478. // Compute whether a line is hidden. Lines count as hidden when they
  1479. // are part of a visual line that starts with another line, or when
  1480. // they are entirely covered by collapsed, non-widget span.
  1481. function lineIsHidden(doc, line) {
  1482. var sps = sawCollapsedSpans && line.markedSpans;
  1483. if (sps) {
  1484. for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1485. sp = sps[i];
  1486. if (!sp.marker.collapsed) { continue }
  1487. if (sp.from == null) { return true }
  1488. if (sp.marker.widgetNode) { continue }
  1489. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1490. { return true }
  1491. }
  1492. }
  1493. }
  1494. function lineIsHiddenInner(doc, line, span) {
  1495. if (span.to == null) {
  1496. var end = span.marker.find(1, true);
  1497. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1498. }
  1499. if (span.marker.inclusiveRight && span.to == line.text.length)
  1500. { return true }
  1501. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1502. sp = line.markedSpans[i];
  1503. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1504. (sp.to == null || sp.to != span.from) &&
  1505. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1506. lineIsHiddenInner(doc, line, sp)) { return true }
  1507. }
  1508. }
  1509. // Find the height above the given line.
  1510. function heightAtLine(lineObj) {
  1511. lineObj = visualLine(lineObj);
  1512. var h = 0, chunk = lineObj.parent;
  1513. for (var i = 0; i < chunk.lines.length; ++i) {
  1514. var line = chunk.lines[i];
  1515. if (line == lineObj) { break }
  1516. else { h += line.height; }
  1517. }
  1518. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1519. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1520. var cur = p.children[i$1];
  1521. if (cur == chunk) { break }
  1522. else { h += cur.height; }
  1523. }
  1524. }
  1525. return h
  1526. }
  1527. // Compute the character length of a line, taking into account
  1528. // collapsed ranges (see markText) that might hide parts, and join
  1529. // other lines onto it.
  1530. function lineLength(line) {
  1531. if (line.height == 0) { return 0 }
  1532. var len = line.text.length, merged, cur = line;
  1533. while (merged = collapsedSpanAtStart(cur)) {
  1534. var found = merged.find(0, true);
  1535. cur = found.from.line;
  1536. len += found.from.ch - found.to.ch;
  1537. }
  1538. cur = line;
  1539. while (merged = collapsedSpanAtEnd(cur)) {
  1540. var found$1 = merged.find(0, true);
  1541. len -= cur.text.length - found$1.from.ch;
  1542. cur = found$1.to.line;
  1543. len += cur.text.length - found$1.to.ch;
  1544. }
  1545. return len
  1546. }
  1547. // Find the longest line in the document.
  1548. function findMaxLine(cm) {
  1549. var d = cm.display, doc = cm.doc;
  1550. d.maxLine = getLine(doc, doc.first);
  1551. d.maxLineLength = lineLength(d.maxLine);
  1552. d.maxLineChanged = true;
  1553. doc.iter(function (line) {
  1554. var len = lineLength(line);
  1555. if (len > d.maxLineLength) {
  1556. d.maxLineLength = len;
  1557. d.maxLine = line;
  1558. }
  1559. });
  1560. }
  1561. // LINE DATA STRUCTURE
  1562. // Line objects. These hold state related to a line, including
  1563. // highlighting info (the styles array).
  1564. var Line = function (text, markedSpans, estimateHeight) {
  1565. this.text = text;
  1566. attachMarkedSpans(this, markedSpans);
  1567. this.height = estimateHeight ? estimateHeight(this) : 1;
  1568. };
  1569. Line.prototype.lineNo = function () { return lineNo(this) };
  1570. eventMixin(Line);
  1571. // Change the content (text, markers) of a line. Automatically
  1572. // invalidates cached information and tries to re-estimate the
  1573. // line's height.
  1574. function updateLine(line, text, markedSpans, estimateHeight) {
  1575. line.text = text;
  1576. if (line.stateAfter) { line.stateAfter = null; }
  1577. if (line.styles) { line.styles = null; }
  1578. if (line.order != null) { line.order = null; }
  1579. detachMarkedSpans(line);
  1580. attachMarkedSpans(line, markedSpans);
  1581. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1582. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1583. }
  1584. // Detach a line from the document tree and its markers.
  1585. function cleanUpLine(line) {
  1586. line.parent = null;
  1587. detachMarkedSpans(line);
  1588. }
  1589. // Convert a style as returned by a mode (either null, or a string
  1590. // containing one or more styles) to a CSS style. This is cached,
  1591. // and also looks for line-wide styles.
  1592. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1593. function interpretTokenStyle(style, options) {
  1594. if (!style || /^\s*$/.test(style)) { return null }
  1595. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1596. return cache[style] ||
  1597. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1598. }
  1599. // Render the DOM representation of the text of a line. Also builds
  1600. // up a 'line map', which points at the DOM nodes that represent
  1601. // specific stretches of text, and is used by the measuring code.
  1602. // The returned object contains the DOM node, this map, and
  1603. // information about line-wide styles that were set by the mode.
  1604. function buildLineContent(cm, lineView) {
  1605. // The padding-right forces the element to have a 'border', which
  1606. // is needed on Webkit to be able to get line-level bounding
  1607. // rectangles for it (in measureChar).
  1608. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1609. var builder = {
  1610. pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1611. col: 0, pos: 0, cm: cm,
  1612. trailingSpace: false,
  1613. splitSpaces: cm.getOption("lineWrapping")
  1614. };
  1615. lineView.measure = {};
  1616. // Iterate over the logical lines that make up this visual line.
  1617. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0) ; i++) {
  1618. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1619. builder.pos = 0;
  1620. builder.addToken = buildToken;
  1621. // Optionally wire in some hacks into the token-rendering
  1622. // algorithm, to deal with browser quirks.
  1623. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1624. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1625. builder.map = [];
  1626. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1627. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1628. if (line.styleClasses) {
  1629. if (line.styleClasses.bgClass)
  1630. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1631. if (line.styleClasses.textClass)
  1632. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1633. }
  1634. // Ensure at least a single node is present, for measuring.
  1635. if (builder.map.length == 0)
  1636. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1637. // Store the map and a cache object for the current logical line
  1638. if (i == 0) {
  1639. lineView.measure.map = builder.map;
  1640. lineView.measure.cache = {};
  1641. } else {
  1642. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1643. ; (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1644. }
  1645. }
  1646. // See issue #2901
  1647. if (webkit) {
  1648. var last = builder.content.lastChild;
  1649. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1650. { builder.content.className = "cm-tab-wrap-hack"; }
  1651. }
  1652. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1653. if (builder.pre.className)
  1654. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1655. return builder
  1656. }
  1657. function defaultSpecialCharPlaceholder(ch) {
  1658. var token = elt("span", "\u2022", "cm-invalidchar");
  1659. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1660. token.setAttribute("aria-label", token.title);
  1661. return token
  1662. }
  1663. // Build up the DOM representation for a single token, and add it to
  1664. // the line map. Takes care to render special characters separately.
  1665. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1666. if (!text) { return }
  1667. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1668. var special = builder.cm.state.specialChars, mustWrap = false;
  1669. var content;
  1670. if (!special.test(text)) {
  1671. builder.col += text.length;
  1672. content = document.createTextNode(displayText);
  1673. builder.map.push(builder.pos, builder.pos + text.length, content);
  1674. if (ie && ie_version < 9) { mustWrap = true; }
  1675. builder.pos += text.length;
  1676. } else {
  1677. content = document.createDocumentFragment();
  1678. var pos = 0;
  1679. while (true) {
  1680. special.lastIndex = pos;
  1681. var m = special.exec(text);
  1682. var skipped = m ? m.index - pos : text.length - pos;
  1683. if (skipped) {
  1684. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1685. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1686. else { content.appendChild(txt); }
  1687. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1688. builder.col += skipped;
  1689. builder.pos += skipped;
  1690. }
  1691. if (!m) { break }
  1692. pos += skipped + 1;
  1693. var txt$1 = (void 0);
  1694. if (m[0] == "\t") {
  1695. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1696. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1697. txt$1.setAttribute("role", "presentation");
  1698. txt$1.setAttribute("cm-text", "\t");
  1699. builder.col += tabWidth;
  1700. } else if (m[0] == "\r" || m[0] == "\n") {
  1701. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1702. txt$1.setAttribute("cm-text", m[0]);
  1703. builder.col += 1;
  1704. } else {
  1705. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1706. txt$1.setAttribute("cm-text", m[0]);
  1707. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1708. else { content.appendChild(txt$1); }
  1709. builder.col += 1;
  1710. }
  1711. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1712. builder.pos++;
  1713. }
  1714. }
  1715. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1716. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  1717. var fullStyle = style || "";
  1718. if (startStyle) { fullStyle += startStyle; }
  1719. if (endStyle) { fullStyle += endStyle; }
  1720. var token = elt("span", [content], fullStyle, css);
  1721. if (attributes) {
  1722. for (var attr in attributes) {
  1723. if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1724. { token.setAttribute(attr, attributes[attr]); }
  1725. }
  1726. }
  1727. return builder.content.appendChild(token)
  1728. }
  1729. builder.content.appendChild(content);
  1730. }
  1731. // Change some spaces to NBSP to prevent the browser from collapsing
  1732. // trailing spaces at the end of a line when rendering text (issue #1362).
  1733. function splitSpaces(text, trailingBefore) {
  1734. if (text.length > 1 && !/ /.test(text)) { return text }
  1735. var spaceBefore = trailingBefore, result = "";
  1736. for (var i = 0; i < text.length; i++) {
  1737. var ch = text.charAt(i);
  1738. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1739. { ch = "\u00a0"; }
  1740. result += ch;
  1741. spaceBefore = ch == " ";
  1742. }
  1743. return result
  1744. }
  1745. // Work around nonsense dimensions being reported for stretches of
  1746. // right-to-left text.
  1747. function buildTokenBadBidi(inner, order) {
  1748. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1749. style = style ? style + " cm-force-border" : "cm-force-border";
  1750. var start = builder.pos, end = start + text.length;
  1751. for (; ;) {
  1752. // Find the part that overlaps with the start of this text
  1753. var part = (void 0);
  1754. for (var i = 0; i < order.length; i++) {
  1755. part = order[i];
  1756. if (part.to > start && part.from <= start) { break }
  1757. }
  1758. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1759. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1760. startStyle = null;
  1761. text = text.slice(part.to - start);
  1762. start = part.to;
  1763. }
  1764. }
  1765. }
  1766. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1767. var widget = !ignoreWidget && marker.widgetNode;
  1768. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1769. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1770. if (!widget)
  1771. { widget = builder.content.appendChild(document.createElement("span")); }
  1772. widget.setAttribute("cm-marker", marker.id);
  1773. }
  1774. if (widget) {
  1775. builder.cm.display.input.setUneditable(widget);
  1776. builder.content.appendChild(widget);
  1777. }
  1778. builder.pos += size;
  1779. builder.trailingSpace = false;
  1780. }
  1781. // Outputs a number of spans to make up a line, taking highlighting
  1782. // and marked text into account.
  1783. function insertLineContent(line, builder, styles) {
  1784. var spans = line.markedSpans, allText = line.text, at = 0;
  1785. if (!spans) {
  1786. for (var i$1 = 1; i$1 < styles.length; i$1 += 2)
  1787. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1 + 1], builder.cm.options)); }
  1788. return
  1789. }
  1790. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1791. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1792. for (; ;) {
  1793. if (nextChange == pos) { // Update current marker set
  1794. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1795. attributes = null;
  1796. collapsed = null; nextChange = Infinity;
  1797. var foundBookmarks = [], endStyles = (void 0);
  1798. for (var j = 0; j < spans.length; ++j) {
  1799. var sp = spans[j], m = sp.marker;
  1800. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1801. foundBookmarks.push(m);
  1802. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1803. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1804. nextChange = sp.to;
  1805. spanEndStyle = "";
  1806. }
  1807. if (m.className) { spanStyle += " " + m.className; }
  1808. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1809. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1810. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1811. // support for the old title property
  1812. // https://github.com/codemirror/CodeMirror/pull/5673
  1813. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1814. if (m.attributes) {
  1815. for (var attr in m.attributes)
  1816. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1817. }
  1818. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1819. { collapsed = sp; }
  1820. } else if (sp.from > pos && nextChange > sp.from) {
  1821. nextChange = sp.from;
  1822. }
  1823. }
  1824. if (endStyles) {
  1825. for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1826. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } }
  1827. }
  1828. if (!collapsed || collapsed.from == pos) {
  1829. for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1830. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); }
  1831. }
  1832. if (collapsed && (collapsed.from || 0) == pos) {
  1833. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1834. collapsed.marker, collapsed.from == null);
  1835. if (collapsed.to == null) { return }
  1836. if (collapsed.to == pos) { collapsed = false; }
  1837. }
  1838. }
  1839. if (pos >= len) { break }
  1840. var upto = Math.min(len, nextChange);
  1841. while (true) {
  1842. if (text) {
  1843. var end = pos + text.length;
  1844. if (!collapsed) {
  1845. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1846. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1847. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1848. }
  1849. if (end >= upto) { text = text.slice(upto - pos); pos = upto; break }
  1850. pos = end;
  1851. spanStartStyle = "";
  1852. }
  1853. text = allText.slice(at, at = styles[i++]);
  1854. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1855. }
  1856. }
  1857. }
  1858. // These objects are used to represent the visible (currently drawn)
  1859. // part of the document. A LineView may correspond to multiple
  1860. // logical lines, if those are connected by collapsed ranges.
  1861. function LineView(doc, line, lineN) {
  1862. // The starting line
  1863. this.line = line;
  1864. // Continuing lines, if any
  1865. this.rest = visualLineContinued(line);
  1866. // Number of logical lines in this visual line
  1867. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1868. this.node = this.text = null;
  1869. this.hidden = lineIsHidden(doc, line);
  1870. }
  1871. // Create a range of LineView objects for the given lines.
  1872. function buildViewArray(cm, from, to) {
  1873. var array = [], nextPos;
  1874. for (var pos = from; pos < to; pos = nextPos) {
  1875. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1876. nextPos = pos + view.size;
  1877. array.push(view);
  1878. }
  1879. return array
  1880. }
  1881. var operationGroup = null;
  1882. function pushOperation(op) {
  1883. if (operationGroup) {
  1884. operationGroup.ops.push(op);
  1885. } else {
  1886. op.ownsGroup = operationGroup = {
  1887. ops: [op],
  1888. delayedCallbacks: []
  1889. };
  1890. }
  1891. }
  1892. function fireCallbacksForOps(group) {
  1893. // Calls delayed callbacks and cursorActivity handlers until no
  1894. // new ones appear
  1895. var callbacks = group.delayedCallbacks, i = 0;
  1896. do {
  1897. for (; i < callbacks.length; i++)
  1898. { callbacks[i].call(null); }
  1899. for (var j = 0; j < group.ops.length; j++) {
  1900. var op = group.ops[j];
  1901. if (op.cursorActivityHandlers) {
  1902. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1903. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); }
  1904. }
  1905. }
  1906. } while (i < callbacks.length)
  1907. }
  1908. function finishOperation(op, endCb) {
  1909. var group = op.ownsGroup;
  1910. if (!group) { return }
  1911. try { fireCallbacksForOps(group); }
  1912. finally {
  1913. operationGroup = null;
  1914. endCb(group);
  1915. }
  1916. }
  1917. var orphanDelayedCallbacks = null;
  1918. // Often, we want to signal events at a point where we are in the
  1919. // middle of some work, but don't want the handler to start calling
  1920. // other methods on the editor, which might be in an inconsistent
  1921. // state or simply not expect any other events to happen.
  1922. // signalLater looks whether there are any handlers, and schedules
  1923. // them to be executed when the last operation ends, or, if no
  1924. // operation is active, when a timeout fires.
  1925. function signalLater(emitter, type /*, values...*/) {
  1926. var arr = getHandlers(emitter, type);
  1927. if (!arr.length) { return }
  1928. var args = Array.prototype.slice.call(arguments, 2), list;
  1929. if (operationGroup) {
  1930. list = operationGroup.delayedCallbacks;
  1931. } else if (orphanDelayedCallbacks) {
  1932. list = orphanDelayedCallbacks;
  1933. } else {
  1934. list = orphanDelayedCallbacks = [];
  1935. setTimeout(fireOrphanDelayed, 0);
  1936. }
  1937. var loop = function (i) {
  1938. list.push(function () { return arr[i].apply(null, args); });
  1939. };
  1940. for (var i = 0; i < arr.length; ++i)
  1941. loop(i);
  1942. }
  1943. function fireOrphanDelayed() {
  1944. var delayed = orphanDelayedCallbacks;
  1945. orphanDelayedCallbacks = null;
  1946. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1947. }
  1948. // When an aspect of a line changes, a string is added to
  1949. // lineView.changes. This updates the relevant part of the line's
  1950. // DOM structure.
  1951. function updateLineForChanges(cm, lineView, lineN, dims) {
  1952. for (var j = 0; j < lineView.changes.length; j++) {
  1953. var type = lineView.changes[j];
  1954. if (type == "text") { updateLineText(cm, lineView); }
  1955. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1956. else if (type == "class") { updateLineClasses(cm, lineView); }
  1957. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1958. }
  1959. lineView.changes = null;
  1960. }
  1961. // Lines with gutter elements, widgets or a background class need to
  1962. // be wrapped, and have the extra elements added to the wrapper div
  1963. function ensureLineWrapped(lineView) {
  1964. if (lineView.node == lineView.text) {
  1965. lineView.node = elt("div", null, null, "position: relative");
  1966. if (lineView.text.parentNode)
  1967. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1968. lineView.node.appendChild(lineView.text);
  1969. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1970. }
  1971. return lineView.node
  1972. }
  1973. function updateLineBackground(cm, lineView) {
  1974. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1975. if (cls) { cls += " CodeMirror-linebackground"; }
  1976. if (lineView.background) {
  1977. if (cls) { lineView.background.className = cls; }
  1978. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1979. } else if (cls) {
  1980. var wrap = ensureLineWrapped(lineView);
  1981. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1982. cm.display.input.setUneditable(lineView.background);
  1983. }
  1984. }
  1985. // Wrapper around buildLineContent which will reuse the structure
  1986. // in display.externalMeasured when possible.
  1987. function getLineContent(cm, lineView) {
  1988. var ext = cm.display.externalMeasured;
  1989. if (ext && ext.line == lineView.line) {
  1990. cm.display.externalMeasured = null;
  1991. lineView.measure = ext.measure;
  1992. return ext.built
  1993. }
  1994. return buildLineContent(cm, lineView)
  1995. }
  1996. // Redraw the line's text. Interacts with the background and text
  1997. // classes because the mode may output tokens that influence these
  1998. // classes.
  1999. function updateLineText(cm, lineView) {
  2000. var cls = lineView.text.className;
  2001. var built = getLineContent(cm, lineView);
  2002. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  2003. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2004. lineView.text = built.pre;
  2005. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2006. lineView.bgClass = built.bgClass;
  2007. lineView.textClass = built.textClass;
  2008. updateLineClasses(cm, lineView);
  2009. } else if (cls) {
  2010. lineView.text.className = cls;
  2011. }
  2012. }
  2013. function updateLineClasses(cm, lineView) {
  2014. updateLineBackground(cm, lineView);
  2015. if (lineView.line.wrapClass)
  2016. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  2017. else if (lineView.node != lineView.text)
  2018. { lineView.node.className = ""; }
  2019. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2020. lineView.text.className = textClass || "";
  2021. }
  2022. function updateLineGutter(cm, lineView, lineN, dims) {
  2023. if (lineView.gutter) {
  2024. lineView.node.removeChild(lineView.gutter);
  2025. lineView.gutter = null;
  2026. }
  2027. if (lineView.gutterBackground) {
  2028. lineView.node.removeChild(lineView.gutterBackground);
  2029. lineView.gutterBackground = null;
  2030. }
  2031. if (lineView.line.gutterClass) {
  2032. var wrap = ensureLineWrapped(lineView);
  2033. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2034. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  2035. cm.display.input.setUneditable(lineView.gutterBackground);
  2036. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2037. }
  2038. var markers = lineView.line.gutterMarkers;
  2039. if (cm.options.lineNumbers || markers) {
  2040. var wrap$1 = ensureLineWrapped(lineView);
  2041. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2042. gutterWrap.setAttribute("aria-hidden", "true");
  2043. cm.display.input.setUneditable(gutterWrap);
  2044. wrap$1.insertBefore(gutterWrap, lineView.text);
  2045. if (lineView.line.gutterClass)
  2046. { gutterWrap.className += " " + lineView.line.gutterClass; }
  2047. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) {
  2048. lineView.lineNumber = gutterWrap.appendChild(
  2049. elt("div", lineNumberFor(cm.options, lineN),
  2050. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2051. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px")));
  2052. }
  2053. if (markers) {
  2054. for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2055. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2056. if (found) {
  2057. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2058. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px")));
  2059. }
  2060. }
  2061. }
  2062. }
  2063. }
  2064. function updateLineWidgets(cm, lineView, dims) {
  2065. if (lineView.alignable) { lineView.alignable = null; }
  2066. var isWidget = classTest("CodeMirror-linewidget");
  2067. for (var node = lineView.node.firstChild, next = (void 0) ; node; node = next) {
  2068. next = node.nextSibling;
  2069. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2070. }
  2071. insertLineWidgets(cm, lineView, dims);
  2072. }
  2073. // Build a line's DOM representation from scratch
  2074. function buildLineElement(cm, lineView, lineN, dims) {
  2075. var built = getLineContent(cm, lineView);
  2076. lineView.text = lineView.node = built.pre;
  2077. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2078. if (built.textClass) { lineView.textClass = built.textClass; }
  2079. updateLineClasses(cm, lineView);
  2080. updateLineGutter(cm, lineView, lineN, dims);
  2081. insertLineWidgets(cm, lineView, dims);
  2082. return lineView.node
  2083. }
  2084. // A lineView may contain multiple logical lines (when merged by
  2085. // collapsed spans). The widgets for all of them need to be drawn.
  2086. function insertLineWidgets(cm, lineView, dims) {
  2087. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2088. if (lineView.rest) {
  2089. for (var i = 0; i < lineView.rest.length; i++)
  2090. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); }
  2091. }
  2092. }
  2093. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2094. if (!line.widgets) { return }
  2095. var wrap = ensureLineWrapped(lineView);
  2096. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2097. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2098. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2099. positionLineWidget(widget, node, lineView, dims);
  2100. cm.display.input.setUneditable(node);
  2101. if (allowAbove && widget.above)
  2102. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2103. else
  2104. { wrap.appendChild(node); }
  2105. signalLater(widget, "redraw");
  2106. }
  2107. }
  2108. function positionLineWidget(widget, node, lineView, dims) {
  2109. if (widget.noHScroll) {
  2110. (lineView.alignable || (lineView.alignable = [])).push(node);
  2111. var width = dims.wrapperWidth;
  2112. node.style.left = dims.fixedPos + "px";
  2113. if (!widget.coverGutter) {
  2114. width -= dims.gutterTotalWidth;
  2115. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2116. }
  2117. node.style.width = width + "px";
  2118. }
  2119. if (widget.coverGutter) {
  2120. node.style.zIndex = 5;
  2121. node.style.position = "relative";
  2122. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2123. }
  2124. }
  2125. function widgetHeight(widget) {
  2126. if (widget.height != null) { return widget.height }
  2127. var cm = widget.doc.cm;
  2128. if (!cm) { return 0 }
  2129. if (!contains(document.body, widget.node)) {
  2130. var parentStyle = "position: relative;";
  2131. if (widget.coverGutter)
  2132. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2133. if (widget.noHScroll)
  2134. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2135. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2136. }
  2137. return widget.height = widget.node.parentNode.offsetHeight
  2138. }
  2139. // Return true when the given mouse event happened in a widget
  2140. function eventInWidget(display, e) {
  2141. for (var n = e_target(e) ; n != display.wrapper; n = n.parentNode) {
  2142. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2143. (n.parentNode == display.sizer && n != display.mover))
  2144. { return true }
  2145. }
  2146. }
  2147. // POSITION MEASUREMENT
  2148. function paddingTop(display) { return display.lineSpace.offsetTop }
  2149. function paddingVert(display) { return display.mover.offsetHeight - display.lineSpace.offsetHeight }
  2150. function paddingH(display) {
  2151. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2152. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2153. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2154. var data = { left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight) };
  2155. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2156. return data
  2157. }
  2158. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2159. function displayWidth(cm) {
  2160. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2161. }
  2162. function displayHeight(cm) {
  2163. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2164. }
  2165. // Ensure the lineView.wrapping.heights array is populated. This is
  2166. // an array of bottom offsets for the lines that make up a drawn
  2167. // line. When lineWrapping is on, there might be more than one
  2168. // height.
  2169. function ensureLineHeights(cm, lineView, rect) {
  2170. var wrapping = cm.options.lineWrapping;
  2171. var curWidth = wrapping && displayWidth(cm);
  2172. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2173. var heights = lineView.measure.heights = [];
  2174. if (wrapping) {
  2175. lineView.measure.width = curWidth;
  2176. var rects = lineView.text.firstChild.getClientRects();
  2177. for (var i = 0; i < rects.length - 1; i++) {
  2178. var cur = rects[i], next = rects[i + 1];
  2179. if (Math.abs(cur.bottom - next.bottom) > 2)
  2180. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2181. }
  2182. }
  2183. heights.push(rect.bottom - rect.top);
  2184. }
  2185. }
  2186. // Find a line map (mapping character offsets to text nodes) and a
  2187. // measurement cache for the given line number. (A line view might
  2188. // contain multiple lines when collapsed ranges are present.)
  2189. function mapFromLineView(lineView, line, lineN) {
  2190. if (lineView.line == line)
  2191. { return { map: lineView.measure.map, cache: lineView.measure.cache } }
  2192. if (lineView.rest) {
  2193. for (var i = 0; i < lineView.rest.length; i++) {
  2194. if (lineView.rest[i] == line)
  2195. { return { map: lineView.measure.maps[i], cache: lineView.measure.caches[i] } }
  2196. }
  2197. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) {
  2198. if (lineNo(lineView.rest[i$1]) > lineN)
  2199. { return { map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true } }
  2200. }
  2201. }
  2202. }
  2203. // Render a line into the hidden node display.externalMeasured. Used
  2204. // when measurement is needed for a line that's not in the viewport.
  2205. function updateExternalMeasurement(cm, line) {
  2206. line = visualLine(line);
  2207. var lineN = lineNo(line);
  2208. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2209. view.lineN = lineN;
  2210. var built = view.built = buildLineContent(cm, view);
  2211. view.text = built.pre;
  2212. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2213. return view
  2214. }
  2215. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2216. // for a given character.
  2217. function measureChar(cm, line, ch, bias) {
  2218. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2219. }
  2220. // Find a line view that corresponds to the given line number.
  2221. function findViewForLine(cm, lineN) {
  2222. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2223. { return cm.display.view[findViewIndex(cm, lineN)] }
  2224. var ext = cm.display.externalMeasured;
  2225. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2226. { return ext }
  2227. }
  2228. // Measurement can be split in two steps, the set-up work that
  2229. // applies to the whole line, and the measurement of the actual
  2230. // character. Functions like coordsChar, that need to do a lot of
  2231. // measurements in a row, can thus ensure that the set-up work is
  2232. // only done once.
  2233. function prepareMeasureForLine(cm, line) {
  2234. var lineN = lineNo(line);
  2235. var view = findViewForLine(cm, lineN);
  2236. if (view && !view.text) {
  2237. view = null;
  2238. } else if (view && view.changes) {
  2239. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2240. cm.curOp.forceUpdate = true;
  2241. }
  2242. if (!view)
  2243. { view = updateExternalMeasurement(cm, line); }
  2244. var info = mapFromLineView(view, line, lineN);
  2245. return {
  2246. line: line, view: view, rect: null,
  2247. map: info.map, cache: info.cache, before: info.before,
  2248. hasHeights: false
  2249. }
  2250. }
  2251. // Given a prepared measurement object, measures the position of an
  2252. // actual character (or fetches it from the cache).
  2253. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2254. if (prepared.before) { ch = -1; }
  2255. var key = ch + (bias || ""), found;
  2256. if (prepared.cache.hasOwnProperty(key)) {
  2257. found = prepared.cache[key];
  2258. } else {
  2259. if (!prepared.rect)
  2260. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2261. if (!prepared.hasHeights) {
  2262. ensureLineHeights(cm, prepared.view, prepared.rect);
  2263. prepared.hasHeights = true;
  2264. }
  2265. found = measureCharInner(cm, prepared, ch, bias);
  2266. if (!found.bogus) { prepared.cache[key] = found; }
  2267. }
  2268. return {
  2269. left: found.left, right: found.right,
  2270. top: varHeight ? found.rtop : found.top,
  2271. bottom: varHeight ? found.rbottom : found.bottom
  2272. }
  2273. }
  2274. var nullRect = { left: 0, right: 0, top: 0, bottom: 0 };
  2275. function nodeAndOffsetInLineMap(map, ch, bias) {
  2276. var node, start, end, collapse, mStart, mEnd;
  2277. // First, search the line map for the text node corresponding to,
  2278. // or closest to, the target character.
  2279. for (var i = 0; i < map.length; i += 3) {
  2280. mStart = map[i];
  2281. mEnd = map[i + 1];
  2282. if (ch < mStart) {
  2283. start = 0; end = 1;
  2284. collapse = "left";
  2285. } else if (ch < mEnd) {
  2286. start = ch - mStart;
  2287. end = start + 1;
  2288. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2289. end = mEnd - mStart;
  2290. start = end - 1;
  2291. if (ch >= mEnd) { collapse = "right"; }
  2292. }
  2293. if (start != null) {
  2294. node = map[i + 2];
  2295. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2296. { collapse = bias; }
  2297. if (bias == "left" && start == 0) {
  2298. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2299. node = map[(i -= 3) + 2];
  2300. collapse = "left";
  2301. }
  2302. }
  2303. if (bias == "right" && start == mEnd - mStart) {
  2304. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2305. node = map[(i += 3) + 2];
  2306. collapse = "right";
  2307. }
  2308. }
  2309. break
  2310. }
  2311. }
  2312. return { node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd }
  2313. }
  2314. function getUsefulRect(rects, bias) {
  2315. var rect = nullRect;
  2316. if (bias == "left") {
  2317. for (var i = 0; i < rects.length; i++) {
  2318. if ((rect = rects[i]).left != rect.right) { break }
  2319. }
  2320. } else {
  2321. for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2322. if ((rect = rects[i$1]).left != rect.right) { break }
  2323. }
  2324. }
  2325. return rect
  2326. }
  2327. function measureCharInner(cm, prepared, ch, bias) {
  2328. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2329. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2330. var rect;
  2331. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2332. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2333. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2334. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2335. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2336. { rect = node.parentNode.getBoundingClientRect(); }
  2337. else
  2338. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2339. if (rect.left || rect.right || start == 0) { break }
  2340. end = start;
  2341. start = start - 1;
  2342. collapse = "right";
  2343. }
  2344. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2345. } else { // If it is a widget, simply get the box for the whole widget.
  2346. if (start > 0) { collapse = bias = "right"; }
  2347. var rects;
  2348. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2349. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2350. else
  2351. { rect = node.getBoundingClientRect(); }
  2352. }
  2353. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2354. var rSpan = node.parentNode.getClientRects()[0];
  2355. if (rSpan)
  2356. { rect = { left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom }; }
  2357. else
  2358. { rect = nullRect; }
  2359. }
  2360. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2361. var mid = (rtop + rbot) / 2;
  2362. var heights = prepared.view.measure.heights;
  2363. var i = 0;
  2364. for (; i < heights.length - 1; i++)
  2365. { if (mid < heights[i]) { break } }
  2366. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2367. var result = {
  2368. left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2369. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2370. top: top, bottom: bot
  2371. };
  2372. if (!rect.left && !rect.right) { result.bogus = true; }
  2373. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2374. return result
  2375. }
  2376. // Work around problem with bounding client rects on ranges being
  2377. // returned incorrectly when zoomed on IE10 and below.
  2378. function maybeUpdateRectForZooming(measure, rect) {
  2379. if (!window.screen || screen.logicalXDPI == null ||
  2380. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2381. { return rect }
  2382. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2383. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2384. return {
  2385. left: rect.left * scaleX, right: rect.right * scaleX,
  2386. top: rect.top * scaleY, bottom: rect.bottom * scaleY
  2387. }
  2388. }
  2389. function clearLineMeasurementCacheFor(lineView) {
  2390. if (lineView.measure) {
  2391. lineView.measure.cache = {};
  2392. lineView.measure.heights = null;
  2393. if (lineView.rest) {
  2394. for (var i = 0; i < lineView.rest.length; i++)
  2395. { lineView.measure.caches[i] = {}; }
  2396. }
  2397. }
  2398. }
  2399. function clearLineMeasurementCache(cm) {
  2400. cm.display.externalMeasure = null;
  2401. removeChildren(cm.display.lineMeasure);
  2402. for (var i = 0; i < cm.display.view.length; i++)
  2403. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2404. }
  2405. function clearCaches(cm) {
  2406. clearLineMeasurementCache(cm);
  2407. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2408. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2409. cm.display.lineNumChars = null;
  2410. }
  2411. function pageScrollX(doc) {
  2412. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2413. // which causes page_Offset and bounding client rects to use
  2414. // different reference viewports and invalidate our calculations.
  2415. if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }
  2416. return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft
  2417. }
  2418. function pageScrollY(doc) {
  2419. if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }
  2420. return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop
  2421. }
  2422. function widgetTopHeight(lineObj) {
  2423. var ref = visualLine(lineObj);
  2424. var widgets = ref.widgets;
  2425. var height = 0;
  2426. if (widgets) {
  2427. for (var i = 0; i < widgets.length; ++i) {
  2428. if (widgets[i].above)
  2429. { height += widgetHeight(widgets[i]); }
  2430. }
  2431. }
  2432. return height
  2433. }
  2434. // Converts a {top, bottom, left, right} box from line-local
  2435. // coordinates into another coordinate system. Context may be one of
  2436. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2437. // or "page".
  2438. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2439. if (!includeWidgets) {
  2440. var height = widgetTopHeight(lineObj);
  2441. rect.top += height; rect.bottom += height;
  2442. }
  2443. if (context == "line") { return rect }
  2444. if (!context) { context = "local"; }
  2445. var yOff = heightAtLine(lineObj);
  2446. if (context == "local") { yOff += paddingTop(cm.display); }
  2447. else { yOff -= cm.display.viewOffset; }
  2448. if (context == "page" || context == "window") {
  2449. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2450. yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm)));
  2451. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
  2452. rect.left += xOff; rect.right += xOff;
  2453. }
  2454. rect.top += yOff; rect.bottom += yOff;
  2455. return rect
  2456. }
  2457. // Coverts a box from "div" coords to another coordinate system.
  2458. // Context may be "window", "page", "div", or "local"./null.
  2459. function fromCoordSystem(cm, coords, context) {
  2460. if (context == "div") { return coords }
  2461. var left = coords.left, top = coords.top;
  2462. // First move into "page" coordinate system
  2463. if (context == "page") {
  2464. left -= pageScrollX(doc(cm));
  2465. top -= pageScrollY(doc(cm));
  2466. } else if (context == "local" || !context) {
  2467. var localBox = cm.display.sizer.getBoundingClientRect();
  2468. left += localBox.left;
  2469. top += localBox.top;
  2470. }
  2471. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2472. return { left: left - lineSpaceBox.left, top: top - lineSpaceBox.top }
  2473. }
  2474. function charCoords(cm, pos, context, lineObj, bias) {
  2475. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2476. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2477. }
  2478. // Returns a box for a given cursor position, which may have an
  2479. // 'other' property containing the position of the secondary cursor
  2480. // on a bidi boundary.
  2481. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2482. // and after `char - 1` in writing order of `char - 1`
  2483. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2484. // and before `char` in writing order of `char`
  2485. // Examples (upper-case letters are RTL, lower-case are LTR):
  2486. // Pos(0, 1, ...)
  2487. // before after
  2488. // ab a|b a|b
  2489. // aB a|B aB|
  2490. // Ab |Ab A|b
  2491. // AB B|A B|A
  2492. // Every position after the last character on a line is considered to stick
  2493. // to the last character on the line.
  2494. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2495. lineObj = lineObj || getLine(cm.doc, pos.line);
  2496. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2497. function get(ch, right) {
  2498. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2499. if (right) { m.left = m.right; } else { m.right = m.left; }
  2500. return intoCoordSystem(cm, lineObj, m, context)
  2501. }
  2502. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2503. if (ch >= lineObj.text.length) {
  2504. ch = lineObj.text.length;
  2505. sticky = "before";
  2506. } else if (ch <= 0) {
  2507. ch = 0;
  2508. sticky = "after";
  2509. }
  2510. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2511. function getBidi(ch, partPos, invert) {
  2512. var part = order[partPos], right = part.level == 1;
  2513. return get(invert ? ch - 1 : ch, right != invert)
  2514. }
  2515. var partPos = getBidiPartAt(order, ch, sticky);
  2516. var other = bidiOther;
  2517. var val = getBidi(ch, partPos, sticky == "before");
  2518. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2519. return val
  2520. }
  2521. // Used to cheaply estimate the coordinates for a position. Used for
  2522. // intermediate scroll updates.
  2523. function estimateCoords(cm, pos) {
  2524. var left = 0;
  2525. pos = clipPos(cm.doc, pos);
  2526. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2527. var lineObj = getLine(cm.doc, pos.line);
  2528. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2529. return { left: left, right: left, top: top, bottom: top + lineObj.height }
  2530. }
  2531. // Positions returned by coordsChar contain some extra information.
  2532. // xRel is the relative x position of the input coordinates compared
  2533. // to the found position (so xRel > 0 means the coordinates are to
  2534. // the right of the character position, for example). When outside
  2535. // is true, that means the coordinates lie outside the line's
  2536. // vertical range.
  2537. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2538. var pos = Pos(line, ch, sticky);
  2539. pos.xRel = xRel;
  2540. if (outside) { pos.outside = outside; }
  2541. return pos
  2542. }
  2543. // Compute the character position closest to the given coordinates.
  2544. // Input must be lineSpace-local ("div" coordinate system).
  2545. function coordsChar(cm, x, y) {
  2546. var doc = cm.doc;
  2547. y += cm.display.viewOffset;
  2548. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2549. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2550. if (lineN > last)
  2551. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2552. if (x < 0) { x = 0; }
  2553. var lineObj = getLine(doc, lineN);
  2554. for (; ;) {
  2555. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2556. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2557. if (!collapsed) { return found }
  2558. var rangeEnd = collapsed.find(1);
  2559. if (rangeEnd.line == lineN) { return rangeEnd }
  2560. lineObj = getLine(doc, lineN = rangeEnd.line);
  2561. }
  2562. }
  2563. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2564. y -= widgetTopHeight(lineObj);
  2565. var end = lineObj.text.length;
  2566. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2567. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2568. return { begin: begin, end: end }
  2569. }
  2570. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2571. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2572. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2573. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2574. }
  2575. // Returns true if the given side of a box is after the given
  2576. // coordinates, in top-to-bottom, left-to-right order.
  2577. function boxIsAfter(box, x, y, left) {
  2578. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2579. }
  2580. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2581. // Move y into line-local coordinate space
  2582. y -= heightAtLine(lineObj);
  2583. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2584. // When directly calling `measureCharPrepared`, we have to adjust
  2585. // for the widgets at this line.
  2586. var widgetHeight = widgetTopHeight(lineObj);
  2587. var begin = 0, end = lineObj.text.length, ltr = true;
  2588. var order = getOrder(lineObj, cm.doc.direction);
  2589. // If the line isn't plain left-to-right text, first figure out
  2590. // which bidi section the coordinates fall into.
  2591. if (order) {
  2592. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2593. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2594. ltr = part.level != 1;
  2595. // The awkward -1 offsets are needed because findFirst (called
  2596. // on these below) will treat its first bound as inclusive,
  2597. // second as exclusive, but we want to actually address the
  2598. // characters in the part's range
  2599. begin = ltr ? part.from : part.to - 1;
  2600. end = ltr ? part.to : part.from - 1;
  2601. }
  2602. // A binary search to find the first character whose bounding box
  2603. // starts after the coordinates. If we run across any whose box wrap
  2604. // the coordinates, store that.
  2605. var chAround = null, boxAround = null;
  2606. var ch = findFirst(function (ch) {
  2607. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2608. box.top += widgetHeight; box.bottom += widgetHeight;
  2609. if (!boxIsAfter(box, x, y, false)) { return false }
  2610. if (box.top <= y && box.left <= x) {
  2611. chAround = ch;
  2612. boxAround = box;
  2613. }
  2614. return true
  2615. }, begin, end);
  2616. var baseX, sticky, outside = false;
  2617. // If a box around the coordinates was found, use that
  2618. if (boxAround) {
  2619. // Distinguish coordinates nearer to the left or right side of the box
  2620. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2621. ch = chAround + (atStart ? 0 : 1);
  2622. sticky = atStart ? "after" : "before";
  2623. baseX = atLeft ? boxAround.left : boxAround.right;
  2624. } else {
  2625. // (Adjust for extended bound, if necessary.)
  2626. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2627. // To determine which side to associate with, get the box to the
  2628. // left of the character and compare it's vertical position to the
  2629. // coordinates
  2630. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2631. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2632. "after" : "before";
  2633. // Now get accurate coordinates for this place, in order to get a
  2634. // base X position
  2635. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2636. baseX = coords.left;
  2637. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2638. }
  2639. ch = skipExtendingChars(lineObj.text, ch, 1);
  2640. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2641. }
  2642. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2643. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2644. // situation, we can take this ordering to correspond to the visual
  2645. // ordering. This finds the first part whose end is after the given
  2646. // coordinates.
  2647. var index = findFirst(function (i) {
  2648. var part = order[i], ltr = part.level != 1;
  2649. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2650. "line", lineObj, preparedMeasure), x, y, true)
  2651. }, 0, order.length - 1);
  2652. var part = order[index];
  2653. // If this isn't the first part, the part's start is also after
  2654. // the coordinates, and the coordinates aren't on the same line as
  2655. // that start, move one part back.
  2656. if (index > 0) {
  2657. var ltr = part.level != 1;
  2658. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2659. "line", lineObj, preparedMeasure);
  2660. if (boxIsAfter(start, x, y, true) && start.top > y)
  2661. { part = order[index - 1]; }
  2662. }
  2663. return part
  2664. }
  2665. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2666. // In a wrapped line, rtl text on wrapping boundaries can do things
  2667. // that don't correspond to the ordering in our `order` array at
  2668. // all, so a binary search doesn't work, and we want to return a
  2669. // part that only spans one line so that the binary search in
  2670. // coordsCharInner is safe. As such, we first find the extent of the
  2671. // wrapped line, and then do a flat search in which we discard any
  2672. // spans that aren't on the line.
  2673. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2674. var begin = ref.begin;
  2675. var end = ref.end;
  2676. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2677. var part = null, closestDist = null;
  2678. for (var i = 0; i < order.length; i++) {
  2679. var p = order[i];
  2680. if (p.from >= end || p.to <= begin) { continue }
  2681. var ltr = p.level != 1;
  2682. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2683. // Weigh against spans ending before this, so that they are only
  2684. // picked if nothing ends after
  2685. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2686. if (!part || closestDist > dist) {
  2687. part = p;
  2688. closestDist = dist;
  2689. }
  2690. }
  2691. if (!part) { part = order[order.length - 1]; }
  2692. // Clip the part to the wrapped line.
  2693. if (part.from < begin) { part = { from: begin, to: part.to, level: part.level }; }
  2694. if (part.to > end) { part = { from: part.from, to: end, level: part.level }; }
  2695. return part
  2696. }
  2697. var measureText;
  2698. // Compute the default text height.
  2699. function textHeight(display) {
  2700. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2701. if (measureText == null) {
  2702. measureText = elt("pre", null, "CodeMirror-line-like");
  2703. // Measure a bunch of lines, for browsers that compute
  2704. // fractional heights.
  2705. for (var i = 0; i < 49; ++i) {
  2706. measureText.appendChild(document.createTextNode("x"));
  2707. measureText.appendChild(elt("br"));
  2708. }
  2709. measureText.appendChild(document.createTextNode("x"));
  2710. }
  2711. removeChildrenAndAdd(display.measure, measureText);
  2712. var height = measureText.offsetHeight / 50;
  2713. if (height > 3) { display.cachedTextHeight = height; }
  2714. removeChildren(display.measure);
  2715. return height || 1
  2716. }
  2717. // Compute the default character width.
  2718. function charWidth(display) {
  2719. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2720. var anchor = elt("span", "xxxxxxxxxx");
  2721. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2722. removeChildrenAndAdd(display.measure, pre);
  2723. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2724. if (width > 2) { display.cachedCharWidth = width; }
  2725. return width || 10
  2726. }
  2727. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2728. // view, so that we don't interleave reading and writing to the DOM.
  2729. function getDimensions(cm) {
  2730. var d = cm.display, left = {}, width = {};
  2731. var gutterLeft = d.gutters.clientLeft;
  2732. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2733. var id = cm.display.gutterSpecs[i].className;
  2734. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2735. width[id] = n.clientWidth;
  2736. }
  2737. return {
  2738. fixedPos: compensateForHScroll(d),
  2739. gutterTotalWidth: d.gutters.offsetWidth,
  2740. gutterLeft: left,
  2741. gutterWidth: width,
  2742. wrapperWidth: d.wrapper.clientWidth
  2743. }
  2744. }
  2745. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2746. // but using getBoundingClientRect to get a sub-pixel-accurate
  2747. // result.
  2748. function compensateForHScroll(display) {
  2749. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2750. }
  2751. // Returns a function that estimates the height of a line, to use as
  2752. // first approximation until the line becomes visible (and is thus
  2753. // properly measurable).
  2754. function estimateHeight(cm) {
  2755. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2756. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2757. return function (line) {
  2758. if (lineIsHidden(cm.doc, line)) { return 0 }
  2759. var widgetsHeight = 0;
  2760. if (line.widgets) {
  2761. for (var i = 0; i < line.widgets.length; i++) {
  2762. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2763. }
  2764. }
  2765. if (wrapping)
  2766. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2767. else
  2768. { return widgetsHeight + th }
  2769. }
  2770. }
  2771. function estimateLineHeights(cm) {
  2772. var doc = cm.doc, est = estimateHeight(cm);
  2773. doc.iter(function (line) {
  2774. var estHeight = est(line);
  2775. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2776. });
  2777. }
  2778. // Given a mouse event, find the corresponding position. If liberal
  2779. // is false, it checks whether a gutter or scrollbar was clicked,
  2780. // and returns null if it was. forRect is used by rectangular
  2781. // selections, and tries to estimate a character position even for
  2782. // coordinates beyond the right of the text.
  2783. function posFromMouse(cm, e, liberal, forRect) {
  2784. var display = cm.display;
  2785. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2786. var x, y, space = display.lineSpace.getBoundingClientRect();
  2787. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2788. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2789. catch (e$1) { return null }
  2790. var coords = coordsChar(cm, x, y), line;
  2791. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2792. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2793. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2794. }
  2795. return coords
  2796. }
  2797. // Find the view element corresponding to a given line. Return null
  2798. // when the line isn't visible.
  2799. function findViewIndex(cm, n) {
  2800. if (n >= cm.display.viewTo) { return null }
  2801. n -= cm.display.viewFrom;
  2802. if (n < 0) { return null }
  2803. var view = cm.display.view;
  2804. for (var i = 0; i < view.length; i++) {
  2805. n -= view[i].size;
  2806. if (n < 0) { return i }
  2807. }
  2808. }
  2809. // Updates the display.view data structure for a given change to the
  2810. // document. From and to are in pre-change coordinates. Lendiff is
  2811. // the amount of lines added or subtracted by the change. This is
  2812. // used for changes that span multiple lines, or change the way
  2813. // lines are divided into visual lines. regLineChange (below)
  2814. // registers single-line changes.
  2815. function regChange(cm, from, to, lendiff) {
  2816. if (from == null) { from = cm.doc.first; }
  2817. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2818. if (!lendiff) { lendiff = 0; }
  2819. var display = cm.display;
  2820. if (lendiff && to < display.viewTo &&
  2821. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2822. { display.updateLineNumbers = from; }
  2823. cm.curOp.viewChanged = true;
  2824. if (from >= display.viewTo) { // Change after
  2825. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2826. { resetView(cm); }
  2827. } else if (to <= display.viewFrom) { // Change before
  2828. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2829. resetView(cm);
  2830. } else {
  2831. display.viewFrom += lendiff;
  2832. display.viewTo += lendiff;
  2833. }
  2834. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2835. resetView(cm);
  2836. } else if (from <= display.viewFrom) { // Top overlap
  2837. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2838. if (cut) {
  2839. display.view = display.view.slice(cut.index);
  2840. display.viewFrom = cut.lineN;
  2841. display.viewTo += lendiff;
  2842. } else {
  2843. resetView(cm);
  2844. }
  2845. } else if (to >= display.viewTo) { // Bottom overlap
  2846. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2847. if (cut$1) {
  2848. display.view = display.view.slice(0, cut$1.index);
  2849. display.viewTo = cut$1.lineN;
  2850. } else {
  2851. resetView(cm);
  2852. }
  2853. } else { // Gap in the middle
  2854. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2855. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2856. if (cutTop && cutBot) {
  2857. display.view = display.view.slice(0, cutTop.index)
  2858. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2859. .concat(display.view.slice(cutBot.index));
  2860. display.viewTo += lendiff;
  2861. } else {
  2862. resetView(cm);
  2863. }
  2864. }
  2865. var ext = display.externalMeasured;
  2866. if (ext) {
  2867. if (to < ext.lineN)
  2868. { ext.lineN += lendiff; }
  2869. else if (from < ext.lineN + ext.size)
  2870. { display.externalMeasured = null; }
  2871. }
  2872. }
  2873. // Register a change to a single line. Type must be one of "text",
  2874. // "gutter", "class", "widget"
  2875. function regLineChange(cm, line, type) {
  2876. cm.curOp.viewChanged = true;
  2877. var display = cm.display, ext = cm.display.externalMeasured;
  2878. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2879. { display.externalMeasured = null; }
  2880. if (line < display.viewFrom || line >= display.viewTo) { return }
  2881. var lineView = display.view[findViewIndex(cm, line)];
  2882. if (lineView.node == null) { return }
  2883. var arr = lineView.changes || (lineView.changes = []);
  2884. if (indexOf(arr, type) == -1) { arr.push(type); }
  2885. }
  2886. // Clear the view.
  2887. function resetView(cm) {
  2888. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2889. cm.display.view = [];
  2890. cm.display.viewOffset = 0;
  2891. }
  2892. function viewCuttingPoint(cm, oldN, newN, dir) {
  2893. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2894. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2895. { return { index: index, lineN: newN } }
  2896. var n = cm.display.viewFrom;
  2897. for (var i = 0; i < index; i++)
  2898. { n += view[i].size; }
  2899. if (n != oldN) {
  2900. if (dir > 0) {
  2901. if (index == view.length - 1) { return null }
  2902. diff = (n + view[index].size) - oldN;
  2903. index++;
  2904. } else {
  2905. diff = n - oldN;
  2906. }
  2907. oldN += diff; newN += diff;
  2908. }
  2909. while (visualLineNo(cm.doc, newN) != newN) {
  2910. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2911. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2912. index += dir;
  2913. }
  2914. return { index: index, lineN: newN }
  2915. }
  2916. // Force the view to cover a given range, adding empty view element
  2917. // or clipping off existing ones as needed.
  2918. function adjustView(cm, from, to) {
  2919. var display = cm.display, view = display.view;
  2920. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2921. display.view = buildViewArray(cm, from, to);
  2922. display.viewFrom = from;
  2923. } else {
  2924. if (display.viewFrom > from)
  2925. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2926. else if (display.viewFrom < from)
  2927. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2928. display.viewFrom = from;
  2929. if (display.viewTo < to)
  2930. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2931. else if (display.viewTo > to)
  2932. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2933. }
  2934. display.viewTo = to;
  2935. }
  2936. // Count the number of lines in the view whose DOM representation is
  2937. // out of date (or nonexistent).
  2938. function countDirtyView(cm) {
  2939. var view = cm.display.view, dirty = 0;
  2940. for (var i = 0; i < view.length; i++) {
  2941. var lineView = view[i];
  2942. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2943. }
  2944. return dirty
  2945. }
  2946. function updateSelection(cm) {
  2947. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2948. }
  2949. function prepareSelection(cm, primary) {
  2950. if (primary === void 0) primary = true;
  2951. var doc = cm.doc, result = {};
  2952. var curFragment = result.cursors = document.createDocumentFragment();
  2953. var selFragment = result.selection = document.createDocumentFragment();
  2954. var customCursor = cm.options.$customCursor;
  2955. if (customCursor) { primary = true; }
  2956. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2957. if (!primary && i == doc.sel.primIndex) { continue }
  2958. var range = doc.sel.ranges[i];
  2959. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2960. var collapsed = range.empty();
  2961. if (customCursor) {
  2962. var head = customCursor(cm, range);
  2963. if (head) { drawSelectionCursor(cm, head, curFragment); }
  2964. } else if (collapsed || cm.options.showCursorWhenSelecting) {
  2965. drawSelectionCursor(cm, range.head, curFragment);
  2966. }
  2967. if (!collapsed)
  2968. { drawSelectionRange(cm, range, selFragment); }
  2969. }
  2970. return result
  2971. }
  2972. // Draws a cursor for the given range
  2973. function drawSelectionCursor(cm, head, output) {
  2974. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2975. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2976. cursor.style.left = pos.left + "px";
  2977. cursor.style.top = pos.top + "px";
  2978. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2979. if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
  2980. var charPos = charCoords(cm, head, "div", null, null);
  2981. var width = charPos.right - charPos.left;
  2982. cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
  2983. }
  2984. if (pos.other) {
  2985. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2986. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2987. otherCursor.style.display = "";
  2988. otherCursor.style.left = pos.other.left + "px";
  2989. otherCursor.style.top = pos.other.top + "px";
  2990. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2991. }
  2992. }
  2993. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2994. // Draws the given range as a highlighted selection
  2995. function drawSelectionRange(cm, range, output) {
  2996. var display = cm.display, doc = cm.doc;
  2997. var fragment = document.createDocumentFragment();
  2998. var padding = paddingH(cm.display), leftSide = padding.left;
  2999. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  3000. var docLTR = doc.direction == "ltr";
  3001. function add(left, top, width, bottom) {
  3002. if (top < 0) { top = 0; }
  3003. top = Math.round(top);
  3004. bottom = Math.round(bottom);
  3005. fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
  3006. }
  3007. function drawForLine(line, fromArg, toArg) {
  3008. var lineObj = getLine(doc, line);
  3009. var lineLen = lineObj.text.length;
  3010. var start, end;
  3011. function coords(ch, bias) {
  3012. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  3013. }
  3014. function wrapX(pos, dir, side) {
  3015. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  3016. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  3017. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  3018. return coords(ch, prop)[prop]
  3019. }
  3020. var order = getOrder(lineObj, doc.direction);
  3021. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  3022. var ltr = dir == "ltr";
  3023. var fromPos = coords(from, ltr ? "left" : "right");
  3024. var toPos = coords(to - 1, ltr ? "right" : "left");
  3025. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  3026. var first = i == 0, last = !order || i == order.length - 1;
  3027. if (toPos.top - fromPos.top <= 3) { // Single line
  3028. var openLeft = (docLTR ? openStart : openEnd) && first;
  3029. var openRight = (docLTR ? openEnd : openStart) && last;
  3030. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  3031. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  3032. add(left, fromPos.top, right - left, fromPos.bottom);
  3033. } else { // Multiple lines
  3034. var topLeft, topRight, botLeft, botRight;
  3035. if (ltr) {
  3036. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  3037. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  3038. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  3039. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  3040. } else {
  3041. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  3042. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  3043. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  3044. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  3045. }
  3046. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  3047. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  3048. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  3049. }
  3050. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  3051. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  3052. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  3053. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  3054. });
  3055. return { start: start, end: end }
  3056. }
  3057. var sFrom = range.from(), sTo = range.to();
  3058. if (sFrom.line == sTo.line) {
  3059. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  3060. } else {
  3061. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  3062. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  3063. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  3064. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  3065. if (singleVLine) {
  3066. if (leftEnd.top < rightStart.top - 2) {
  3067. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  3068. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  3069. } else {
  3070. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  3071. }
  3072. }
  3073. if (leftEnd.bottom < rightStart.top)
  3074. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  3075. }
  3076. output.appendChild(fragment);
  3077. }
  3078. // Cursor-blinking
  3079. function restartBlink(cm) {
  3080. if (!cm.state.focused) { return }
  3081. var display = cm.display;
  3082. clearInterval(display.blinker);
  3083. var on = true;
  3084. display.cursorDiv.style.visibility = "";
  3085. if (cm.options.cursorBlinkRate > 0) {
  3086. display.blinker = setInterval(function () {
  3087. if (!cm.hasFocus()) { onBlur(cm); }
  3088. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  3089. }, cm.options.cursorBlinkRate);
  3090. }
  3091. else if (cm.options.cursorBlinkRate < 0)
  3092. { display.cursorDiv.style.visibility = "hidden"; }
  3093. }
  3094. function ensureFocus(cm) {
  3095. if (!cm.hasFocus()) {
  3096. cm.display.input.focus();
  3097. if (!cm.state.focused) { onFocus(cm); }
  3098. }
  3099. }
  3100. function delayBlurEvent(cm) {
  3101. cm.state.delayingBlurEvent = true;
  3102. setTimeout(function () {
  3103. if (cm.state.delayingBlurEvent) {
  3104. cm.state.delayingBlurEvent = false;
  3105. if (cm.state.focused) { onBlur(cm); }
  3106. }
  3107. }, 100);
  3108. }
  3109. function onFocus(cm, e) {
  3110. if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  3111. if (cm.options.readOnly == "nocursor") { return }
  3112. if (!cm.state.focused) {
  3113. signal(cm, "focus", cm, e);
  3114. cm.state.focused = true;
  3115. addClass(cm.display.wrapper, "CodeMirror-focused");
  3116. // This test prevents this from firing when a context
  3117. // menu is closed (since the input reset would kill the
  3118. // select-all detection hack)
  3119. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3120. cm.display.input.reset();
  3121. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3122. }
  3123. cm.display.input.receivedFocus();
  3124. }
  3125. restartBlink(cm);
  3126. }
  3127. function onBlur(cm, e) {
  3128. if (cm.state.delayingBlurEvent) { return }
  3129. if (cm.state.focused) {
  3130. signal(cm, "blur", cm, e);
  3131. cm.state.focused = false;
  3132. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3133. }
  3134. clearInterval(cm.display.blinker);
  3135. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3136. }
  3137. // Read the actual heights of the rendered lines, and update their
  3138. // stored heights to match.
  3139. function updateHeightsInViewport(cm) {
  3140. var display = cm.display;
  3141. var prevBottom = display.lineDiv.offsetTop;
  3142. var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
  3143. var oldHeight = display.lineDiv.getBoundingClientRect().top;
  3144. var mustScroll = 0;
  3145. for (var i = 0; i < display.view.length; i++) {
  3146. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3147. var height = (void 0), width = 0;
  3148. if (cur.hidden) { continue }
  3149. oldHeight += cur.line.height;
  3150. if (ie && ie_version < 8) {
  3151. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3152. height = bot - prevBottom;
  3153. prevBottom = bot;
  3154. } else {
  3155. var box = cur.node.getBoundingClientRect();
  3156. height = box.bottom - box.top;
  3157. // Check that lines don't extend past the right of the current
  3158. // editor width
  3159. if (!wrapping && cur.text.firstChild)
  3160. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3161. }
  3162. var diff = cur.line.height - height;
  3163. if (diff > .005 || diff < -.005) {
  3164. if (oldHeight < viewTop) { mustScroll -= diff; }
  3165. updateLineHeight(cur.line, height);
  3166. updateWidgetHeight(cur.line);
  3167. if (cur.rest) {
  3168. for (var j = 0; j < cur.rest.length; j++)
  3169. { updateWidgetHeight(cur.rest[j]); }
  3170. }
  3171. }
  3172. if (width > cm.display.sizerWidth) {
  3173. var chWidth = Math.ceil(width / charWidth(cm.display));
  3174. if (chWidth > cm.display.maxLineLength) {
  3175. cm.display.maxLineLength = chWidth;
  3176. cm.display.maxLine = cur.line;
  3177. cm.display.maxLineChanged = true;
  3178. }
  3179. }
  3180. }
  3181. if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
  3182. }
  3183. // Read and store the height of line widgets associated with the
  3184. // given line.
  3185. function updateWidgetHeight(line) {
  3186. if (line.widgets) {
  3187. for (var i = 0; i < line.widgets.length; ++i) {
  3188. var w = line.widgets[i], parent = w.node.parentNode;
  3189. if (parent) { w.height = parent.offsetHeight; }
  3190. }
  3191. }
  3192. }
  3193. // Compute the lines that are visible in a given viewport (defaults
  3194. // the the current scroll position). viewport may contain top,
  3195. // height, and ensure (see op.scrollToPos) properties.
  3196. function visibleLines(display, doc, viewport) {
  3197. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3198. top = Math.floor(top - paddingTop(display));
  3199. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3200. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3201. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3202. // forces those lines into the viewport (if possible).
  3203. if (viewport && viewport.ensure) {
  3204. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3205. if (ensureFrom < from) {
  3206. from = ensureFrom;
  3207. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3208. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3209. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3210. to = ensureTo;
  3211. }
  3212. }
  3213. return { from: from, to: Math.max(to, from + 1) }
  3214. }
  3215. // SCROLLING THINGS INTO VIEW
  3216. // If an editor sits on the top or bottom of the window, partially
  3217. // scrolled out of view, this ensures that the cursor is visible.
  3218. function maybeScrollWindow(cm, rect) {
  3219. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3220. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3221. var doc = display.wrapper.ownerDocument;
  3222. if (rect.top + box.top < 0) { doScroll = true; }
  3223. else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; }
  3224. if (doScroll != null && !phantom) {
  3225. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
  3226. cm.display.lineSpace.appendChild(scrollNode);
  3227. scrollNode.scrollIntoView(doScroll);
  3228. cm.display.lineSpace.removeChild(scrollNode);
  3229. }
  3230. }
  3231. // Scroll a given position into view (immediately), verifying that
  3232. // it actually became visible (as line heights are accurately
  3233. // measured, the position of something may 'drift' during drawing).
  3234. function scrollPosIntoView(cm, pos, end, margin) {
  3235. if (margin == null) { margin = 0; }
  3236. var rect;
  3237. if (!cm.options.lineWrapping && pos == end) {
  3238. // Set pos and end to the cursor positions around the character pos sticks to
  3239. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3240. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3241. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3242. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3243. }
  3244. for (var limit = 0; limit < 5; limit++) {
  3245. var changed = false;
  3246. var coords = cursorCoords(cm, pos);
  3247. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3248. rect = {
  3249. left: Math.min(coords.left, endCoords.left),
  3250. top: Math.min(coords.top, endCoords.top) - margin,
  3251. right: Math.max(coords.left, endCoords.left),
  3252. bottom: Math.max(coords.bottom, endCoords.bottom) + margin
  3253. };
  3254. var scrollPos = calculateScrollPos(cm, rect);
  3255. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3256. if (scrollPos.scrollTop != null) {
  3257. updateScrollTop(cm, scrollPos.scrollTop);
  3258. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3259. }
  3260. if (scrollPos.scrollLeft != null) {
  3261. setScrollLeft(cm, scrollPos.scrollLeft);
  3262. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3263. }
  3264. if (!changed) { break }
  3265. }
  3266. return rect
  3267. }
  3268. // Scroll a given set of coordinates into view (immediately).
  3269. function scrollIntoView(cm, rect) {
  3270. var scrollPos = calculateScrollPos(cm, rect);
  3271. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3272. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3273. }
  3274. // Calculate a new scroll position needed to scroll the given
  3275. // rectangle into view. Returns an object with scrollTop and
  3276. // scrollLeft properties. When these are undefined, the
  3277. // vertical/horizontal position does not need to be adjusted.
  3278. function calculateScrollPos(cm, rect) {
  3279. var display = cm.display, snapMargin = textHeight(cm.display);
  3280. if (rect.top < 0) { rect.top = 0; }
  3281. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3282. var screen = displayHeight(cm), result = {};
  3283. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3284. var docBottom = cm.doc.height + paddingVert(display);
  3285. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3286. if (rect.top < screentop) {
  3287. result.scrollTop = atTop ? 0 : rect.top;
  3288. } else if (rect.bottom > screentop + screen) {
  3289. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3290. if (newTop != screentop) { result.scrollTop = newTop; }
  3291. }
  3292. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  3293. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  3294. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  3295. var tooWide = rect.right - rect.left > screenw;
  3296. if (tooWide) { rect.right = rect.left + screenw; }
  3297. if (rect.left < 10)
  3298. { result.scrollLeft = 0; }
  3299. else if (rect.left < screenleft)
  3300. { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  3301. else if (rect.right > screenw + screenleft - 3)
  3302. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3303. return result
  3304. }
  3305. // Store a relative adjustment to the scroll position in the current
  3306. // operation (to be applied when the operation finishes).
  3307. function addToScrollTop(cm, top) {
  3308. if (top == null) { return }
  3309. resolveScrollToPos(cm);
  3310. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3311. }
  3312. // Make sure that at the end of the operation the current cursor is
  3313. // shown.
  3314. function ensureCursorVisible(cm) {
  3315. resolveScrollToPos(cm);
  3316. var cur = cm.getCursor();
  3317. cm.curOp.scrollToPos = { from: cur, to: cur, margin: cm.options.cursorScrollMargin };
  3318. }
  3319. function scrollToCoords(cm, x, y) {
  3320. if (x != null || y != null) { resolveScrollToPos(cm); }
  3321. if (x != null) { cm.curOp.scrollLeft = x; }
  3322. if (y != null) { cm.curOp.scrollTop = y; }
  3323. }
  3324. function scrollToRange(cm, range) {
  3325. resolveScrollToPos(cm);
  3326. cm.curOp.scrollToPos = range;
  3327. }
  3328. // When an operation has its scrollToPos property set, and another
  3329. // scroll action is applied before the end of the operation, this
  3330. // 'simulates' scrolling that position into view in a cheap way, so
  3331. // that the effect of intermediate scroll commands is not ignored.
  3332. function resolveScrollToPos(cm) {
  3333. var range = cm.curOp.scrollToPos;
  3334. if (range) {
  3335. cm.curOp.scrollToPos = null;
  3336. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3337. scrollToCoordsRange(cm, from, to, range.margin);
  3338. }
  3339. }
  3340. function scrollToCoordsRange(cm, from, to, margin) {
  3341. var sPos = calculateScrollPos(cm, {
  3342. left: Math.min(from.left, to.left),
  3343. top: Math.min(from.top, to.top) - margin,
  3344. right: Math.max(from.right, to.right),
  3345. bottom: Math.max(from.bottom, to.bottom) + margin
  3346. });
  3347. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3348. }
  3349. // Sync the scrollable area and scrollbars, ensure the viewport
  3350. // covers the visible area.
  3351. function updateScrollTop(cm, val) {
  3352. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3353. if (!gecko) { updateDisplaySimple(cm, { top: val }); }
  3354. setScrollTop(cm, val, true);
  3355. if (gecko) { updateDisplaySimple(cm); }
  3356. startWorker(cm, 100);
  3357. }
  3358. function setScrollTop(cm, val, forceScroll) {
  3359. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3360. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3361. cm.doc.scrollTop = val;
  3362. cm.display.scrollbars.setScrollTop(val);
  3363. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3364. }
  3365. // Sync scroller and scrollbar, ensure the gutter elements are
  3366. // aligned.
  3367. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3368. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3369. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3370. cm.doc.scrollLeft = val;
  3371. alignHorizontally(cm);
  3372. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3373. cm.display.scrollbars.setScrollLeft(val);
  3374. }
  3375. // SCROLLBARS
  3376. // Prepare DOM reads needed to update the scrollbars. Done in one
  3377. // shot to minimize update/measure roundtrips.
  3378. function measureForScrollbars(cm) {
  3379. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3380. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3381. return {
  3382. clientHeight: d.scroller.clientHeight,
  3383. viewHeight: d.wrapper.clientHeight,
  3384. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3385. viewWidth: d.wrapper.clientWidth,
  3386. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3387. docHeight: docH,
  3388. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3389. nativeBarWidth: d.nativeBarWidth,
  3390. gutterWidth: gutterW
  3391. }
  3392. }
  3393. var NativeScrollbars = function (place, scroll, cm) {
  3394. this.cm = cm;
  3395. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3396. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3397. vert.tabIndex = horiz.tabIndex = -1;
  3398. place(vert); place(horiz);
  3399. on(vert, "scroll", function () {
  3400. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3401. });
  3402. on(horiz, "scroll", function () {
  3403. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3404. });
  3405. this.checkedZeroWidth = false;
  3406. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3407. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3408. };
  3409. NativeScrollbars.prototype.update = function (measure) {
  3410. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3411. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3412. var sWidth = measure.nativeBarWidth;
  3413. if (needsV) {
  3414. this.vert.style.display = "block";
  3415. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3416. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3417. // A bug in IE8 can cause this value to be negative, so guard it.
  3418. this.vert.firstChild.style.height =
  3419. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3420. } else {
  3421. this.vert.scrollTop = 0;
  3422. this.vert.style.display = "";
  3423. this.vert.firstChild.style.height = "0";
  3424. }
  3425. if (needsH) {
  3426. this.horiz.style.display = "block";
  3427. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3428. this.horiz.style.left = measure.barLeft + "px";
  3429. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3430. this.horiz.firstChild.style.width =
  3431. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3432. } else {
  3433. this.horiz.style.display = "";
  3434. this.horiz.firstChild.style.width = "0";
  3435. }
  3436. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3437. if (sWidth == 0) { this.zeroWidthHack(); }
  3438. this.checkedZeroWidth = true;
  3439. }
  3440. return { right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0 }
  3441. };
  3442. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3443. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3444. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3445. };
  3446. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3447. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3448. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3449. };
  3450. NativeScrollbars.prototype.zeroWidthHack = function () {
  3451. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3452. this.horiz.style.height = this.vert.style.width = w;
  3453. this.horiz.style.visibility = this.vert.style.visibility = "hidden";
  3454. this.disableHoriz = new Delayed;
  3455. this.disableVert = new Delayed;
  3456. };
  3457. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3458. bar.style.visibility = "";
  3459. function maybeDisable() {
  3460. // To find out whether the scrollbar is still visible, we
  3461. // check whether the element under the pixel in the bottom
  3462. // right corner of the scrollbar box is the scrollbar box
  3463. // itself (when the bar is still visible) or its filler child
  3464. // (when the bar is hidden). If it is still visible, we keep
  3465. // it enabled, if it's hidden, we disable pointer events.
  3466. var box = bar.getBoundingClientRect();
  3467. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3468. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3469. if (elt != bar) { bar.style.visibility = "hidden"; }
  3470. else { delay.set(1000, maybeDisable); }
  3471. }
  3472. delay.set(1000, maybeDisable);
  3473. };
  3474. NativeScrollbars.prototype.clear = function () {
  3475. var parent = this.horiz.parentNode;
  3476. parent.removeChild(this.horiz);
  3477. parent.removeChild(this.vert);
  3478. };
  3479. var NullScrollbars = function () { };
  3480. NullScrollbars.prototype.update = function () { return { bottom: 0, right: 0 } };
  3481. NullScrollbars.prototype.setScrollLeft = function () { };
  3482. NullScrollbars.prototype.setScrollTop = function () { };
  3483. NullScrollbars.prototype.clear = function () { };
  3484. function updateScrollbars(cm, measure) {
  3485. if (!measure) { measure = measureForScrollbars(cm); }
  3486. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3487. updateScrollbarsInner(cm, measure);
  3488. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3489. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3490. { updateHeightsInViewport(cm); }
  3491. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3492. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3493. }
  3494. }
  3495. // Re-synchronize the fake scrollbars with the actual size of the
  3496. // content.
  3497. function updateScrollbarsInner(cm, measure) {
  3498. var d = cm.display;
  3499. var sizes = d.scrollbars.update(measure);
  3500. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3501. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3502. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3503. if (sizes.right && sizes.bottom) {
  3504. d.scrollbarFiller.style.display = "block";
  3505. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3506. d.scrollbarFiller.style.width = sizes.right + "px";
  3507. } else { d.scrollbarFiller.style.display = ""; }
  3508. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3509. d.gutterFiller.style.display = "block";
  3510. d.gutterFiller.style.height = sizes.bottom + "px";
  3511. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3512. } else { d.gutterFiller.style.display = ""; }
  3513. }
  3514. var scrollbarModel = { "native": NativeScrollbars, "null": NullScrollbars };
  3515. function initScrollbars(cm) {
  3516. if (cm.display.scrollbars) {
  3517. cm.display.scrollbars.clear();
  3518. if (cm.display.scrollbars.addClass)
  3519. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3520. }
  3521. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3522. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3523. // Prevent clicks in the scrollbars from killing focus
  3524. on(node, "mousedown", function () {
  3525. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3526. });
  3527. node.setAttribute("cm-not-content", "true");
  3528. }, function (pos, axis) {
  3529. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3530. else { updateScrollTop(cm, pos); }
  3531. }, cm);
  3532. if (cm.display.scrollbars.addClass)
  3533. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3534. }
  3535. // Operations are used to wrap a series of changes to the editor
  3536. // state in such a way that each change won't have to update the
  3537. // cursor and display (which would be awkward, slow, and
  3538. // error-prone). Instead, display updates are batched and then all
  3539. // combined and executed at once.
  3540. var nextOpId = 0;
  3541. // Start a new operation.
  3542. function startOperation(cm) {
  3543. cm.curOp = {
  3544. cm: cm,
  3545. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3546. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3547. forceUpdate: false, // Used to force a redraw
  3548. updateInput: 0, // Whether to reset the input textarea
  3549. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3550. changeObjs: null, // Accumulated changes, for firing change events
  3551. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3552. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3553. selectionChanged: false, // Whether the selection needs to be redrawn
  3554. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3555. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3556. scrollToPos: null, // Used to scroll to a specific position
  3557. focus: false,
  3558. id: ++nextOpId, // Unique ID
  3559. markArrays: null // Used by addMarkedSpan
  3560. };
  3561. pushOperation(cm.curOp);
  3562. }
  3563. // Finish an operation, updating the display and signalling delayed events
  3564. function endOperation(cm) {
  3565. var op = cm.curOp;
  3566. if (op) {
  3567. finishOperation(op, function (group) {
  3568. for (var i = 0; i < group.ops.length; i++)
  3569. { group.ops[i].cm.curOp = null; }
  3570. endOperations(group);
  3571. });
  3572. }
  3573. }
  3574. // The DOM updates done when an operation finishes are batched so
  3575. // that the minimum number of relayouts are required.
  3576. function endOperations(group) {
  3577. var ops = group.ops;
  3578. for (var i = 0; i < ops.length; i++) // Read DOM
  3579. { endOperation_R1(ops[i]); }
  3580. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3581. { endOperation_W1(ops[i$1]); }
  3582. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3583. { endOperation_R2(ops[i$2]); }
  3584. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3585. { endOperation_W2(ops[i$3]); }
  3586. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3587. { endOperation_finish(ops[i$4]); }
  3588. }
  3589. function endOperation_R1(op) {
  3590. var cm = op.cm, display = cm.display;
  3591. maybeClipScrollbars(cm);
  3592. if (op.updateMaxLine) { findMaxLine(cm); }
  3593. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3594. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3595. op.scrollToPos.to.line >= display.viewTo) ||
  3596. display.maxLineChanged && cm.options.lineWrapping;
  3597. op.update = op.mustUpdate &&
  3598. new DisplayUpdate(cm, op.mustUpdate && { top: op.scrollTop, ensure: op.scrollToPos }, op.forceUpdate);
  3599. }
  3600. function endOperation_W1(op) {
  3601. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3602. }
  3603. function endOperation_R2(op) {
  3604. var cm = op.cm, display = cm.display;
  3605. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3606. op.barMeasure = measureForScrollbars(cm);
  3607. // If the max line changed since it was last measured, measure it,
  3608. // and ensure the document's width matches it.
  3609. // updateDisplay_W2 will use these properties to do the actual resizing
  3610. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3611. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3612. cm.display.sizerWidth = op.adjustWidthTo;
  3613. op.barMeasure.scrollWidth =
  3614. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3615. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3616. }
  3617. if (op.updatedDisplay || op.selectionChanged)
  3618. { op.preparedSelection = display.input.prepareSelection(); }
  3619. }
  3620. function endOperation_W2(op) {
  3621. var cm = op.cm;
  3622. if (op.adjustWidthTo != null) {
  3623. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3624. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3625. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3626. cm.display.maxLineChanged = false;
  3627. }
  3628. var takeFocus = op.focus && op.focus == activeElt(doc(cm));
  3629. if (op.preparedSelection)
  3630. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3631. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3632. { updateScrollbars(cm, op.barMeasure); }
  3633. if (op.updatedDisplay)
  3634. { setDocumentHeight(cm, op.barMeasure); }
  3635. if (op.selectionChanged) { restartBlink(cm); }
  3636. if (cm.state.focused && op.updateInput)
  3637. { cm.display.input.reset(op.typing); }
  3638. if (takeFocus) { ensureFocus(op.cm); }
  3639. }
  3640. function endOperation_finish(op) {
  3641. var cm = op.cm, display = cm.display, doc = cm.doc;
  3642. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3643. // Abort mouse wheel delta measurement, when scrolling explicitly
  3644. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3645. { display.wheelStartX = display.wheelStartY = null; }
  3646. // Propagate the scroll position to the actual DOM scroller
  3647. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3648. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3649. // If we need to scroll a specific position into view, do so.
  3650. if (op.scrollToPos) {
  3651. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3652. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3653. maybeScrollWindow(cm, rect);
  3654. }
  3655. // Fire events for markers that are hidden/unidden by editing or
  3656. // undoing
  3657. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3658. if (hidden) {
  3659. for (var i = 0; i < hidden.length; ++i)
  3660. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } }
  3661. }
  3662. if (unhidden) {
  3663. for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3664. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } }
  3665. }
  3666. if (display.wrapper.offsetHeight)
  3667. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3668. // Fire change events, and delayed event handlers
  3669. if (op.changeObjs)
  3670. { signal(cm, "changes", cm, op.changeObjs); }
  3671. if (op.update)
  3672. { op.update.finish(); }
  3673. }
  3674. // Run the given function in an operation
  3675. function runInOp(cm, f) {
  3676. if (cm.curOp) { return f() }
  3677. startOperation(cm);
  3678. try { return f() }
  3679. finally { endOperation(cm); }
  3680. }
  3681. // Wraps a function in an operation. Returns the wrapped function.
  3682. function operation(cm, f) {
  3683. return function () {
  3684. if (cm.curOp) { return f.apply(cm, arguments) }
  3685. startOperation(cm);
  3686. try { return f.apply(cm, arguments) }
  3687. finally { endOperation(cm); }
  3688. }
  3689. }
  3690. // Used to add methods to editor and doc instances, wrapping them in
  3691. // operations.
  3692. function methodOp(f) {
  3693. return function () {
  3694. if (this.curOp) { return f.apply(this, arguments) }
  3695. startOperation(this);
  3696. try { return f.apply(this, arguments) }
  3697. finally { endOperation(this); }
  3698. }
  3699. }
  3700. function docMethodOp(f) {
  3701. return function () {
  3702. var cm = this.cm;
  3703. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3704. startOperation(cm);
  3705. try { return f.apply(this, arguments) }
  3706. finally { endOperation(cm); }
  3707. }
  3708. }
  3709. // HIGHLIGHT WORKER
  3710. function startWorker(cm, time) {
  3711. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3712. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3713. }
  3714. function highlightWorker(cm) {
  3715. var doc = cm.doc;
  3716. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3717. var end = +new Date + cm.options.workTime;
  3718. var context = getContextBefore(cm, doc.highlightFrontier);
  3719. var changedLines = [];
  3720. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3721. if (context.line >= cm.display.viewFrom) { // Visible
  3722. var oldStyles = line.styles;
  3723. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3724. var highlighted = highlightLine(cm, line, context, true);
  3725. if (resetState) { context.state = resetState; }
  3726. line.styles = highlighted.styles;
  3727. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3728. if (newCls) { line.styleClasses = newCls; }
  3729. else if (oldCls) { line.styleClasses = null; }
  3730. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3731. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3732. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3733. if (ischange) { changedLines.push(context.line); }
  3734. line.stateAfter = context.save();
  3735. context.nextLine();
  3736. } else {
  3737. if (line.text.length <= cm.options.maxHighlightLength)
  3738. { processLine(cm, line.text, context); }
  3739. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3740. context.nextLine();
  3741. }
  3742. if (+new Date > end) {
  3743. startWorker(cm, cm.options.workDelay);
  3744. return true
  3745. }
  3746. });
  3747. doc.highlightFrontier = context.line;
  3748. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3749. if (changedLines.length) {
  3750. runInOp(cm, function () {
  3751. for (var i = 0; i < changedLines.length; i++)
  3752. { regLineChange(cm, changedLines[i], "text"); }
  3753. });
  3754. }
  3755. }
  3756. // DISPLAY DRAWING
  3757. var DisplayUpdate = function (cm, viewport, force) {
  3758. var display = cm.display;
  3759. this.viewport = viewport;
  3760. // Store some values that we'll need later (but don't want to force a relayout for)
  3761. this.visible = visibleLines(display, cm.doc, viewport);
  3762. this.editorIsHidden = !display.wrapper.offsetWidth;
  3763. this.wrapperHeight = display.wrapper.clientHeight;
  3764. this.wrapperWidth = display.wrapper.clientWidth;
  3765. this.oldDisplayWidth = displayWidth(cm);
  3766. this.force = force;
  3767. this.dims = getDimensions(cm);
  3768. this.events = [];
  3769. };
  3770. DisplayUpdate.prototype.signal = function (emitter, type) {
  3771. if (hasHandler(emitter, type))
  3772. { this.events.push(arguments); }
  3773. };
  3774. DisplayUpdate.prototype.finish = function () {
  3775. for (var i = 0; i < this.events.length; i++)
  3776. { signal.apply(null, this.events[i]); }
  3777. };
  3778. function maybeClipScrollbars(cm) {
  3779. var display = cm.display;
  3780. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3781. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3782. display.heightForcer.style.height = scrollGap(cm) + "px";
  3783. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3784. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3785. display.scrollbarsClipped = true;
  3786. }
  3787. }
  3788. function selectionSnapshot(cm) {
  3789. if (cm.hasFocus()) { return null }
  3790. var active = activeElt(doc(cm));
  3791. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3792. var result = { activeElt: active };
  3793. if (window.getSelection) {
  3794. var sel = win(cm).getSelection();
  3795. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3796. result.anchorNode = sel.anchorNode;
  3797. result.anchorOffset = sel.anchorOffset;
  3798. result.focusNode = sel.focusNode;
  3799. result.focusOffset = sel.focusOffset;
  3800. }
  3801. }
  3802. return result
  3803. }
  3804. function restoreSelection(snapshot) {
  3805. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(snapshot.activeElt.ownerDocument)) { return }
  3806. snapshot.activeElt.focus();
  3807. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  3808. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3809. var doc = snapshot.activeElt.ownerDocument;
  3810. var sel = doc.defaultView.getSelection(), range = doc.createRange();
  3811. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3812. range.collapse(false);
  3813. sel.removeAllRanges();
  3814. sel.addRange(range);
  3815. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3816. }
  3817. }
  3818. // Does the actual updating of the line display. Bails out
  3819. // (returning false) when there is nothing to be done and forced is
  3820. // false.
  3821. function updateDisplayIfNeeded(cm, update) {
  3822. var display = cm.display, doc = cm.doc;
  3823. if (update.editorIsHidden) {
  3824. resetView(cm);
  3825. return false
  3826. }
  3827. // Bail out if the visible area is already rendered and nothing changed.
  3828. if (!update.force &&
  3829. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3830. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3831. display.renderedView == display.view && countDirtyView(cm) == 0)
  3832. { return false }
  3833. if (maybeUpdateLineNumberWidth(cm)) {
  3834. resetView(cm);
  3835. update.dims = getDimensions(cm);
  3836. }
  3837. // Compute a suitable new viewport (from & to)
  3838. var end = doc.first + doc.size;
  3839. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3840. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3841. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3842. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3843. if (sawCollapsedSpans) {
  3844. from = visualLineNo(cm.doc, from);
  3845. to = visualLineEndNo(cm.doc, to);
  3846. }
  3847. var different = from != display.viewFrom || to != display.viewTo ||
  3848. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3849. adjustView(cm, from, to);
  3850. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3851. // Position the mover div to align with the current scroll position
  3852. cm.display.mover.style.top = display.viewOffset + "px";
  3853. var toUpdate = countDirtyView(cm);
  3854. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3855. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3856. { return false }
  3857. // For big changes, we hide the enclosing element during the
  3858. // update, since that speeds up the operations on most browsers.
  3859. var selSnapshot = selectionSnapshot(cm);
  3860. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3861. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3862. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3863. display.renderedView = display.view;
  3864. // There might have been a widget with a focused element that got
  3865. // hidden or updated, if so re-focus it.
  3866. restoreSelection(selSnapshot);
  3867. // Prevent selection and cursors from interfering with the scroll
  3868. // width and height.
  3869. removeChildren(display.cursorDiv);
  3870. removeChildren(display.selectionDiv);
  3871. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3872. if (different) {
  3873. display.lastWrapHeight = update.wrapperHeight;
  3874. display.lastWrapWidth = update.wrapperWidth;
  3875. startWorker(cm, 400);
  3876. }
  3877. display.updateLineNumbers = null;
  3878. return true
  3879. }
  3880. function postUpdateDisplay(cm, update) {
  3881. var viewport = update.viewport;
  3882. for (var first = true; ; first = false) {
  3883. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3884. // Clip forced viewport to actual scrollable area.
  3885. if (viewport && viewport.top != null)
  3886. { viewport = { top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) }; }
  3887. // Updated line heights might result in the drawn area not
  3888. // actually covering the viewport. Keep looping until it does.
  3889. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3890. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3891. { break }
  3892. } else if (first) {
  3893. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3894. }
  3895. if (!updateDisplayIfNeeded(cm, update)) { break }
  3896. updateHeightsInViewport(cm);
  3897. var barMeasure = measureForScrollbars(cm);
  3898. updateSelection(cm);
  3899. updateScrollbars(cm, barMeasure);
  3900. setDocumentHeight(cm, barMeasure);
  3901. update.force = false;
  3902. }
  3903. update.signal(cm, "update", cm);
  3904. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3905. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3906. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3907. }
  3908. }
  3909. function updateDisplaySimple(cm, viewport) {
  3910. var update = new DisplayUpdate(cm, viewport);
  3911. if (updateDisplayIfNeeded(cm, update)) {
  3912. updateHeightsInViewport(cm);
  3913. postUpdateDisplay(cm, update);
  3914. var barMeasure = measureForScrollbars(cm);
  3915. updateSelection(cm);
  3916. updateScrollbars(cm, barMeasure);
  3917. setDocumentHeight(cm, barMeasure);
  3918. update.finish();
  3919. }
  3920. }
  3921. // Sync the actual display DOM structure with display.view, removing
  3922. // nodes for lines that are no longer in view, and creating the ones
  3923. // that are not there yet, and updating the ones that are out of
  3924. // date.
  3925. function patchDisplay(cm, updateNumbersFrom, dims) {
  3926. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3927. var container = display.lineDiv, cur = container.firstChild;
  3928. function rm(node) {
  3929. var next = node.nextSibling;
  3930. // Works around a throw-scroll bug in OS X Webkit
  3931. if (webkit && mac && cm.display.currentWheelTarget == node)
  3932. { node.style.display = "none"; }
  3933. else
  3934. { node.parentNode.removeChild(node); }
  3935. return next
  3936. }
  3937. var view = display.view, lineN = display.viewFrom;
  3938. // Loop over the elements in the view, syncing cur (the DOM nodes
  3939. // in display.lineDiv) with the view as we go.
  3940. for (var i = 0; i < view.length; i++) {
  3941. var lineView = view[i];
  3942. if (lineView.hidden); else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3943. var node = buildLineElement(cm, lineView, lineN, dims);
  3944. container.insertBefore(node, cur);
  3945. } else { // Already drawn
  3946. while (cur != lineView.node) { cur = rm(cur); }
  3947. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3948. updateNumbersFrom <= lineN && lineView.lineNumber;
  3949. if (lineView.changes) {
  3950. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3951. updateLineForChanges(cm, lineView, lineN, dims);
  3952. }
  3953. if (updateNumber) {
  3954. removeChildren(lineView.lineNumber);
  3955. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3956. }
  3957. cur = lineView.node.nextSibling;
  3958. }
  3959. lineN += lineView.size;
  3960. }
  3961. while (cur) { cur = rm(cur); }
  3962. }
  3963. function updateGutterSpace(display) {
  3964. var width = display.gutters.offsetWidth;
  3965. display.sizer.style.marginLeft = width + "px";
  3966. // Send an event to consumers responding to changes in gutter width.
  3967. signalLater(display, "gutterChanged", display);
  3968. }
  3969. function setDocumentHeight(cm, measure) {
  3970. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3971. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3972. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3973. }
  3974. // Re-align line numbers and gutter marks to compensate for
  3975. // horizontal scrolling.
  3976. function alignHorizontally(cm) {
  3977. var display = cm.display, view = display.view;
  3978. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3979. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3980. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3981. for (var i = 0; i < view.length; i++) {
  3982. if (!view[i].hidden) {
  3983. if (cm.options.fixedGutter) {
  3984. if (view[i].gutter)
  3985. { view[i].gutter.style.left = left; }
  3986. if (view[i].gutterBackground)
  3987. { view[i].gutterBackground.style.left = left; }
  3988. }
  3989. var align = view[i].alignable;
  3990. if (align) {
  3991. for (var j = 0; j < align.length; j++)
  3992. { align[j].style.left = left; }
  3993. }
  3994. }
  3995. }
  3996. if (cm.options.fixedGutter)
  3997. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3998. }
  3999. // Used to ensure that the line number gutter is still the right
  4000. // size for the current document size. Returns true when an update
  4001. // is needed.
  4002. function maybeUpdateLineNumberWidth(cm) {
  4003. if (!cm.options.lineNumbers) { return false }
  4004. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  4005. if (last.length != display.lineNumChars) {
  4006. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  4007. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  4008. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  4009. display.lineGutter.style.width = "";
  4010. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  4011. display.lineNumWidth = display.lineNumInnerWidth + padding;
  4012. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  4013. display.lineGutter.style.width = display.lineNumWidth + "px";
  4014. updateGutterSpace(cm.display);
  4015. return true
  4016. }
  4017. return false
  4018. }
  4019. function getGutters(gutters, lineNumbers) {
  4020. var result = [], sawLineNumbers = false;
  4021. for (var i = 0; i < gutters.length; i++) {
  4022. var name = gutters[i], style = null;
  4023. if (typeof name != "string") { style = name.style; name = name.className; }
  4024. if (name == "CodeMirror-linenumbers") {
  4025. if (!lineNumbers) { continue }
  4026. else { sawLineNumbers = true; }
  4027. }
  4028. result.push({ className: name, style: style });
  4029. }
  4030. if (lineNumbers && !sawLineNumbers) { result.push({ className: "CodeMirror-linenumbers", style: null }); }
  4031. return result
  4032. }
  4033. // Rebuild the gutter elements, ensure the margin to the left of the
  4034. // code matches their width.
  4035. function renderGutters(display) {
  4036. var gutters = display.gutters, specs = display.gutterSpecs;
  4037. removeChildren(gutters);
  4038. display.lineGutter = null;
  4039. for (var i = 0; i < specs.length; ++i) {
  4040. var ref = specs[i];
  4041. var className = ref.className;
  4042. var style = ref.style;
  4043. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  4044. if (style) { gElt.style.cssText = style; }
  4045. if (className == "CodeMirror-linenumbers") {
  4046. display.lineGutter = gElt;
  4047. gElt.style.width = (display.lineNumWidth || 1) + "px";
  4048. }
  4049. }
  4050. gutters.style.display = specs.length ? "" : "none";
  4051. updateGutterSpace(display);
  4052. }
  4053. function updateGutters(cm) {
  4054. renderGutters(cm.display);
  4055. regChange(cm);
  4056. alignHorizontally(cm);
  4057. }
  4058. // The display handles the DOM integration, both for input reading
  4059. // and content drawing. It holds references to DOM nodes and
  4060. // display-related state.
  4061. function Display(place, doc, input, options) {
  4062. var d = this;
  4063. this.input = input;
  4064. // Covers bottom-right square when both scrollbars are present.
  4065. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  4066. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  4067. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  4068. // and h scrollbar is present.
  4069. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  4070. d.gutterFiller.setAttribute("cm-not-content", "true");
  4071. // Will contain the actual code, positioned to cover the viewport.
  4072. d.lineDiv = eltP("div", null, "CodeMirror-code");
  4073. // Elements are added to these to represent selection and cursors.
  4074. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  4075. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  4076. // A visibility: hidden element used to find the size of things.
  4077. d.measure = elt("div", null, "CodeMirror-measure");
  4078. // When lines outside of the viewport are measured, they are drawn in this.
  4079. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  4080. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  4081. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  4082. null, "position: relative; outline: none");
  4083. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  4084. // Moved around its parent to cover visible view.
  4085. d.mover = elt("div", [lines], null, "position: relative");
  4086. // Set to the height of the document, allowing scrolling.
  4087. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  4088. d.sizerWidth = null;
  4089. // Behavior of elts with overflow: auto and padding is
  4090. // inconsistent across browsers. This is used to ensure the
  4091. // scrollable area is big enough.
  4092. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  4093. // Will contain the gutters, if any.
  4094. d.gutters = elt("div", null, "CodeMirror-gutters");
  4095. d.lineGutter = null;
  4096. // Actual scrollable element.
  4097. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  4098. d.scroller.setAttribute("tabIndex", "-1");
  4099. // The element in which the editor lives.
  4100. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  4101. // See #6982. FIXME remove when this has been fixed for a while in Chrome
  4102. if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = "inset(0px)"; }
  4103. // This attribute is respected by automatic translation systems such as Google Translate,
  4104. // and may also be respected by tools used by human translators.
  4105. d.wrapper.setAttribute('translate', 'no');
  4106. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  4107. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  4108. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  4109. if (place) {
  4110. if (place.appendChild) { place.appendChild(d.wrapper); }
  4111. else { place(d.wrapper); }
  4112. }
  4113. // Current rendered range (may be bigger than the view window).
  4114. d.viewFrom = d.viewTo = doc.first;
  4115. d.reportedViewFrom = d.reportedViewTo = doc.first;
  4116. // Information about the rendered lines.
  4117. d.view = [];
  4118. d.renderedView = null;
  4119. // Holds info about a single rendered line when it was rendered
  4120. // for measurement, while not in view.
  4121. d.externalMeasured = null;
  4122. // Empty space (in pixels) above the view
  4123. d.viewOffset = 0;
  4124. d.lastWrapHeight = d.lastWrapWidth = 0;
  4125. d.updateLineNumbers = null;
  4126. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  4127. d.scrollbarsClipped = false;
  4128. // Used to only resize the line number gutter when necessary (when
  4129. // the amount of lines crosses a boundary that makes its width change)
  4130. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  4131. // Set to true when a non-horizontal-scrolling line widget is
  4132. // added. As an optimization, line widget aligning is skipped when
  4133. // this is false.
  4134. d.alignWidgets = false;
  4135. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4136. // Tracks the maximum line length so that the horizontal scrollbar
  4137. // can be kept static when scrolling.
  4138. d.maxLine = null;
  4139. d.maxLineLength = 0;
  4140. d.maxLineChanged = false;
  4141. // Used for measuring wheel scrolling granularity
  4142. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4143. // True when shift is held down.
  4144. d.shift = false;
  4145. // Used to track whether anything happened since the context menu
  4146. // was opened.
  4147. d.selForContextMenu = null;
  4148. d.activeTouch = null;
  4149. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4150. renderGutters(d);
  4151. input.init(d);
  4152. }
  4153. // Since the delta values reported on mouse wheel events are
  4154. // unstandardized between browsers and even browser versions, and
  4155. // generally horribly unpredictable, this code starts by measuring
  4156. // the scroll effect that the first few mouse wheel events have,
  4157. // and, from that, detects the way it can convert deltas to pixel
  4158. // offsets afterwards.
  4159. //
  4160. // The reason we want to know the amount a wheel event will scroll
  4161. // is that it gives us a chance to update the display before the
  4162. // actual scrolling happens, reducing flickering.
  4163. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4164. // Fill in a browser-detected starting value on browsers where we
  4165. // know one. These don't have to be accurate -- the result of them
  4166. // being wrong would just be a slight flicker on the first wheel
  4167. // scroll (if it is large enough).
  4168. if (ie) { wheelPixelsPerUnit = -.53; }
  4169. else if (gecko) { wheelPixelsPerUnit = 15; }
  4170. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4171. else if (safari) { wheelPixelsPerUnit = -1 / 3; }
  4172. function wheelEventDelta(e) {
  4173. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4174. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4175. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4176. else if (dy == null) { dy = e.wheelDelta; }
  4177. return { x: dx, y: dy }
  4178. }
  4179. function wheelEventPixels(e) {
  4180. var delta = wheelEventDelta(e);
  4181. delta.x *= wheelPixelsPerUnit;
  4182. delta.y *= wheelPixelsPerUnit;
  4183. return delta
  4184. }
  4185. function onScrollWheel(cm, e) {
  4186. // On Chrome 102, viewport updates somehow stop wheel-based
  4187. // scrolling. Turning off pointer events during the scroll seems
  4188. // to avoid the issue.
  4189. if (chrome && chrome_version == 102) {
  4190. if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
  4191. else { clearTimeout(cm.display.chromeScrollHack); }
  4192. cm.display.chromeScrollHack = setTimeout(function () {
  4193. cm.display.chromeScrollHack = null;
  4194. cm.display.sizer.style.pointerEvents = "";
  4195. }, 100);
  4196. }
  4197. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4198. var pixelsPerUnit = wheelPixelsPerUnit;
  4199. if (e.deltaMode === 0) {
  4200. dx = e.deltaX;
  4201. dy = e.deltaY;
  4202. pixelsPerUnit = 1;
  4203. }
  4204. var display = cm.display, scroll = display.scroller;
  4205. // Quit if there's nothing to scroll here
  4206. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4207. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4208. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4209. // Webkit browsers on OS X abort momentum scrolls when the target
  4210. // of the scroll event is removed from the scrollable element.
  4211. // This hack (see related code in patchDisplay) makes sure the
  4212. // element is kept around.
  4213. if (dy && mac && webkit) {
  4214. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4215. for (var i = 0; i < view.length; i++) {
  4216. if (view[i].node == cur) {
  4217. cm.display.currentWheelTarget = cur;
  4218. break outer
  4219. }
  4220. }
  4221. }
  4222. }
  4223. // On some browsers, horizontal scrolling will cause redraws to
  4224. // happen before the gutter has been realigned, causing it to
  4225. // wriggle around in a most unseemly way. When we have an
  4226. // estimated pixels/delta value, we just handle horizontal
  4227. // scrolling entirely here. It'll be slightly off from native, but
  4228. // better than glitching out.
  4229. if (dx && !gecko && !presto && pixelsPerUnit != null) {
  4230. if (dy && canScrollY)
  4231. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
  4232. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
  4233. // Only prevent default scrolling if vertical scrolling is
  4234. // actually possible. Otherwise, it causes vertical scroll
  4235. // jitter on OSX trackpads when deltaX is small and deltaY
  4236. // is large (issue #3579)
  4237. if (!dy || (dy && canScrollY))
  4238. { e_preventDefault(e); }
  4239. display.wheelStartX = null; // Abort measurement, if in progress
  4240. return
  4241. }
  4242. // 'Project' the visible viewport to cover the area that is being
  4243. // scrolled into view (if we know enough to estimate it).
  4244. if (dy && pixelsPerUnit != null) {
  4245. var pixels = dy * pixelsPerUnit;
  4246. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4247. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4248. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4249. updateDisplaySimple(cm, { top: top, bottom: bot });
  4250. }
  4251. if (wheelSamples < 20 && e.deltaMode !== 0) {
  4252. if (display.wheelStartX == null) {
  4253. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4254. display.wheelDX = dx; display.wheelDY = dy;
  4255. setTimeout(function () {
  4256. if (display.wheelStartX == null) { return }
  4257. var movedX = scroll.scrollLeft - display.wheelStartX;
  4258. var movedY = scroll.scrollTop - display.wheelStartY;
  4259. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4260. (movedX && display.wheelDX && movedX / display.wheelDX);
  4261. display.wheelStartX = display.wheelStartY = null;
  4262. if (!sample) { return }
  4263. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4264. ++wheelSamples;
  4265. }, 200);
  4266. } else {
  4267. display.wheelDX += dx; display.wheelDY += dy;
  4268. }
  4269. }
  4270. }
  4271. // Selection objects are immutable. A new one is created every time
  4272. // the selection changes. A selection is one or more non-overlapping
  4273. // (and non-touching) ranges, sorted, and an integer that indicates
  4274. // which one is the primary selection (the one that's scrolled into
  4275. // view, that getCursor returns, etc).
  4276. var Selection = function (ranges, primIndex) {
  4277. this.ranges = ranges;
  4278. this.primIndex = primIndex;
  4279. };
  4280. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4281. Selection.prototype.equals = function (other) {
  4282. if (other == this) { return true }
  4283. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4284. for (var i = 0; i < this.ranges.length; i++) {
  4285. var here = this.ranges[i], there = other.ranges[i];
  4286. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4287. }
  4288. return true
  4289. };
  4290. Selection.prototype.deepCopy = function () {
  4291. var out = [];
  4292. for (var i = 0; i < this.ranges.length; i++)
  4293. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4294. return new Selection(out, this.primIndex)
  4295. };
  4296. Selection.prototype.somethingSelected = function () {
  4297. for (var i = 0; i < this.ranges.length; i++)
  4298. { if (!this.ranges[i].empty()) { return true } }
  4299. return false
  4300. };
  4301. Selection.prototype.contains = function (pos, end) {
  4302. if (!end) { end = pos; }
  4303. for (var i = 0; i < this.ranges.length; i++) {
  4304. var range = this.ranges[i];
  4305. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4306. { return i }
  4307. }
  4308. return -1
  4309. };
  4310. var Range = function (anchor, head) {
  4311. this.anchor = anchor; this.head = head;
  4312. };
  4313. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4314. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4315. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4316. // Take an unsorted, potentially overlapping set of ranges, and
  4317. // build a selection out of it. 'Consumes' ranges array (modifying
  4318. // it).
  4319. function normalizeSelection(cm, ranges, primIndex) {
  4320. var mayTouch = cm && cm.options.selectionsMayTouch;
  4321. var prim = ranges[primIndex];
  4322. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4323. primIndex = indexOf(ranges, prim);
  4324. for (var i = 1; i < ranges.length; i++) {
  4325. var cur = ranges[i], prev = ranges[i - 1];
  4326. var diff = cmp(prev.to(), cur.from());
  4327. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4328. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4329. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4330. if (i <= primIndex) { --primIndex; }
  4331. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4332. }
  4333. }
  4334. return new Selection(ranges, primIndex)
  4335. }
  4336. function simpleSelection(anchor, head) {
  4337. return new Selection([new Range(anchor, head || anchor)], 0)
  4338. }
  4339. // Compute the position of the end of a change (its 'to' property
  4340. // refers to the pre-change end).
  4341. function changeEnd(change) {
  4342. if (!change.text) { return change.to }
  4343. return Pos(change.from.line + change.text.length - 1,
  4344. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4345. }
  4346. // Adjust a position to refer to the post-change position of the
  4347. // same text, or the end of the change if the change covers it.
  4348. function adjustForChange(pos, change) {
  4349. if (cmp(pos, change.from) < 0) { return pos }
  4350. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4351. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4352. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4353. return Pos(line, ch)
  4354. }
  4355. function computeSelAfterChange(doc, change) {
  4356. var out = [];
  4357. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4358. var range = doc.sel.ranges[i];
  4359. out.push(new Range(adjustForChange(range.anchor, change),
  4360. adjustForChange(range.head, change)));
  4361. }
  4362. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4363. }
  4364. function offsetPos(pos, old, nw) {
  4365. if (pos.line == old.line)
  4366. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4367. else
  4368. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4369. }
  4370. // Used by replaceSelections to allow moving the selection to the
  4371. // start or around the replaced test. Hint may be "start" or "around".
  4372. function computeReplacedSel(doc, changes, hint) {
  4373. var out = [];
  4374. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4375. for (var i = 0; i < changes.length; i++) {
  4376. var change = changes[i];
  4377. var from = offsetPos(change.from, oldPrev, newPrev);
  4378. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4379. oldPrev = change.to;
  4380. newPrev = to;
  4381. if (hint == "around") {
  4382. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4383. out[i] = new Range(inv ? to : from, inv ? from : to);
  4384. } else {
  4385. out[i] = new Range(from, from);
  4386. }
  4387. }
  4388. return new Selection(out, doc.sel.primIndex)
  4389. }
  4390. // Used to get the editor into a consistent state again when options change.
  4391. function loadMode(cm) {
  4392. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4393. resetModeState(cm);
  4394. }
  4395. function resetModeState(cm) {
  4396. cm.doc.iter(function (line) {
  4397. if (line.stateAfter) { line.stateAfter = null; }
  4398. if (line.styles) { line.styles = null; }
  4399. });
  4400. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4401. startWorker(cm, 100);
  4402. cm.state.modeGen++;
  4403. if (cm.curOp) { regChange(cm); }
  4404. }
  4405. // DOCUMENT DATA STRUCTURE
  4406. // By default, updates that start and end at the beginning of a line
  4407. // are treated specially, in order to make the association of line
  4408. // widgets and marker elements with the text behave more intuitive.
  4409. function isWholeLineUpdate(doc, change) {
  4410. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4411. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4412. }
  4413. // Perform a change on the document data structure.
  4414. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4415. function spansFor(n) { return markedSpans ? markedSpans[n] : null }
  4416. function update(line, text, spans) {
  4417. updateLine(line, text, spans, estimateHeight);
  4418. signalLater(line, "change", line, change);
  4419. }
  4420. function linesFor(start, end) {
  4421. var result = [];
  4422. for (var i = start; i < end; ++i)
  4423. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4424. return result
  4425. }
  4426. var from = change.from, to = change.to, text = change.text;
  4427. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4428. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4429. // Adjust the line structure
  4430. if (change.full) {
  4431. doc.insert(0, linesFor(0, text.length));
  4432. doc.remove(text.length, doc.size - text.length);
  4433. } else if (isWholeLineUpdate(doc, change)) {
  4434. // This is a whole-line replace. Treated specially to make
  4435. // sure line objects move the way they are supposed to.
  4436. var added = linesFor(0, text.length - 1);
  4437. update(lastLine, lastLine.text, lastSpans);
  4438. if (nlines) { doc.remove(from.line, nlines); }
  4439. if (added.length) { doc.insert(from.line, added); }
  4440. } else if (firstLine == lastLine) {
  4441. if (text.length == 1) {
  4442. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4443. } else {
  4444. var added$1 = linesFor(1, text.length - 1);
  4445. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4446. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4447. doc.insert(from.line + 1, added$1);
  4448. }
  4449. } else if (text.length == 1) {
  4450. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4451. doc.remove(from.line + 1, nlines);
  4452. } else {
  4453. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4454. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4455. var added$2 = linesFor(1, text.length - 1);
  4456. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4457. doc.insert(from.line + 1, added$2);
  4458. }
  4459. signalLater(doc, "change", doc, change);
  4460. }
  4461. // Call f for all linked documents.
  4462. function linkedDocs(doc, f, sharedHistOnly) {
  4463. function propagate(doc, skip, sharedHist) {
  4464. if (doc.linked) {
  4465. for (var i = 0; i < doc.linked.length; ++i) {
  4466. var rel = doc.linked[i];
  4467. if (rel.doc == skip) { continue }
  4468. var shared = sharedHist && rel.sharedHist;
  4469. if (sharedHistOnly && !shared) { continue }
  4470. f(rel.doc, shared);
  4471. propagate(rel.doc, doc, shared);
  4472. }
  4473. }
  4474. }
  4475. propagate(doc, null, true);
  4476. }
  4477. // Attach a document to an editor.
  4478. function attachDoc(cm, doc) {
  4479. if (doc.cm) { throw new Error("This document is already in use.") }
  4480. cm.doc = doc;
  4481. doc.cm = cm;
  4482. estimateLineHeights(cm);
  4483. loadMode(cm);
  4484. setDirectionClass(cm);
  4485. cm.options.direction = doc.direction;
  4486. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4487. cm.options.mode = doc.modeOption;
  4488. regChange(cm);
  4489. }
  4490. function setDirectionClass(cm) {
  4491. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4492. }
  4493. function directionChanged(cm) {
  4494. runInOp(cm, function () {
  4495. setDirectionClass(cm);
  4496. regChange(cm);
  4497. });
  4498. }
  4499. function History(prev) {
  4500. // Arrays of change events and selections. Doing something adds an
  4501. // event to done and clears undo. Undoing moves events from done
  4502. // to undone, redoing moves them in the other direction.
  4503. this.done = []; this.undone = [];
  4504. this.undoDepth = prev ? prev.undoDepth : Infinity;
  4505. // Used to track when changes can be merged into a single undo
  4506. // event
  4507. this.lastModTime = this.lastSelTime = 0;
  4508. this.lastOp = this.lastSelOp = null;
  4509. this.lastOrigin = this.lastSelOrigin = null;
  4510. // Used by the isClean() method
  4511. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  4512. }
  4513. // Create a history change event from an updateDoc-style change
  4514. // object.
  4515. function historyChangeFromChange(doc, change) {
  4516. var histChange = { from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to) };
  4517. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4518. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4519. return histChange
  4520. }
  4521. // Pop all selection events off the end of a history array. Stop at
  4522. // a change event.
  4523. function clearSelectionEvents(array) {
  4524. while (array.length) {
  4525. var last = lst(array);
  4526. if (last.ranges) { array.pop(); }
  4527. else { break }
  4528. }
  4529. }
  4530. // Find the top change event in the history. Pop off selection
  4531. // events that are in the way.
  4532. function lastChangeEvent(hist, force) {
  4533. if (force) {
  4534. clearSelectionEvents(hist.done);
  4535. return lst(hist.done)
  4536. } else if (hist.done.length && !lst(hist.done).ranges) {
  4537. return lst(hist.done)
  4538. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4539. hist.done.pop();
  4540. return lst(hist.done)
  4541. }
  4542. }
  4543. // Register a change in the history. Merges changes that are within
  4544. // a single operation, or are close together with an origin that
  4545. // allows merging (starting with "+") into a single event.
  4546. function addChangeToHistory(doc, change, selAfter, opId) {
  4547. var hist = doc.history;
  4548. hist.undone.length = 0;
  4549. var time = +new Date, cur;
  4550. var last;
  4551. if ((hist.lastOp == opId ||
  4552. hist.lastOrigin == change.origin && change.origin &&
  4553. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4554. change.origin.charAt(0) == "*")) &&
  4555. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4556. // Merge this change into the last event
  4557. last = lst(cur.changes);
  4558. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4559. // Optimized case for simple insertion -- don't want to add
  4560. // new changesets for every character typed
  4561. last.to = changeEnd(change);
  4562. } else {
  4563. // Add new sub-event
  4564. cur.changes.push(historyChangeFromChange(doc, change));
  4565. }
  4566. } else {
  4567. // Can not be merged, start a new event.
  4568. var before = lst(hist.done);
  4569. if (!before || !before.ranges)
  4570. { pushSelectionToHistory(doc.sel, hist.done); }
  4571. cur = {
  4572. changes: [historyChangeFromChange(doc, change)],
  4573. generation: hist.generation
  4574. };
  4575. hist.done.push(cur);
  4576. while (hist.done.length > hist.undoDepth) {
  4577. hist.done.shift();
  4578. if (!hist.done[0].ranges) { hist.done.shift(); }
  4579. }
  4580. }
  4581. hist.done.push(selAfter);
  4582. hist.generation = ++hist.maxGeneration;
  4583. hist.lastModTime = hist.lastSelTime = time;
  4584. hist.lastOp = hist.lastSelOp = opId;
  4585. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4586. if (!last) { signal(doc, "historyAdded"); }
  4587. }
  4588. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4589. var ch = origin.charAt(0);
  4590. return ch == "*" ||
  4591. ch == "+" &&
  4592. prev.ranges.length == sel.ranges.length &&
  4593. prev.somethingSelected() == sel.somethingSelected() &&
  4594. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4595. }
  4596. // Called whenever the selection changes, sets the new selection as
  4597. // the pending selection in the history, and pushes the old pending
  4598. // selection into the 'done' array when it was significantly
  4599. // different (in number of selected ranges, emptiness, or time).
  4600. function addSelectionToHistory(doc, sel, opId, options) {
  4601. var hist = doc.history, origin = options && options.origin;
  4602. // A new event is started when the previous origin does not match
  4603. // the current, or the origins don't allow matching. Origins
  4604. // starting with * are always merged, those starting with + are
  4605. // merged when similar and close together in time.
  4606. if (opId == hist.lastSelOp ||
  4607. (origin && hist.lastSelOrigin == origin &&
  4608. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4609. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4610. { hist.done[hist.done.length - 1] = sel; }
  4611. else
  4612. { pushSelectionToHistory(sel, hist.done); }
  4613. hist.lastSelTime = +new Date;
  4614. hist.lastSelOrigin = origin;
  4615. hist.lastSelOp = opId;
  4616. if (options && options.clearRedo !== false)
  4617. { clearSelectionEvents(hist.undone); }
  4618. }
  4619. function pushSelectionToHistory(sel, dest) {
  4620. var top = lst(dest);
  4621. if (!(top && top.ranges && top.equals(sel)))
  4622. { dest.push(sel); }
  4623. }
  4624. // Used to store marked span information in the history.
  4625. function attachLocalSpans(doc, change, from, to) {
  4626. var existing = change["spans_" + doc.id], n = 0;
  4627. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4628. if (line.markedSpans)
  4629. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4630. ++n;
  4631. });
  4632. }
  4633. // When un/re-doing restores text containing marked spans, those
  4634. // that have been explicitly cleared should not be restored.
  4635. function removeClearedSpans(spans) {
  4636. if (!spans) { return null }
  4637. var out;
  4638. for (var i = 0; i < spans.length; ++i) {
  4639. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4640. else if (out) { out.push(spans[i]); }
  4641. }
  4642. return !out ? spans : out.length ? out : null
  4643. }
  4644. // Retrieve and filter the old marked spans stored in a change event.
  4645. function getOldSpans(doc, change) {
  4646. var found = change["spans_" + doc.id];
  4647. if (!found) { return null }
  4648. var nw = [];
  4649. for (var i = 0; i < change.text.length; ++i)
  4650. { nw.push(removeClearedSpans(found[i])); }
  4651. return nw
  4652. }
  4653. // Used for un/re-doing changes from the history. Combines the
  4654. // result of computing the existing spans with the set of spans that
  4655. // existed in the history (so that deleting around a span and then
  4656. // undoing brings back the span).
  4657. function mergeOldSpans(doc, change) {
  4658. var old = getOldSpans(doc, change);
  4659. var stretched = stretchSpansOverChange(doc, change);
  4660. if (!old) { return stretched }
  4661. if (!stretched) { return old }
  4662. for (var i = 0; i < old.length; ++i) {
  4663. var oldCur = old[i], stretchCur = stretched[i];
  4664. if (oldCur && stretchCur) {
  4665. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4666. var span = stretchCur[j];
  4667. for (var k = 0; k < oldCur.length; ++k)
  4668. { if (oldCur[k].marker == span.marker) { continue spans } }
  4669. oldCur.push(span);
  4670. }
  4671. } else if (stretchCur) {
  4672. old[i] = stretchCur;
  4673. }
  4674. }
  4675. return old
  4676. }
  4677. // Used both to provide a JSON-safe object in .getHistory, and, when
  4678. // detaching a document, to split the history in two
  4679. function copyHistoryArray(events, newGroup, instantiateSel) {
  4680. var copy = [];
  4681. for (var i = 0; i < events.length; ++i) {
  4682. var event = events[i];
  4683. if (event.ranges) {
  4684. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4685. continue
  4686. }
  4687. var changes = event.changes, newChanges = [];
  4688. copy.push({ changes: newChanges });
  4689. for (var j = 0; j < changes.length; ++j) {
  4690. var change = changes[j], m = (void 0);
  4691. newChanges.push({ from: change.from, to: change.to, text: change.text });
  4692. if (newGroup) {
  4693. for (var prop in change) {
  4694. if (m = prop.match(/^spans_(\d+)$/)) {
  4695. if (indexOf(newGroup, Number(m[1])) > -1) {
  4696. lst(newChanges)[prop] = change[prop];
  4697. delete change[prop];
  4698. }
  4699. }
  4700. }
  4701. }
  4702. }
  4703. }
  4704. return copy
  4705. }
  4706. // The 'scroll' parameter given to many of these indicated whether
  4707. // the new cursor position should be scrolled into view after
  4708. // modifying the selection.
  4709. // If shift is held or the extend flag is set, extends a range to
  4710. // include a given position (and optionally a second position).
  4711. // Otherwise, simply returns the range between the given positions.
  4712. // Used for cursor motion and such.
  4713. function extendRange(range, head, other, extend) {
  4714. if (extend) {
  4715. var anchor = range.anchor;
  4716. if (other) {
  4717. var posBefore = cmp(head, anchor) < 0;
  4718. if (posBefore != (cmp(other, anchor) < 0)) {
  4719. anchor = head;
  4720. head = other;
  4721. } else if (posBefore != (cmp(head, other) < 0)) {
  4722. head = other;
  4723. }
  4724. }
  4725. return new Range(anchor, head)
  4726. } else {
  4727. return new Range(other || head, head)
  4728. }
  4729. }
  4730. // Extend the primary selection range, discard the rest.
  4731. function extendSelection(doc, head, other, options, extend) {
  4732. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4733. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4734. }
  4735. // Extend all selections (pos is an array of selections with length
  4736. // equal the number of selections)
  4737. function extendSelections(doc, heads, options) {
  4738. var out = [];
  4739. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4740. for (var i = 0; i < doc.sel.ranges.length; i++)
  4741. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4742. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4743. setSelection(doc, newSel, options);
  4744. }
  4745. // Updates a single range in the selection.
  4746. function replaceOneSelection(doc, i, range, options) {
  4747. var ranges = doc.sel.ranges.slice(0);
  4748. ranges[i] = range;
  4749. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4750. }
  4751. // Reset the selection to a single range.
  4752. function setSimpleSelection(doc, anchor, head, options) {
  4753. setSelection(doc, simpleSelection(anchor, head), options);
  4754. }
  4755. // Give beforeSelectionChange handlers a change to influence a
  4756. // selection update.
  4757. function filterSelectionChange(doc, sel, options) {
  4758. var obj = {
  4759. ranges: sel.ranges,
  4760. update: function (ranges) {
  4761. this.ranges = [];
  4762. for (var i = 0; i < ranges.length; i++) {
  4763. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4764. clipPos(doc, ranges[i].head));
  4765. }
  4766. },
  4767. origin: options && options.origin
  4768. };
  4769. signal(doc, "beforeSelectionChange", doc, obj);
  4770. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4771. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4772. else { return sel }
  4773. }
  4774. function setSelectionReplaceHistory(doc, sel, options) {
  4775. var done = doc.history.done, last = lst(done);
  4776. if (last && last.ranges) {
  4777. done[done.length - 1] = sel;
  4778. setSelectionNoUndo(doc, sel, options);
  4779. } else {
  4780. setSelection(doc, sel, options);
  4781. }
  4782. }
  4783. // Set a new selection.
  4784. function setSelection(doc, sel, options) {
  4785. setSelectionNoUndo(doc, sel, options);
  4786. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4787. }
  4788. function setSelectionNoUndo(doc, sel, options) {
  4789. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4790. { sel = filterSelectionChange(doc, sel, options); }
  4791. var bias = options && options.bias ||
  4792. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4793. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4794. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
  4795. { ensureCursorVisible(doc.cm); }
  4796. }
  4797. function setSelectionInner(doc, sel) {
  4798. if (sel.equals(doc.sel)) { return }
  4799. doc.sel = sel;
  4800. if (doc.cm) {
  4801. doc.cm.curOp.updateInput = 1;
  4802. doc.cm.curOp.selectionChanged = true;
  4803. signalCursorActivity(doc.cm);
  4804. }
  4805. signalLater(doc, "cursorActivity", doc);
  4806. }
  4807. // Verify that the selection does not partially select any atomic
  4808. // marked ranges.
  4809. function reCheckSelection(doc) {
  4810. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4811. }
  4812. // Return a selection that does not partially select any atomic
  4813. // ranges.
  4814. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4815. var out;
  4816. for (var i = 0; i < sel.ranges.length; i++) {
  4817. var range = sel.ranges[i];
  4818. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4819. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4820. var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4821. if (out || newAnchor != range.anchor || newHead != range.head) {
  4822. if (!out) { out = sel.ranges.slice(0, i); }
  4823. out[i] = new Range(newAnchor, newHead);
  4824. }
  4825. }
  4826. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4827. }
  4828. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4829. var line = getLine(doc, pos.line);
  4830. if (line.markedSpans) {
  4831. for (var i = 0; i < line.markedSpans.length; ++i) {
  4832. var sp = line.markedSpans[i], m = sp.marker;
  4833. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  4834. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  4835. // is with selectLeft/Right
  4836. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  4837. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  4838. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4839. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4840. if (mayClear) {
  4841. signal(m, "beforeCursorEnter");
  4842. if (m.explicitlyCleared) {
  4843. if (!line.markedSpans) { break }
  4844. else { --i; continue }
  4845. }
  4846. }
  4847. if (!m.atomic) { continue }
  4848. if (oldPos) {
  4849. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4850. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  4851. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4852. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4853. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4854. }
  4855. var far = m.find(dir < 0 ? -1 : 1);
  4856. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  4857. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4858. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4859. }
  4860. }
  4861. }
  4862. return pos
  4863. }
  4864. // Ensure a given position is not inside an atomic range.
  4865. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4866. var dir = bias || 1;
  4867. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4868. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4869. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4870. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4871. if (!found) {
  4872. doc.cantEdit = true;
  4873. return Pos(doc.first, 0)
  4874. }
  4875. return found
  4876. }
  4877. function movePos(doc, pos, dir, line) {
  4878. if (dir < 0 && pos.ch == 0) {
  4879. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4880. else { return null }
  4881. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4882. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4883. else { return null }
  4884. } else {
  4885. return new Pos(pos.line, pos.ch + dir)
  4886. }
  4887. }
  4888. function selectAll(cm) {
  4889. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4890. }
  4891. // UPDATING
  4892. // Allow "beforeChange" event handlers to influence a change
  4893. function filterChange(doc, change, update) {
  4894. var obj = {
  4895. canceled: false,
  4896. from: change.from,
  4897. to: change.to,
  4898. text: change.text,
  4899. origin: change.origin,
  4900. cancel: function () { return obj.canceled = true; }
  4901. };
  4902. if (update) {
  4903. obj.update = function (from, to, text, origin) {
  4904. if (from) { obj.from = clipPos(doc, from); }
  4905. if (to) { obj.to = clipPos(doc, to); }
  4906. if (text) { obj.text = text; }
  4907. if (origin !== undefined) { obj.origin = origin; }
  4908. };
  4909. }
  4910. signal(doc, "beforeChange", doc, obj);
  4911. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4912. if (obj.canceled) {
  4913. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4914. return null
  4915. }
  4916. return { from: obj.from, to: obj.to, text: obj.text, origin: obj.origin }
  4917. }
  4918. // Apply a change to a document, and add it to the document's
  4919. // history, and propagating it to all linked documents.
  4920. function makeChange(doc, change, ignoreReadOnly) {
  4921. if (doc.cm) {
  4922. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4923. if (doc.cm.state.suppressEdits) { return }
  4924. }
  4925. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4926. change = filterChange(doc, change, true);
  4927. if (!change) { return }
  4928. }
  4929. // Possibly split or suppress the update based on the presence
  4930. // of read-only spans in its range.
  4931. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4932. if (split) {
  4933. for (var i = split.length - 1; i >= 0; --i)
  4934. { makeChangeInner(doc, { from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin }); }
  4935. } else {
  4936. makeChangeInner(doc, change);
  4937. }
  4938. }
  4939. function makeChangeInner(doc, change) {
  4940. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4941. var selAfter = computeSelAfterChange(doc, change);
  4942. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4943. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4944. var rebased = [];
  4945. linkedDocs(doc, function (doc, sharedHist) {
  4946. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4947. rebaseHist(doc.history, change);
  4948. rebased.push(doc.history);
  4949. }
  4950. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4951. });
  4952. }
  4953. // Revert a change stored in a document's history.
  4954. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4955. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4956. if (suppress && !allowSelectionOnly) { return }
  4957. var hist = doc.history, event, selAfter = doc.sel;
  4958. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4959. // Verify that there is a useable event (so that ctrl-z won't
  4960. // needlessly clear selection events)
  4961. var i = 0;
  4962. for (; i < source.length; i++) {
  4963. event = source[i];
  4964. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4965. { break }
  4966. }
  4967. if (i == source.length) { return }
  4968. hist.lastOrigin = hist.lastSelOrigin = null;
  4969. for (; ;) {
  4970. event = source.pop();
  4971. if (event.ranges) {
  4972. pushSelectionToHistory(event, dest);
  4973. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4974. setSelection(doc, event, { clearRedo: false });
  4975. return
  4976. }
  4977. selAfter = event;
  4978. } else if (suppress) {
  4979. source.push(event);
  4980. return
  4981. } else { break }
  4982. }
  4983. // Build up a reverse change object to add to the opposite history
  4984. // stack (redo when undoing, and vice versa).
  4985. var antiChanges = [];
  4986. pushSelectionToHistory(selAfter, dest);
  4987. dest.push({ changes: antiChanges, generation: hist.generation });
  4988. hist.generation = event.generation || ++hist.maxGeneration;
  4989. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4990. var loop = function (i) {
  4991. var change = event.changes[i];
  4992. change.origin = type;
  4993. if (filter && !filterChange(doc, change, false)) {
  4994. source.length = 0;
  4995. return {}
  4996. }
  4997. antiChanges.push(historyChangeFromChange(doc, change));
  4998. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4999. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  5000. if (!i && doc.cm) { doc.cm.scrollIntoView({ from: change.from, to: changeEnd(change) }); }
  5001. var rebased = [];
  5002. // Propagate to the linked documents
  5003. linkedDocs(doc, function (doc, sharedHist) {
  5004. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5005. rebaseHist(doc.history, change);
  5006. rebased.push(doc.history);
  5007. }
  5008. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  5009. });
  5010. };
  5011. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  5012. var returned = loop(i$1);
  5013. if (returned) return returned.v;
  5014. }
  5015. }
  5016. // Sub-views need their line numbers shifted when text is added
  5017. // above or below them in the parent document.
  5018. function shiftDoc(doc, distance) {
  5019. if (distance == 0) { return }
  5020. doc.first += distance;
  5021. doc.sel = new Selection(map(doc.sel.ranges, function (range) {
  5022. return new Range(
  5023. Pos(range.anchor.line + distance, range.anchor.ch),
  5024. Pos(range.head.line + distance, range.head.ch)
  5025. );
  5026. }), doc.sel.primIndex);
  5027. if (doc.cm) {
  5028. regChange(doc.cm, doc.first, doc.first - distance, distance);
  5029. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  5030. { regLineChange(doc.cm, l, "gutter"); }
  5031. }
  5032. }
  5033. // More lower-level change function, handling only a single document
  5034. // (not linked ones).
  5035. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  5036. if (doc.cm && !doc.cm.curOp)
  5037. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  5038. if (change.to.line < doc.first) {
  5039. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  5040. return
  5041. }
  5042. if (change.from.line > doc.lastLine()) { return }
  5043. // Clip the change to the size of this doc
  5044. if (change.from.line < doc.first) {
  5045. var shift = change.text.length - 1 - (doc.first - change.from.line);
  5046. shiftDoc(doc, shift);
  5047. change = {
  5048. from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  5049. text: [lst(change.text)], origin: change.origin
  5050. };
  5051. }
  5052. var last = doc.lastLine();
  5053. if (change.to.line > last) {
  5054. change = {
  5055. from: change.from, to: Pos(last, getLine(doc, last).text.length),
  5056. text: [change.text[0]], origin: change.origin
  5057. };
  5058. }
  5059. change.removed = getBetween(doc, change.from, change.to);
  5060. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  5061. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  5062. else { updateDoc(doc, change, spans); }
  5063. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  5064. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  5065. { doc.cantEdit = false; }
  5066. }
  5067. // Handle the interaction of a change to a document with the editor
  5068. // that this document is part of.
  5069. function makeChangeSingleDocInEditor(cm, change, spans) {
  5070. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  5071. var recomputeMaxLength = false, checkWidthStart = from.line;
  5072. if (!cm.options.lineWrapping) {
  5073. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  5074. doc.iter(checkWidthStart, to.line + 1, function (line) {
  5075. if (line == display.maxLine) {
  5076. recomputeMaxLength = true;
  5077. return true
  5078. }
  5079. });
  5080. }
  5081. if (doc.sel.contains(change.from, change.to) > -1)
  5082. { signalCursorActivity(cm); }
  5083. updateDoc(doc, change, spans, estimateHeight(cm));
  5084. if (!cm.options.lineWrapping) {
  5085. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  5086. var len = lineLength(line);
  5087. if (len > display.maxLineLength) {
  5088. display.maxLine = line;
  5089. display.maxLineLength = len;
  5090. display.maxLineChanged = true;
  5091. recomputeMaxLength = false;
  5092. }
  5093. });
  5094. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  5095. }
  5096. retreatFrontier(doc, from.line);
  5097. startWorker(cm, 400);
  5098. var lendiff = change.text.length - (to.line - from.line) - 1;
  5099. // Remember that these lines changed, for updating the display
  5100. if (change.full)
  5101. { regChange(cm); }
  5102. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  5103. { regLineChange(cm, from.line, "text"); }
  5104. else
  5105. { regChange(cm, from.line, to.line + 1, lendiff); }
  5106. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  5107. if (changeHandler || changesHandler) {
  5108. var obj = {
  5109. from: from, to: to,
  5110. text: change.text,
  5111. removed: change.removed,
  5112. origin: change.origin
  5113. };
  5114. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  5115. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  5116. }
  5117. cm.display.selForContextMenu = null;
  5118. }
  5119. function replaceRange(doc, code, from, to, origin) {
  5120. var assign;
  5121. if (!to) { to = from; }
  5122. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  5123. if (typeof code == "string") { code = doc.splitLines(code); }
  5124. makeChange(doc, { from: from, to: to, text: code, origin: origin });
  5125. }
  5126. // Rebasing/resetting history to deal with externally-sourced changes
  5127. function rebaseHistSelSingle(pos, from, to, diff) {
  5128. if (to < pos.line) {
  5129. pos.line += diff;
  5130. } else if (from < pos.line) {
  5131. pos.line = from;
  5132. pos.ch = 0;
  5133. }
  5134. }
  5135. // Tries to rebase an array of history events given a change in the
  5136. // document. If the change touches the same lines as the event, the
  5137. // event, and everything 'behind' it, is discarded. If the change is
  5138. // before the event, the event's positions are updated. Uses a
  5139. // copy-on-write scheme for the positions, to avoid having to
  5140. // reallocate them all on every rebase, but also avoid problems with
  5141. // shared position objects being unsafely updated.
  5142. function rebaseHistArray(array, from, to, diff) {
  5143. for (var i = 0; i < array.length; ++i) {
  5144. var sub = array[i], ok = true;
  5145. if (sub.ranges) {
  5146. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  5147. for (var j = 0; j < sub.ranges.length; j++) {
  5148. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  5149. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  5150. }
  5151. continue
  5152. }
  5153. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  5154. var cur = sub.changes[j$1];
  5155. if (to < cur.from.line) {
  5156. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  5157. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  5158. } else if (from <= cur.to.line) {
  5159. ok = false;
  5160. break
  5161. }
  5162. }
  5163. if (!ok) {
  5164. array.splice(0, i + 1);
  5165. i = 0;
  5166. }
  5167. }
  5168. }
  5169. function rebaseHist(hist, change) {
  5170. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5171. rebaseHistArray(hist.done, from, to, diff);
  5172. rebaseHistArray(hist.undone, from, to, diff);
  5173. }
  5174. // Utility for applying a change to a line by handle or number,
  5175. // returning the number and optionally registering the line as
  5176. // changed.
  5177. function changeLine(doc, handle, changeType, op) {
  5178. var no = handle, line = handle;
  5179. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5180. else { no = lineNo(handle); }
  5181. if (no == null) { return null }
  5182. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5183. return line
  5184. }
  5185. // The document is represented as a BTree consisting of leaves, with
  5186. // chunk of lines in them, and branches, with up to ten leaves or
  5187. // other branch nodes below them. The top node is always a branch
  5188. // node, and is the document object itself (meaning it has
  5189. // additional methods and properties).
  5190. //
  5191. // All nodes have parent links. The tree is used both to go from
  5192. // line numbers to line objects, and to go from objects to numbers.
  5193. // It also indexes by height, and is used to convert between height
  5194. // and line object, and to find the total height of the document.
  5195. //
  5196. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5197. function LeafChunk(lines) {
  5198. this.lines = lines;
  5199. this.parent = null;
  5200. var height = 0;
  5201. for (var i = 0; i < lines.length; ++i) {
  5202. lines[i].parent = this;
  5203. height += lines[i].height;
  5204. }
  5205. this.height = height;
  5206. }
  5207. LeafChunk.prototype = {
  5208. chunkSize: function () { return this.lines.length },
  5209. // Remove the n lines at offset 'at'.
  5210. removeInner: function (at, n) {
  5211. for (var i = at, e = at + n; i < e; ++i) {
  5212. var line = this.lines[i];
  5213. this.height -= line.height;
  5214. cleanUpLine(line);
  5215. signalLater(line, "delete");
  5216. }
  5217. this.lines.splice(at, n);
  5218. },
  5219. // Helper used to collapse a small branch into a single leaf.
  5220. collapse: function (lines) {
  5221. lines.push.apply(lines, this.lines);
  5222. },
  5223. // Insert the given array of lines at offset 'at', count them as
  5224. // having the given height.
  5225. insertInner: function (at, lines, height) {
  5226. this.height += height;
  5227. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5228. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5229. },
  5230. // Used to iterate over a part of the tree.
  5231. iterN: function (at, n, op) {
  5232. for (var e = at + n; at < e; ++at)
  5233. { if (op(this.lines[at])) { return true } }
  5234. }
  5235. };
  5236. function BranchChunk(children) {
  5237. this.children = children;
  5238. var size = 0, height = 0;
  5239. for (var i = 0; i < children.length; ++i) {
  5240. var ch = children[i];
  5241. size += ch.chunkSize(); height += ch.height;
  5242. ch.parent = this;
  5243. }
  5244. this.size = size;
  5245. this.height = height;
  5246. this.parent = null;
  5247. }
  5248. BranchChunk.prototype = {
  5249. chunkSize: function () { return this.size },
  5250. removeInner: function (at, n) {
  5251. this.size -= n;
  5252. for (var i = 0; i < this.children.length; ++i) {
  5253. var child = this.children[i], sz = child.chunkSize();
  5254. if (at < sz) {
  5255. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5256. child.removeInner(at, rm);
  5257. this.height -= oldHeight - child.height;
  5258. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5259. if ((n -= rm) == 0) { break }
  5260. at = 0;
  5261. } else { at -= sz; }
  5262. }
  5263. // If the result is smaller than 25 lines, ensure that it is a
  5264. // single leaf node.
  5265. if (this.size - n < 25 &&
  5266. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5267. var lines = [];
  5268. this.collapse(lines);
  5269. this.children = [new LeafChunk(lines)];
  5270. this.children[0].parent = this;
  5271. }
  5272. },
  5273. collapse: function (lines) {
  5274. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5275. },
  5276. insertInner: function (at, lines, height) {
  5277. this.size += lines.length;
  5278. this.height += height;
  5279. for (var i = 0; i < this.children.length; ++i) {
  5280. var child = this.children[i], sz = child.chunkSize();
  5281. if (at <= sz) {
  5282. child.insertInner(at, lines, height);
  5283. if (child.lines && child.lines.length > 50) {
  5284. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5285. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5286. var remaining = child.lines.length % 25 + 25;
  5287. for (var pos = remaining; pos < child.lines.length;) {
  5288. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5289. child.height -= leaf.height;
  5290. this.children.splice(++i, 0, leaf);
  5291. leaf.parent = this;
  5292. }
  5293. child.lines = child.lines.slice(0, remaining);
  5294. this.maybeSpill();
  5295. }
  5296. break
  5297. }
  5298. at -= sz;
  5299. }
  5300. },
  5301. // When a node has grown, check whether it should be split.
  5302. maybeSpill: function () {
  5303. if (this.children.length <= 10) { return }
  5304. var me = this;
  5305. do {
  5306. var spilled = me.children.splice(me.children.length - 5, 5);
  5307. var sibling = new BranchChunk(spilled);
  5308. if (!me.parent) { // Become the parent node
  5309. var copy = new BranchChunk(me.children);
  5310. copy.parent = me;
  5311. me.children = [copy, sibling];
  5312. me = copy;
  5313. } else {
  5314. me.size -= sibling.size;
  5315. me.height -= sibling.height;
  5316. var myIndex = indexOf(me.parent.children, me);
  5317. me.parent.children.splice(myIndex + 1, 0, sibling);
  5318. }
  5319. sibling.parent = me.parent;
  5320. } while (me.children.length > 10)
  5321. me.parent.maybeSpill();
  5322. },
  5323. iterN: function (at, n, op) {
  5324. for (var i = 0; i < this.children.length; ++i) {
  5325. var child = this.children[i], sz = child.chunkSize();
  5326. if (at < sz) {
  5327. var used = Math.min(n, sz - at);
  5328. if (child.iterN(at, used, op)) { return true }
  5329. if ((n -= used) == 0) { break }
  5330. at = 0;
  5331. } else { at -= sz; }
  5332. }
  5333. }
  5334. };
  5335. // Line widgets are block elements displayed above or below a line.
  5336. var LineWidget = function (doc, node, options) {
  5337. if (options) {
  5338. for (var opt in options) {
  5339. if (options.hasOwnProperty(opt))
  5340. { this[opt] = options[opt]; }
  5341. }
  5342. }
  5343. this.doc = doc;
  5344. this.node = node;
  5345. };
  5346. LineWidget.prototype.clear = function () {
  5347. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5348. if (no == null || !ws) { return }
  5349. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5350. if (!ws.length) { line.widgets = null; }
  5351. var height = widgetHeight(this);
  5352. updateLineHeight(line, Math.max(0, line.height - height));
  5353. if (cm) {
  5354. runInOp(cm, function () {
  5355. adjustScrollWhenAboveVisible(cm, line, -height);
  5356. regLineChange(cm, no, "widget");
  5357. });
  5358. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5359. }
  5360. };
  5361. LineWidget.prototype.changed = function () {
  5362. var this$1 = this;
  5363. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5364. this.height = null;
  5365. var diff = widgetHeight(this) - oldH;
  5366. if (!diff) { return }
  5367. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5368. if (cm) {
  5369. runInOp(cm, function () {
  5370. cm.curOp.forceUpdate = true;
  5371. adjustScrollWhenAboveVisible(cm, line, diff);
  5372. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5373. });
  5374. }
  5375. };
  5376. eventMixin(LineWidget);
  5377. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5378. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5379. { addToScrollTop(cm, diff); }
  5380. }
  5381. function addLineWidget(doc, handle, node, options) {
  5382. var widget = new LineWidget(doc, node, options);
  5383. var cm = doc.cm;
  5384. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5385. changeLine(doc, handle, "widget", function (line) {
  5386. var widgets = line.widgets || (line.widgets = []);
  5387. if (widget.insertAt == null) { widgets.push(widget); }
  5388. else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  5389. widget.line = line;
  5390. if (cm && !lineIsHidden(doc, line)) {
  5391. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5392. updateLineHeight(line, line.height + widgetHeight(widget));
  5393. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5394. cm.curOp.forceUpdate = true;
  5395. }
  5396. return true
  5397. });
  5398. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5399. return widget
  5400. }
  5401. // TEXTMARKERS
  5402. // Created with markText and setBookmark methods. A TextMarker is a
  5403. // handle that can be used to clear or find a marked position in the
  5404. // document. Line objects hold arrays (markedSpans) containing
  5405. // {from, to, marker} object pointing to such marker objects, and
  5406. // indicating that such a marker is present on that line. Multiple
  5407. // lines may point to the same marker when it spans across lines.
  5408. // The spans will have null for their from/to properties when the
  5409. // marker continues beyond the start/end of the line. Markers have
  5410. // links back to the lines they currently touch.
  5411. // Collapsed markers have unique ids, in order to be able to order
  5412. // them, which is needed for uniquely determining an outer marker
  5413. // when they overlap (they may nest, but not partially overlap).
  5414. var nextMarkerId = 0;
  5415. var TextMarker = function (doc, type) {
  5416. this.lines = [];
  5417. this.type = type;
  5418. this.doc = doc;
  5419. this.id = ++nextMarkerId;
  5420. };
  5421. // Clear the marker.
  5422. TextMarker.prototype.clear = function () {
  5423. if (this.explicitlyCleared) { return }
  5424. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5425. if (withOp) { startOperation(cm); }
  5426. if (hasHandler(this, "clear")) {
  5427. var found = this.find();
  5428. if (found) { signalLater(this, "clear", found.from, found.to); }
  5429. }
  5430. var min = null, max = null;
  5431. for (var i = 0; i < this.lines.length; ++i) {
  5432. var line = this.lines[i];
  5433. var span = getMarkedSpanFor(line.markedSpans, this);
  5434. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5435. else if (cm) {
  5436. if (span.to != null) { max = lineNo(line); }
  5437. if (span.from != null) { min = lineNo(line); }
  5438. }
  5439. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5440. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5441. { updateLineHeight(line, textHeight(cm.display)); }
  5442. }
  5443. if (cm && this.collapsed && !cm.options.lineWrapping) {
  5444. for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5445. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5446. if (len > cm.display.maxLineLength) {
  5447. cm.display.maxLine = visual;
  5448. cm.display.maxLineLength = len;
  5449. cm.display.maxLineChanged = true;
  5450. }
  5451. }
  5452. }
  5453. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5454. this.lines.length = 0;
  5455. this.explicitlyCleared = true;
  5456. if (this.atomic && this.doc.cantEdit) {
  5457. this.doc.cantEdit = false;
  5458. if (cm) { reCheckSelection(cm.doc); }
  5459. }
  5460. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5461. if (withOp) { endOperation(cm); }
  5462. if (this.parent) { this.parent.clear(); }
  5463. };
  5464. // Find the position of the marker in the document. Returns a {from,
  5465. // to} object by default. Side can be passed to get a specific side
  5466. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5467. // Pos objects returned contain a line object, rather than a line
  5468. // number (used to prevent looking up the same line twice).
  5469. TextMarker.prototype.find = function (side, lineObj) {
  5470. if (side == null && this.type == "bookmark") { side = 1; }
  5471. var from, to;
  5472. for (var i = 0; i < this.lines.length; ++i) {
  5473. var line = this.lines[i];
  5474. var span = getMarkedSpanFor(line.markedSpans, this);
  5475. if (span.from != null) {
  5476. from = Pos(lineObj ? line : lineNo(line), span.from);
  5477. if (side == -1) { return from }
  5478. }
  5479. if (span.to != null) {
  5480. to = Pos(lineObj ? line : lineNo(line), span.to);
  5481. if (side == 1) { return to }
  5482. }
  5483. }
  5484. return from && { from: from, to: to }
  5485. };
  5486. // Signals that the marker's widget changed, and surrounding layout
  5487. // should be recomputed.
  5488. TextMarker.prototype.changed = function () {
  5489. var this$1 = this;
  5490. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5491. if (!pos || !cm) { return }
  5492. runInOp(cm, function () {
  5493. var line = pos.line, lineN = lineNo(pos.line);
  5494. var view = findViewForLine(cm, lineN);
  5495. if (view) {
  5496. clearLineMeasurementCacheFor(view);
  5497. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5498. }
  5499. cm.curOp.updateMaxLine = true;
  5500. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5501. var oldHeight = widget.height;
  5502. widget.height = null;
  5503. var dHeight = widgetHeight(widget) - oldHeight;
  5504. if (dHeight)
  5505. { updateLineHeight(line, line.height + dHeight); }
  5506. }
  5507. signalLater(cm, "markerChanged", cm, this$1);
  5508. });
  5509. };
  5510. TextMarker.prototype.attachLine = function (line) {
  5511. if (!this.lines.length && this.doc.cm) {
  5512. var op = this.doc.cm.curOp;
  5513. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5514. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5515. }
  5516. this.lines.push(line);
  5517. };
  5518. TextMarker.prototype.detachLine = function (line) {
  5519. this.lines.splice(indexOf(this.lines, line), 1);
  5520. if (!this.lines.length && this.doc.cm) {
  5521. var op = this.doc.cm.curOp
  5522. ; (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5523. }
  5524. };
  5525. eventMixin(TextMarker);
  5526. // Create a marker, wire it up to the right lines, and
  5527. function markText(doc, from, to, options, type) {
  5528. // Shared markers (across linked documents) are handled separately
  5529. // (markTextShared will call out to this again, once per
  5530. // document).
  5531. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5532. // Ensure we are in an operation.
  5533. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5534. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5535. if (options) { copyObj(options, marker, false); }
  5536. // Don't connect empty markers unless clearWhenEmpty is false
  5537. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5538. { return marker }
  5539. if (marker.replacedWith) {
  5540. // Showing up as a widget implies collapsed (widget replaces text)
  5541. marker.collapsed = true;
  5542. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5543. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5544. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5545. }
  5546. if (marker.collapsed) {
  5547. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5548. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5549. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5550. seeCollapsedSpans();
  5551. }
  5552. if (marker.addToHistory)
  5553. { addChangeToHistory(doc, { from: from, to: to, origin: "markText" }, doc.sel, NaN); }
  5554. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5555. doc.iter(curLine, to.line + 1, function (line) {
  5556. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5557. { updateMaxLine = true; }
  5558. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5559. addMarkedSpan(line, new MarkedSpan(marker,
  5560. curLine == from.line ? from.ch : null,
  5561. curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
  5562. ++curLine;
  5563. });
  5564. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5565. if (marker.collapsed) {
  5566. doc.iter(from.line, to.line + 1, function (line) {
  5567. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5568. });
  5569. }
  5570. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5571. if (marker.readOnly) {
  5572. seeReadOnlySpans();
  5573. if (doc.history.done.length || doc.history.undone.length)
  5574. { doc.clearHistory(); }
  5575. }
  5576. if (marker.collapsed) {
  5577. marker.id = ++nextMarkerId;
  5578. marker.atomic = true;
  5579. }
  5580. if (cm) {
  5581. // Sync editor state
  5582. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5583. if (marker.collapsed)
  5584. { regChange(cm, from.line, to.line + 1); }
  5585. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5586. marker.attributes || marker.title)
  5587. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5588. if (marker.atomic) { reCheckSelection(cm.doc); }
  5589. signalLater(cm, "markerAdded", cm, marker);
  5590. }
  5591. return marker
  5592. }
  5593. // SHARED TEXTMARKERS
  5594. // A shared marker spans multiple linked documents. It is
  5595. // implemented as a meta-marker-object controlling multiple normal
  5596. // markers.
  5597. var SharedTextMarker = function (markers, primary) {
  5598. this.markers = markers;
  5599. this.primary = primary;
  5600. for (var i = 0; i < markers.length; ++i)
  5601. { markers[i].parent = this; }
  5602. };
  5603. SharedTextMarker.prototype.clear = function () {
  5604. if (this.explicitlyCleared) { return }
  5605. this.explicitlyCleared = true;
  5606. for (var i = 0; i < this.markers.length; ++i)
  5607. { this.markers[i].clear(); }
  5608. signalLater(this, "clear");
  5609. };
  5610. SharedTextMarker.prototype.find = function (side, lineObj) {
  5611. return this.primary.find(side, lineObj)
  5612. };
  5613. eventMixin(SharedTextMarker);
  5614. function markTextShared(doc, from, to, options, type) {
  5615. options = copyObj(options);
  5616. options.shared = false;
  5617. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5618. var widget = options.widgetNode;
  5619. linkedDocs(doc, function (doc) {
  5620. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5621. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5622. for (var i = 0; i < doc.linked.length; ++i)
  5623. { if (doc.linked[i].isParent) { return } }
  5624. primary = lst(markers);
  5625. });
  5626. return new SharedTextMarker(markers, primary)
  5627. }
  5628. function findSharedMarkers(doc) {
  5629. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5630. }
  5631. function copySharedMarkers(doc, markers) {
  5632. for (var i = 0; i < markers.length; i++) {
  5633. var marker = markers[i], pos = marker.find();
  5634. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5635. if (cmp(mFrom, mTo)) {
  5636. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5637. marker.markers.push(subMark);
  5638. subMark.parent = marker;
  5639. }
  5640. }
  5641. }
  5642. function detachSharedMarkers(markers) {
  5643. var loop = function (i) {
  5644. var marker = markers[i], linked = [marker.primary.doc];
  5645. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5646. for (var j = 0; j < marker.markers.length; j++) {
  5647. var subMarker = marker.markers[j];
  5648. if (indexOf(linked, subMarker.doc) == -1) {
  5649. subMarker.parent = null;
  5650. marker.markers.splice(j--, 1);
  5651. }
  5652. }
  5653. };
  5654. for (var i = 0; i < markers.length; i++) loop(i);
  5655. }
  5656. var nextDocId = 0;
  5657. var Doc = function (text, mode, firstLine, lineSep, direction) {
  5658. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5659. if (firstLine == null) { firstLine = 0; }
  5660. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5661. this.first = firstLine;
  5662. this.scrollTop = this.scrollLeft = 0;
  5663. this.cantEdit = false;
  5664. this.cleanGeneration = 1;
  5665. this.modeFrontier = this.highlightFrontier = firstLine;
  5666. var start = Pos(firstLine, 0);
  5667. this.sel = simpleSelection(start);
  5668. this.history = new History(null);
  5669. this.id = ++nextDocId;
  5670. this.modeOption = mode;
  5671. this.lineSep = lineSep;
  5672. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5673. this.extend = false;
  5674. if (typeof text == "string") { text = this.splitLines(text); }
  5675. updateDoc(this, { from: start, to: start, text: text });
  5676. setSelection(this, simpleSelection(start), sel_dontScroll);
  5677. };
  5678. Doc.prototype = createObj(BranchChunk.prototype, {
  5679. constructor: Doc,
  5680. // Iterate over the document. Supports two forms -- with only one
  5681. // argument, it calls that for each line in the document. With
  5682. // three, it iterates over the range given by the first two (with
  5683. // the second being non-inclusive).
  5684. iter: function (from, to, op) {
  5685. if (op) { this.iterN(from - this.first, to - from, op); }
  5686. else { this.iterN(this.first, this.first + this.size, from); }
  5687. },
  5688. // Non-public interface for adding and removing lines.
  5689. insert: function (at, lines) {
  5690. var height = 0;
  5691. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5692. this.insertInner(at - this.first, lines, height);
  5693. },
  5694. remove: function (at, n) { this.removeInner(at - this.first, n); },
  5695. // From here, the methods are part of the public interface. Most
  5696. // are also available from CodeMirror (editor) instances.
  5697. getValue: function (lineSep) {
  5698. var lines = getLines(this, this.first, this.first + this.size);
  5699. if (lineSep === false) { return lines }
  5700. return lines.join(lineSep || this.lineSeparator())
  5701. },
  5702. setValue: docMethodOp(function (code) {
  5703. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5704. makeChange(this, {
  5705. from: top, to: Pos(last, getLine(this, last).text.length),
  5706. text: this.splitLines(code), origin: "setValue", full: true
  5707. }, true);
  5708. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5709. setSelection(this, simpleSelection(top), sel_dontScroll);
  5710. }),
  5711. replaceRange: function (code, from, to, origin) {
  5712. from = clipPos(this, from);
  5713. to = to ? clipPos(this, to) : from;
  5714. replaceRange(this, code, from, to, origin);
  5715. },
  5716. getRange: function (from, to, lineSep) {
  5717. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5718. if (lineSep === false) { return lines }
  5719. if (lineSep === '') { return lines.join('') }
  5720. return lines.join(lineSep || this.lineSeparator())
  5721. },
  5722. getLine: function (line) { var l = this.getLineHandle(line); return l && l.text },
  5723. getLineHandle: function (line) { if (isLine(this, line)) { return getLine(this, line) } },
  5724. getLineNumber: function (line) { return lineNo(line) },
  5725. getLineHandleVisualStart: function (line) {
  5726. if (typeof line == "number") { line = getLine(this, line); }
  5727. return visualLine(line)
  5728. },
  5729. lineCount: function () { return this.size },
  5730. firstLine: function () { return this.first },
  5731. lastLine: function () { return this.first + this.size - 1 },
  5732. clipPos: function (pos) { return clipPos(this, pos) },
  5733. getCursor: function (start) {
  5734. var range = this.sel.primary(), pos;
  5735. if (start == null || start == "head") { pos = range.head; }
  5736. else if (start == "anchor") { pos = range.anchor; }
  5737. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  5738. else { pos = range.from(); }
  5739. return pos
  5740. },
  5741. listSelections: function () { return this.sel.ranges },
  5742. somethingSelected: function () { return this.sel.somethingSelected() },
  5743. setCursor: docMethodOp(function (line, ch, options) {
  5744. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5745. }),
  5746. setSelection: docMethodOp(function (anchor, head, options) {
  5747. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5748. }),
  5749. extendSelection: docMethodOp(function (head, other, options) {
  5750. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5751. }),
  5752. extendSelections: docMethodOp(function (heads, options) {
  5753. extendSelections(this, clipPosArray(this, heads), options);
  5754. }),
  5755. extendSelectionsBy: docMethodOp(function (f, options) {
  5756. var heads = map(this.sel.ranges, f);
  5757. extendSelections(this, clipPosArray(this, heads), options);
  5758. }),
  5759. setSelections: docMethodOp(function (ranges, primary, options) {
  5760. if (!ranges.length) { return }
  5761. var out = [];
  5762. for (var i = 0; i < ranges.length; i++) {
  5763. out[i] = new Range(clipPos(this, ranges[i].anchor),
  5764. clipPos(this, ranges[i].head || ranges[i].anchor));
  5765. }
  5766. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5767. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5768. }),
  5769. addSelection: docMethodOp(function (anchor, head, options) {
  5770. var ranges = this.sel.ranges.slice(0);
  5771. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5772. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5773. }),
  5774. getSelection: function (lineSep) {
  5775. var ranges = this.sel.ranges, lines;
  5776. for (var i = 0; i < ranges.length; i++) {
  5777. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5778. lines = lines ? lines.concat(sel) : sel;
  5779. }
  5780. if (lineSep === false) { return lines }
  5781. else { return lines.join(lineSep || this.lineSeparator()) }
  5782. },
  5783. getSelections: function (lineSep) {
  5784. var parts = [], ranges = this.sel.ranges;
  5785. for (var i = 0; i < ranges.length; i++) {
  5786. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5787. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  5788. parts[i] = sel;
  5789. }
  5790. return parts
  5791. },
  5792. replaceSelection: function (code, collapse, origin) {
  5793. var dup = [];
  5794. for (var i = 0; i < this.sel.ranges.length; i++)
  5795. { dup[i] = code; }
  5796. this.replaceSelections(dup, collapse, origin || "+input");
  5797. },
  5798. replaceSelections: docMethodOp(function (code, collapse, origin) {
  5799. var changes = [], sel = this.sel;
  5800. for (var i = 0; i < sel.ranges.length; i++) {
  5801. var range = sel.ranges[i];
  5802. changes[i] = { from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin };
  5803. }
  5804. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5805. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5806. { makeChange(this, changes[i$1]); }
  5807. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5808. else if (this.cm) { ensureCursorVisible(this.cm); }
  5809. }),
  5810. undo: docMethodOp(function () { makeChangeFromHistory(this, "undo"); }),
  5811. redo: docMethodOp(function () { makeChangeFromHistory(this, "redo"); }),
  5812. undoSelection: docMethodOp(function () { makeChangeFromHistory(this, "undo", true); }),
  5813. redoSelection: docMethodOp(function () { makeChangeFromHistory(this, "redo", true); }),
  5814. setExtending: function (val) { this.extend = val; },
  5815. getExtending: function () { return this.extend },
  5816. historySize: function () {
  5817. var hist = this.history, done = 0, undone = 0;
  5818. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5819. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5820. return { undo: done, redo: undone }
  5821. },
  5822. clearHistory: function () {
  5823. var this$1 = this;
  5824. this.history = new History(this.history);
  5825. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  5826. },
  5827. markClean: function () {
  5828. this.cleanGeneration = this.changeGeneration(true);
  5829. },
  5830. changeGeneration: function (forceSplit) {
  5831. if (forceSplit)
  5832. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5833. return this.history.generation
  5834. },
  5835. isClean: function (gen) {
  5836. return this.history.generation == (gen || this.cleanGeneration)
  5837. },
  5838. getHistory: function () {
  5839. return {
  5840. done: copyHistoryArray(this.history.done),
  5841. undone: copyHistoryArray(this.history.undone)
  5842. }
  5843. },
  5844. setHistory: function (histData) {
  5845. var hist = this.history = new History(this.history);
  5846. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5847. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5848. },
  5849. setGutterMarker: docMethodOp(function (line, gutterID, value) {
  5850. return changeLine(this, line, "gutter", function (line) {
  5851. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5852. markers[gutterID] = value;
  5853. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5854. return true
  5855. })
  5856. }),
  5857. clearGutter: docMethodOp(function (gutterID) {
  5858. var this$1 = this;
  5859. this.iter(function (line) {
  5860. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5861. changeLine(this$1, line, "gutter", function () {
  5862. line.gutterMarkers[gutterID] = null;
  5863. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5864. return true
  5865. });
  5866. }
  5867. });
  5868. }),
  5869. lineInfo: function (line) {
  5870. var n;
  5871. if (typeof line == "number") {
  5872. if (!isLine(this, line)) { return null }
  5873. n = line;
  5874. line = getLine(this, line);
  5875. if (!line) { return null }
  5876. } else {
  5877. n = lineNo(line);
  5878. if (n == null) { return null }
  5879. }
  5880. return {
  5881. line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5882. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5883. widgets: line.widgets
  5884. }
  5885. },
  5886. addLineClass: docMethodOp(function (handle, where, cls) {
  5887. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5888. var prop = where == "text" ? "textClass"
  5889. : where == "background" ? "bgClass"
  5890. : where == "gutter" ? "gutterClass" : "wrapClass";
  5891. if (!line[prop]) { line[prop] = cls; }
  5892. else if (classTest(cls).test(line[prop])) { return false }
  5893. else { line[prop] += " " + cls; }
  5894. return true
  5895. })
  5896. }),
  5897. removeLineClass: docMethodOp(function (handle, where, cls) {
  5898. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5899. var prop = where == "text" ? "textClass"
  5900. : where == "background" ? "bgClass"
  5901. : where == "gutter" ? "gutterClass" : "wrapClass";
  5902. var cur = line[prop];
  5903. if (!cur) { return false }
  5904. else if (cls == null) { line[prop] = null; }
  5905. else {
  5906. var found = cur.match(classTest(cls));
  5907. if (!found) { return false }
  5908. var end = found.index + found[0].length;
  5909. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5910. }
  5911. return true
  5912. })
  5913. }),
  5914. addLineWidget: docMethodOp(function (handle, node, options) {
  5915. return addLineWidget(this, handle, node, options)
  5916. }),
  5917. removeLineWidget: function (widget) { widget.clear(); },
  5918. markText: function (from, to, options) {
  5919. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5920. },
  5921. setBookmark: function (pos, options) {
  5922. var realOpts = {
  5923. replacedWith: options && (options.nodeType == null ? options.widget : options),
  5924. insertLeft: options && options.insertLeft,
  5925. clearWhenEmpty: false, shared: options && options.shared,
  5926. handleMouseEvents: options && options.handleMouseEvents
  5927. };
  5928. pos = clipPos(this, pos);
  5929. return markText(this, pos, pos, realOpts, "bookmark")
  5930. },
  5931. findMarksAt: function (pos) {
  5932. pos = clipPos(this, pos);
  5933. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5934. if (spans) {
  5935. for (var i = 0; i < spans.length; ++i) {
  5936. var span = spans[i];
  5937. if ((span.from == null || span.from <= pos.ch) &&
  5938. (span.to == null || span.to >= pos.ch))
  5939. { markers.push(span.marker.parent || span.marker); }
  5940. }
  5941. }
  5942. return markers
  5943. },
  5944. findMarks: function (from, to, filter) {
  5945. from = clipPos(this, from); to = clipPos(this, to);
  5946. var found = [], lineNo = from.line;
  5947. this.iter(from.line, to.line + 1, function (line) {
  5948. var spans = line.markedSpans;
  5949. if (spans) {
  5950. for (var i = 0; i < spans.length; i++) {
  5951. var span = spans[i];
  5952. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5953. span.from == null && lineNo != from.line ||
  5954. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5955. (!filter || filter(span.marker)))
  5956. { found.push(span.marker.parent || span.marker); }
  5957. }
  5958. }
  5959. ++lineNo;
  5960. });
  5961. return found
  5962. },
  5963. getAllMarks: function () {
  5964. var markers = [];
  5965. this.iter(function (line) {
  5966. var sps = line.markedSpans;
  5967. if (sps) {
  5968. for (var i = 0; i < sps.length; ++i)
  5969. { if (sps[i].from != null) { markers.push(sps[i].marker); } }
  5970. }
  5971. });
  5972. return markers
  5973. },
  5974. posFromIndex: function (off) {
  5975. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  5976. this.iter(function (line) {
  5977. var sz = line.text.length + sepSize;
  5978. if (sz > off) { ch = off; return true }
  5979. off -= sz;
  5980. ++lineNo;
  5981. });
  5982. return clipPos(this, Pos(lineNo, ch))
  5983. },
  5984. indexFromPos: function (coords) {
  5985. coords = clipPos(this, coords);
  5986. var index = coords.ch;
  5987. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5988. var sepSize = this.lineSeparator().length;
  5989. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5990. index += line.text.length + sepSize;
  5991. });
  5992. return index
  5993. },
  5994. copy: function (copyHistory) {
  5995. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5996. this.modeOption, this.first, this.lineSep, this.direction);
  5997. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5998. doc.sel = this.sel;
  5999. doc.extend = false;
  6000. if (copyHistory) {
  6001. doc.history.undoDepth = this.history.undoDepth;
  6002. doc.setHistory(this.getHistory());
  6003. }
  6004. return doc
  6005. },
  6006. linkedDoc: function (options) {
  6007. if (!options) { options = {}; }
  6008. var from = this.first, to = this.first + this.size;
  6009. if (options.from != null && options.from > from) { from = options.from; }
  6010. if (options.to != null && options.to < to) { to = options.to; }
  6011. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  6012. if (options.sharedHist) {
  6013. copy.history = this.history
  6014. ;
  6015. } (this.linked || (this.linked = [])).push({ doc: copy, sharedHist: options.sharedHist });
  6016. copy.linked = [{ doc: this, isParent: true, sharedHist: options.sharedHist }];
  6017. copySharedMarkers(copy, findSharedMarkers(this));
  6018. return copy
  6019. },
  6020. unlinkDoc: function (other) {
  6021. if (other instanceof CodeMirror) { other = other.doc; }
  6022. if (this.linked) {
  6023. for (var i = 0; i < this.linked.length; ++i) {
  6024. var link = this.linked[i];
  6025. if (link.doc != other) { continue }
  6026. this.linked.splice(i, 1);
  6027. other.unlinkDoc(this);
  6028. detachSharedMarkers(findSharedMarkers(this));
  6029. break
  6030. }
  6031. }
  6032. // If the histories were shared, split them again
  6033. if (other.history == this.history) {
  6034. var splitIds = [other.id];
  6035. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  6036. other.history = new History(null);
  6037. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6038. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6039. }
  6040. },
  6041. iterLinkedDocs: function (f) { linkedDocs(this, f); },
  6042. getMode: function () { return this.mode },
  6043. getEditor: function () { return this.cm },
  6044. splitLines: function (str) {
  6045. if (this.lineSep) { return str.split(this.lineSep) }
  6046. return splitLinesAuto(str)
  6047. },
  6048. lineSeparator: function () { return this.lineSep || "\n" },
  6049. setDirection: docMethodOp(function (dir) {
  6050. if (dir != "rtl") { dir = "ltr"; }
  6051. if (dir == this.direction) { return }
  6052. this.direction = dir;
  6053. this.iter(function (line) { return line.order = null; });
  6054. if (this.cm) { directionChanged(this.cm); }
  6055. })
  6056. });
  6057. // Public alias.
  6058. Doc.prototype.eachLine = Doc.prototype.iter;
  6059. // Kludge to work around strange IE behavior where it'll sometimes
  6060. // re-fire a series of drag-related events right after the drop (#1551)
  6061. var lastDrop = 0;
  6062. function onDrop(e) {
  6063. var cm = this;
  6064. clearDragCursor(cm);
  6065. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  6066. { return }
  6067. e_preventDefault(e);
  6068. if (ie) { lastDrop = +new Date; }
  6069. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  6070. if (!pos || cm.isReadOnly()) { return }
  6071. // Might be a file drop, in which case we simply extract the text
  6072. // and insert it.
  6073. if (files && files.length && window.FileReader && window.File) {
  6074. var n = files.length, text = Array(n), read = 0;
  6075. var markAsReadAndPasteIfAllFilesAreRead = function () {
  6076. if (++read == n) {
  6077. operation(cm, function () {
  6078. pos = clipPos(cm.doc, pos);
  6079. var change = {
  6080. from: pos, to: pos,
  6081. text: cm.doc.splitLines(
  6082. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  6083. origin: "paste"
  6084. };
  6085. makeChange(cm.doc, change);
  6086. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  6087. })();
  6088. }
  6089. };
  6090. var readTextFromFile = function (file, i) {
  6091. if (cm.options.allowDropFileTypes &&
  6092. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  6093. markAsReadAndPasteIfAllFilesAreRead();
  6094. return
  6095. }
  6096. var reader = new FileReader;
  6097. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  6098. reader.onload = function () {
  6099. var content = reader.result;
  6100. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  6101. markAsReadAndPasteIfAllFilesAreRead();
  6102. return
  6103. }
  6104. text[i] = content;
  6105. markAsReadAndPasteIfAllFilesAreRead();
  6106. };
  6107. reader.readAsText(file);
  6108. };
  6109. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  6110. } else { // Normal drop
  6111. // Don't do a replace if the drop happened inside of the selected text.
  6112. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  6113. cm.state.draggingText(e);
  6114. // Ensure the editor is re-focused
  6115. setTimeout(function () { return cm.display.input.focus(); }, 20);
  6116. return
  6117. }
  6118. try {
  6119. var text$1 = e.dataTransfer.getData("Text");
  6120. if (text$1) {
  6121. var selected;
  6122. if (cm.state.draggingText && !cm.state.draggingText.copy)
  6123. { selected = cm.listSelections(); }
  6124. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  6125. if (selected) {
  6126. for (var i$1 = 0; i$1 < selected.length; ++i$1)
  6127. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); }
  6128. }
  6129. cm.replaceSelection(text$1, "around", "paste");
  6130. cm.display.input.focus();
  6131. }
  6132. }
  6133. catch (e$1) { }
  6134. }
  6135. }
  6136. function onDragStart(cm, e) {
  6137. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  6138. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  6139. e.dataTransfer.setData("Text", cm.getSelection());
  6140. e.dataTransfer.effectAllowed = "copyMove";
  6141. // Use dummy image instead of default browsers image.
  6142. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  6143. if (e.dataTransfer.setDragImage && !safari) {
  6144. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  6145. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  6146. if (presto) {
  6147. img.width = img.height = 1;
  6148. cm.display.wrapper.appendChild(img);
  6149. // Force a relayout, or Opera won't use our image for some obscure reason
  6150. img._top = img.offsetTop;
  6151. }
  6152. e.dataTransfer.setDragImage(img, 0, 0);
  6153. if (presto) { img.parentNode.removeChild(img); }
  6154. }
  6155. }
  6156. function onDragOver(cm, e) {
  6157. var pos = posFromMouse(cm, e);
  6158. if (!pos) { return }
  6159. var frag = document.createDocumentFragment();
  6160. drawSelectionCursor(cm, pos, frag);
  6161. if (!cm.display.dragCursor) {
  6162. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  6163. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  6164. }
  6165. removeChildrenAndAdd(cm.display.dragCursor, frag);
  6166. }
  6167. function clearDragCursor(cm) {
  6168. if (cm.display.dragCursor) {
  6169. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  6170. cm.display.dragCursor = null;
  6171. }
  6172. }
  6173. // These must be handled carefully, because naively registering a
  6174. // handler for each editor will cause the editors to never be
  6175. // garbage collected.
  6176. function forEachCodeMirror(f) {
  6177. if (!document.getElementsByClassName) { return }
  6178. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  6179. for (var i = 0; i < byClass.length; i++) {
  6180. var cm = byClass[i].CodeMirror;
  6181. if (cm) { editors.push(cm); }
  6182. }
  6183. if (editors.length) {
  6184. editors[0].operation(function () {
  6185. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  6186. });
  6187. }
  6188. }
  6189. var globalsRegistered = false;
  6190. function ensureGlobalHandlers() {
  6191. if (globalsRegistered) { return }
  6192. registerGlobalHandlers();
  6193. globalsRegistered = true;
  6194. }
  6195. function registerGlobalHandlers() {
  6196. // When the window resizes, we need to refresh active editors.
  6197. var resizeTimer;
  6198. on(window, "resize", function () {
  6199. if (resizeTimer == null) {
  6200. resizeTimer = setTimeout(function () {
  6201. resizeTimer = null;
  6202. forEachCodeMirror(onResize);
  6203. }, 100);
  6204. }
  6205. });
  6206. // When the window loses focus, we want to show the editor as blurred
  6207. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6208. }
  6209. // Called when the window resizes
  6210. function onResize(cm) {
  6211. var d = cm.display;
  6212. // Might be a text scaling operation, clear size caches.
  6213. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6214. d.scrollbarsClipped = false;
  6215. cm.setSize();
  6216. }
  6217. var keyNames = {
  6218. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6219. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6220. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6221. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6222. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6223. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6224. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6225. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6226. };
  6227. // Number keys
  6228. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6229. // Alphabetic keys
  6230. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6231. // Function keys
  6232. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6233. var keyMap = {};
  6234. keyMap.basic = {
  6235. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6236. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6237. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6238. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6239. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6240. "Esc": "singleSelection"
  6241. };
  6242. // Note that the save and find-related commands aren't defined by
  6243. // default. User code or addons can define them. Unknown commands
  6244. // are simply ignored.
  6245. keyMap.pcDefault = {
  6246. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6247. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6248. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6249. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6250. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6251. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6252. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6253. "fallthrough": "basic"
  6254. };
  6255. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6256. keyMap.emacsy = {
  6257. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6258. "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
  6259. "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
  6260. "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  6261. };
  6262. keyMap.macDefault = {
  6263. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6264. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6265. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6266. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6267. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6268. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6269. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6270. "fallthrough": ["basic", "emacsy"]
  6271. };
  6272. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6273. // KEYMAP DISPATCH
  6274. function normalizeKeyName(name) {
  6275. var parts = name.split(/-(?!$)/);
  6276. name = parts[parts.length - 1];
  6277. var alt, ctrl, shift, cmd;
  6278. for (var i = 0; i < parts.length - 1; i++) {
  6279. var mod = parts[i];
  6280. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6281. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6282. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6283. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6284. else { throw new Error("Unrecognized modifier name: " + mod) }
  6285. }
  6286. if (alt) { name = "Alt-" + name; }
  6287. if (ctrl) { name = "Ctrl-" + name; }
  6288. if (cmd) { name = "Cmd-" + name; }
  6289. if (shift) { name = "Shift-" + name; }
  6290. return name
  6291. }
  6292. // This is a kludge to keep keymaps mostly working as raw objects
  6293. // (backwards compatibility) while at the same time support features
  6294. // like normalization and multi-stroke key bindings. It compiles a
  6295. // new normalized keymap, and then updates the old object to reflect
  6296. // this.
  6297. function normalizeKeyMap(keymap) {
  6298. var copy = {};
  6299. for (var keyname in keymap) {
  6300. if (keymap.hasOwnProperty(keyname)) {
  6301. var value = keymap[keyname];
  6302. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6303. if (value == "...") { delete keymap[keyname]; continue }
  6304. var keys = map(keyname.split(" "), normalizeKeyName);
  6305. for (var i = 0; i < keys.length; i++) {
  6306. var val = (void 0), name = (void 0);
  6307. if (i == keys.length - 1) {
  6308. name = keys.join(" ");
  6309. val = value;
  6310. } else {
  6311. name = keys.slice(0, i + 1).join(" ");
  6312. val = "...";
  6313. }
  6314. var prev = copy[name];
  6315. if (!prev) { copy[name] = val; }
  6316. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6317. }
  6318. delete keymap[keyname];
  6319. }
  6320. }
  6321. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6322. return keymap
  6323. }
  6324. function lookupKey(key, map, handle, context) {
  6325. map = getKeyMap(map);
  6326. var found = map.call ? map.call(key, context) : map[key];
  6327. if (found === false) { return "nothing" }
  6328. if (found === "...") { return "multi" }
  6329. if (found != null && handle(found)) { return "handled" }
  6330. if (map.fallthrough) {
  6331. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6332. { return lookupKey(key, map.fallthrough, handle, context) }
  6333. for (var i = 0; i < map.fallthrough.length; i++) {
  6334. var result = lookupKey(key, map.fallthrough[i], handle, context);
  6335. if (result) { return result }
  6336. }
  6337. }
  6338. }
  6339. // Modifier key presses don't count as 'real' key presses for the
  6340. // purpose of keymap fallthrough.
  6341. function isModifierKey(value) {
  6342. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6343. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6344. }
  6345. function addModifierNames(name, event, noShift) {
  6346. var base = name;
  6347. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6348. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6349. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  6350. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6351. return name
  6352. }
  6353. // Look up the name of a key as indicated by an event object.
  6354. function keyName(event, noShift) {
  6355. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6356. var name = keyNames[event.keyCode];
  6357. if (name == null || event.altGraphKey) { return false }
  6358. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6359. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6360. if (event.keyCode == 3 && event.code) { name = event.code; }
  6361. return addModifierNames(name, event, noShift)
  6362. }
  6363. function getKeyMap(val) {
  6364. return typeof val == "string" ? keyMap[val] : val
  6365. }
  6366. // Helper for deleting text near the selection(s), used to implement
  6367. // backspace, delete, and similar functionality.
  6368. function deleteNearSelection(cm, compute) {
  6369. var ranges = cm.doc.sel.ranges, kill = [];
  6370. // Build up a set of ranges to kill first, merging overlapping
  6371. // ranges.
  6372. for (var i = 0; i < ranges.length; i++) {
  6373. var toKill = compute(ranges[i]);
  6374. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6375. var replaced = kill.pop();
  6376. if (cmp(replaced.from, toKill.from) < 0) {
  6377. toKill.from = replaced.from;
  6378. break
  6379. }
  6380. }
  6381. kill.push(toKill);
  6382. }
  6383. // Next, remove those actual ranges.
  6384. runInOp(cm, function () {
  6385. for (var i = kill.length - 1; i >= 0; i--)
  6386. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6387. ensureCursorVisible(cm);
  6388. });
  6389. }
  6390. function moveCharLogically(line, ch, dir) {
  6391. var target = skipExtendingChars(line.text, ch + dir, dir);
  6392. return target < 0 || target > line.text.length ? null : target
  6393. }
  6394. function moveLogically(line, start, dir) {
  6395. var ch = moveCharLogically(line, start.ch, dir);
  6396. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6397. }
  6398. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6399. if (visually) {
  6400. if (cm.doc.direction == "rtl") { dir = -dir; }
  6401. var order = getOrder(lineObj, cm.doc.direction);
  6402. if (order) {
  6403. var part = dir < 0 ? lst(order) : order[0];
  6404. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6405. var sticky = moveInStorageOrder ? "after" : "before";
  6406. var ch;
  6407. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6408. // it could be that the last bidi part is not on the last visual line,
  6409. // since visual lines contain content order-consecutive chunks.
  6410. // Thus, in rtl, we are looking for the first (content-order) character
  6411. // in the rtl chunk that is on the last line (that is, the same line
  6412. // as the last (content-order) character).
  6413. if (part.level > 0 || cm.doc.direction == "rtl") {
  6414. var prep = prepareMeasureForLine(cm, lineObj);
  6415. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6416. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6417. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6418. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6419. } else { ch = dir < 0 ? part.to : part.from; }
  6420. return new Pos(lineNo, ch, sticky)
  6421. }
  6422. }
  6423. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6424. }
  6425. function moveVisually(cm, line, start, dir) {
  6426. var bidi = getOrder(line, cm.doc.direction);
  6427. if (!bidi) { return moveLogically(line, start, dir) }
  6428. if (start.ch >= line.text.length) {
  6429. start.ch = line.text.length;
  6430. start.sticky = "before";
  6431. } else if (start.ch <= 0) {
  6432. start.ch = 0;
  6433. start.sticky = "after";
  6434. }
  6435. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6436. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6437. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6438. // nothing interesting happens.
  6439. return moveLogically(line, start, dir)
  6440. }
  6441. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6442. var prep;
  6443. var getWrappedLineExtent = function (ch) {
  6444. if (!cm.options.lineWrapping) { return { begin: 0, end: line.text.length } }
  6445. prep = prep || prepareMeasureForLine(cm, line);
  6446. return wrappedLineExtentChar(cm, line, prep, ch)
  6447. };
  6448. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6449. if (cm.doc.direction == "rtl" || part.level == 1) {
  6450. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6451. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6452. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6453. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6454. var sticky = moveInStorageOrder ? "before" : "after";
  6455. return new Pos(start.line, ch, sticky)
  6456. }
  6457. }
  6458. // Case 3: Could not move within this bidi part in this visual line, so leave
  6459. // the current bidi part
  6460. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6461. var getRes = function (ch, moveInStorageOrder) {
  6462. return moveInStorageOrder
  6463. ? new Pos(start.line, mv(ch, 1), "before")
  6464. : new Pos(start.line, ch, "after");
  6465. };
  6466. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6467. var part = bidi[partPos];
  6468. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6469. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6470. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6471. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6472. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6473. }
  6474. };
  6475. // Case 3a: Look for other bidi parts on the same visual line
  6476. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6477. if (res) { return res }
  6478. // Case 3b: Look for other bidi parts on the next visual line
  6479. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6480. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6481. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6482. if (res) { return res }
  6483. }
  6484. // Case 4: Nowhere to move
  6485. return null
  6486. }
  6487. // Commands are parameter-less actions that can be performed on an
  6488. // editor, mostly used for keybindings.
  6489. var commands = {
  6490. selectAll: selectAll,
  6491. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6492. killLine: function (cm) {
  6493. return deleteNearSelection(cm, function (range) {
  6494. if (range.empty()) {
  6495. var len = getLine(cm.doc, range.head.line).text.length;
  6496. if (range.head.ch == len && range.head.line < cm.lastLine())
  6497. { return { from: range.head, to: Pos(range.head.line + 1, 0) } }
  6498. else
  6499. { return { from: range.head, to: Pos(range.head.line, len) } }
  6500. } else {
  6501. return { from: range.from(), to: range.to() }
  6502. }
  6503. });
  6504. },
  6505. deleteLine: function (cm) {
  6506. return deleteNearSelection(cm, function (range) {
  6507. return ({
  6508. from: Pos(range.from().line, 0),
  6509. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6510. });
  6511. });
  6512. },
  6513. delLineLeft: function (cm) {
  6514. return deleteNearSelection(cm, function (range) {
  6515. return ({
  6516. from: Pos(range.from().line, 0), to: range.from()
  6517. });
  6518. });
  6519. },
  6520. delWrappedLineLeft: function (cm) {
  6521. return deleteNearSelection(cm, function (range) {
  6522. var top = cm.charCoords(range.head, "div").top + 5;
  6523. var leftPos = cm.coordsChar({ left: 0, top: top }, "div");
  6524. return { from: leftPos, to: range.from() }
  6525. });
  6526. },
  6527. delWrappedLineRight: function (cm) {
  6528. return deleteNearSelection(cm, function (range) {
  6529. var top = cm.charCoords(range.head, "div").top + 5;
  6530. var rightPos = cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top }, "div");
  6531. return { from: range.from(), to: rightPos }
  6532. });
  6533. },
  6534. undo: function (cm) { return cm.undo(); },
  6535. redo: function (cm) { return cm.redo(); },
  6536. undoSelection: function (cm) { return cm.undoSelection(); },
  6537. redoSelection: function (cm) { return cm.redoSelection(); },
  6538. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6539. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6540. goLineStart: function (cm) {
  6541. return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6542. { origin: "+move", bias: 1 }
  6543. );
  6544. },
  6545. goLineStartSmart: function (cm) {
  6546. return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6547. { origin: "+move", bias: 1 }
  6548. );
  6549. },
  6550. goLineEnd: function (cm) {
  6551. return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6552. { origin: "+move", bias: -1 }
  6553. );
  6554. },
  6555. goLineRight: function (cm) {
  6556. return cm.extendSelectionsBy(function (range) {
  6557. var top = cm.cursorCoords(range.head, "div").top + 5;
  6558. return cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top }, "div")
  6559. }, sel_move);
  6560. },
  6561. goLineLeft: function (cm) {
  6562. return cm.extendSelectionsBy(function (range) {
  6563. var top = cm.cursorCoords(range.head, "div").top + 5;
  6564. return cm.coordsChar({ left: 0, top: top }, "div")
  6565. }, sel_move);
  6566. },
  6567. goLineLeftSmart: function (cm) {
  6568. return cm.extendSelectionsBy(function (range) {
  6569. var top = cm.cursorCoords(range.head, "div").top + 5;
  6570. var pos = cm.coordsChar({ left: 0, top: top }, "div");
  6571. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6572. return pos
  6573. }, sel_move);
  6574. },
  6575. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6576. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6577. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6578. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6579. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6580. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6581. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6582. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6583. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6584. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6585. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6586. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6587. delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  6588. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6589. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6590. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6591. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6592. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6593. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6594. indentMore: function (cm) { return cm.indentSelection("add"); },
  6595. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6596. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6597. insertSoftTab: function (cm) {
  6598. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6599. for (var i = 0; i < ranges.length; i++) {
  6600. var pos = ranges[i].from();
  6601. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6602. spaces.push(spaceStr(tabSize - col % tabSize));
  6603. }
  6604. cm.replaceSelections(spaces);
  6605. },
  6606. defaultTab: function (cm) {
  6607. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6608. else { cm.execCommand("insertTab"); }
  6609. },
  6610. // Swap the two chars left and right of each selection's head.
  6611. // Move cursor behind the two swapped characters afterwards.
  6612. //
  6613. // Doesn't consider line feeds a character.
  6614. // Doesn't scan more than one line above to find a character.
  6615. // Doesn't do anything on an empty line.
  6616. // Doesn't do anything with non-empty selections.
  6617. transposeChars: function (cm) {
  6618. return runInOp(cm, function () {
  6619. var ranges = cm.listSelections(), newSel = [];
  6620. for (var i = 0; i < ranges.length; i++) {
  6621. if (!ranges[i].empty()) { continue }
  6622. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6623. if (line) {
  6624. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6625. if (cur.ch > 0) {
  6626. cur = new Pos(cur.line, cur.ch + 1);
  6627. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6628. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6629. } else if (cur.line > cm.doc.first) {
  6630. var prev = getLine(cm.doc, cur.line - 1).text;
  6631. if (prev) {
  6632. cur = new Pos(cur.line, 1);
  6633. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6634. prev.charAt(prev.length - 1),
  6635. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6636. }
  6637. }
  6638. }
  6639. newSel.push(new Range(cur, cur));
  6640. }
  6641. cm.setSelections(newSel);
  6642. });
  6643. },
  6644. newlineAndIndent: function (cm) {
  6645. return runInOp(cm, function () {
  6646. var sels = cm.listSelections();
  6647. for (var i = sels.length - 1; i >= 0; i--)
  6648. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6649. sels = cm.listSelections();
  6650. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6651. { cm.indentLine(sels[i$1].from().line, null, true); }
  6652. ensureCursorVisible(cm);
  6653. });
  6654. },
  6655. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6656. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6657. };
  6658. function lineStart(cm, lineN) {
  6659. var line = getLine(cm.doc, lineN);
  6660. var visual = visualLine(line);
  6661. if (visual != line) { lineN = lineNo(visual); }
  6662. return endOfLine(true, cm, visual, lineN, 1)
  6663. }
  6664. function lineEnd(cm, lineN) {
  6665. var line = getLine(cm.doc, lineN);
  6666. var visual = visualLineEnd(line);
  6667. if (visual != line) { lineN = lineNo(visual); }
  6668. return endOfLine(true, cm, line, lineN, -1)
  6669. }
  6670. function lineStartSmart(cm, pos) {
  6671. var start = lineStart(cm, pos.line);
  6672. var line = getLine(cm.doc, start.line);
  6673. var order = getOrder(line, cm.doc.direction);
  6674. if (!order || order[0].level == 0) {
  6675. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  6676. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6677. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6678. }
  6679. return start
  6680. }
  6681. // Run a handler that was bound to a key.
  6682. function doHandleBinding(cm, bound, dropShift) {
  6683. if (typeof bound == "string") {
  6684. bound = commands[bound];
  6685. if (!bound) { return false }
  6686. }
  6687. // Ensure previous input has been read, so that the handler sees a
  6688. // consistent view of the document
  6689. cm.display.input.ensurePolled();
  6690. var prevShift = cm.display.shift, done = false;
  6691. try {
  6692. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6693. if (dropShift) { cm.display.shift = false; }
  6694. done = bound(cm) != Pass;
  6695. } finally {
  6696. cm.display.shift = prevShift;
  6697. cm.state.suppressEdits = false;
  6698. }
  6699. return done
  6700. }
  6701. function lookupKeyForEditor(cm, name, handle) {
  6702. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6703. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6704. if (result) { return result }
  6705. }
  6706. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6707. || lookupKey(name, cm.options.keyMap, handle, cm)
  6708. }
  6709. // Note that, despite the name, this function is also used to check
  6710. // for bound mouse clicks.
  6711. var stopSeq = new Delayed;
  6712. function dispatchKey(cm, name, e, handle) {
  6713. var seq = cm.state.keySeq;
  6714. if (seq) {
  6715. if (isModifierKey(name)) { return "handled" }
  6716. if (/\'$/.test(name))
  6717. { cm.state.keySeq = null; }
  6718. else
  6719. {
  6720. stopSeq.set(50, function () {
  6721. if (cm.state.keySeq == seq) {
  6722. cm.state.keySeq = null;
  6723. cm.display.input.reset();
  6724. }
  6725. });
  6726. }
  6727. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6728. }
  6729. return dispatchKeyInner(cm, name, e, handle)
  6730. }
  6731. function dispatchKeyInner(cm, name, e, handle) {
  6732. var result = lookupKeyForEditor(cm, name, handle);
  6733. if (result == "multi")
  6734. { cm.state.keySeq = name; }
  6735. if (result == "handled")
  6736. { signalLater(cm, "keyHandled", cm, name, e); }
  6737. if (result == "handled" || result == "multi") {
  6738. e_preventDefault(e);
  6739. restartBlink(cm);
  6740. }
  6741. return !!result
  6742. }
  6743. // Handle a key from the keydown event.
  6744. function handleKeyBinding(cm, e) {
  6745. var name = keyName(e, true);
  6746. if (!name) { return false }
  6747. if (e.shiftKey && !cm.state.keySeq) {
  6748. // First try to resolve full name (including 'Shift-'). Failing
  6749. // that, see if there is a cursor-motion command (starting with
  6750. // 'go') bound to the keyname without 'Shift-'.
  6751. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6752. || dispatchKey(cm, name, e, function (b) {
  6753. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6754. { return doHandleBinding(cm, b) }
  6755. })
  6756. } else {
  6757. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6758. }
  6759. }
  6760. // Handle a key from the keypress event
  6761. function handleCharBinding(cm, e, ch) {
  6762. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6763. }
  6764. var lastStoppedKey = null;
  6765. function onKeyDown(e) {
  6766. var cm = this;
  6767. if (e.target && e.target != cm.display.input.getField()) { return }
  6768. cm.curOp.focus = activeElt(doc(cm));
  6769. if (signalDOMEvent(cm, e)) { return }
  6770. // IE does strange things with escape.
  6771. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6772. var code = e.keyCode;
  6773. cm.display.shift = code == 16 || e.shiftKey;
  6774. var handled = handleKeyBinding(cm, e);
  6775. if (presto) {
  6776. lastStoppedKey = handled ? code : null;
  6777. // Opera has no cut event... we try to at least catch the key combo
  6778. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6779. { cm.replaceSelection("", null, "cut"); }
  6780. }
  6781. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  6782. { document.execCommand("cut"); }
  6783. // Turn mouse into crosshair when Alt is held on Mac.
  6784. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6785. { showCrossHair(cm); }
  6786. }
  6787. function showCrossHair(cm) {
  6788. var lineDiv = cm.display.lineDiv;
  6789. addClass(lineDiv, "CodeMirror-crosshair");
  6790. function up(e) {
  6791. if (e.keyCode == 18 || !e.altKey) {
  6792. rmClass(lineDiv, "CodeMirror-crosshair");
  6793. off(document, "keyup", up);
  6794. off(document, "mouseover", up);
  6795. }
  6796. }
  6797. on(document, "keyup", up);
  6798. on(document, "mouseover", up);
  6799. }
  6800. function onKeyUp(e) {
  6801. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6802. signalDOMEvent(this, e);
  6803. }
  6804. function onKeyPress(e) {
  6805. var cm = this;
  6806. if (e.target && e.target != cm.display.input.getField()) { return }
  6807. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6808. var keyCode = e.keyCode, charCode = e.charCode;
  6809. if (presto && keyCode == lastStoppedKey) { lastStoppedKey = null; e_preventDefault(e); return }
  6810. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6811. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6812. // Some browsers fire keypress events for backspace
  6813. if (ch == "\x08") { return }
  6814. if (handleCharBinding(cm, e, ch)) { return }
  6815. cm.display.input.onKeyPress(e);
  6816. }
  6817. var DOUBLECLICK_DELAY = 400;
  6818. var PastClick = function (time, pos, button) {
  6819. this.time = time;
  6820. this.pos = pos;
  6821. this.button = button;
  6822. };
  6823. PastClick.prototype.compare = function (time, pos, button) {
  6824. return this.time + DOUBLECLICK_DELAY > time &&
  6825. cmp(pos, this.pos) == 0 && button == this.button
  6826. };
  6827. var lastClick, lastDoubleClick;
  6828. function clickRepeat(pos, button) {
  6829. var now = +new Date;
  6830. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6831. lastClick = lastDoubleClick = null;
  6832. return "triple"
  6833. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6834. lastDoubleClick = new PastClick(now, pos, button);
  6835. lastClick = null;
  6836. return "double"
  6837. } else {
  6838. lastClick = new PastClick(now, pos, button);
  6839. lastDoubleClick = null;
  6840. return "single"
  6841. }
  6842. }
  6843. // A mouse down can be a single click, double click, triple click,
  6844. // start of selection drag, start of text drag, new cursor
  6845. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6846. // middle-click-paste. Or it might be a click on something we should
  6847. // not interfere with, such as a scrollbar or widget.
  6848. function onMouseDown(e) {
  6849. var cm = this, display = cm.display;
  6850. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6851. display.input.ensurePolled();
  6852. display.shift = e.shiftKey;
  6853. if (eventInWidget(display, e)) {
  6854. if (!webkit) {
  6855. // Briefly turn off draggability, to allow widgets to do
  6856. // normal dragging things.
  6857. display.scroller.draggable = false;
  6858. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6859. }
  6860. return
  6861. }
  6862. if (clickInGutter(cm, e)) { return }
  6863. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6864. win(cm).focus();
  6865. // #3261: make sure, that we're not starting a second selection
  6866. if (button == 1 && cm.state.selectingText)
  6867. { cm.state.selectingText(e); }
  6868. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6869. if (button == 1) {
  6870. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6871. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6872. } else if (button == 2) {
  6873. if (pos) { extendSelection(cm.doc, pos); }
  6874. setTimeout(function () { return display.input.focus(); }, 20);
  6875. } else if (button == 3) {
  6876. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6877. else { delayBlurEvent(cm); }
  6878. }
  6879. }
  6880. function handleMappedButton(cm, button, pos, repeat, event) {
  6881. var name = "Click";
  6882. if (repeat == "double") { name = "Double" + name; }
  6883. else if (repeat == "triple") { name = "Triple" + name; }
  6884. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6885. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6886. if (typeof bound == "string") { bound = commands[bound]; }
  6887. if (!bound) { return false }
  6888. var done = false;
  6889. try {
  6890. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6891. done = bound(cm, pos) != Pass;
  6892. } finally {
  6893. cm.state.suppressEdits = false;
  6894. }
  6895. return done
  6896. })
  6897. }
  6898. function configureMouse(cm, repeat, event) {
  6899. var option = cm.getOption("configureMouse");
  6900. var value = option ? option(cm, repeat, event) : {};
  6901. if (value.unit == null) {
  6902. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6903. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6904. }
  6905. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6906. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6907. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6908. return value
  6909. }
  6910. function leftButtonDown(cm, pos, repeat, event) {
  6911. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6912. else { cm.curOp.focus = activeElt(doc(cm)); }
  6913. var behavior = configureMouse(cm, repeat, event);
  6914. var sel = cm.doc.sel, contained;
  6915. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6916. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6917. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6918. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6919. { leftButtonStartDrag(cm, event, pos, behavior); }
  6920. else
  6921. { leftButtonSelect(cm, event, pos, behavior); }
  6922. }
  6923. // Start a text drag. When it ends, see if any dragging actually
  6924. // happen, and treat as a click if it didn't.
  6925. function leftButtonStartDrag(cm, event, pos, behavior) {
  6926. var display = cm.display, moved = false;
  6927. var dragEnd = operation(cm, function (e) {
  6928. if (webkit) { display.scroller.draggable = false; }
  6929. cm.state.draggingText = false;
  6930. if (cm.state.delayingBlurEvent) {
  6931. if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  6932. else { delayBlurEvent(cm); }
  6933. }
  6934. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6935. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6936. off(display.scroller, "dragstart", dragStart);
  6937. off(display.scroller, "drop", dragEnd);
  6938. if (!moved) {
  6939. e_preventDefault(e);
  6940. if (!behavior.addNew)
  6941. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6942. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6943. if ((webkit && !safari) || ie && ie_version == 9)
  6944. { setTimeout(function () { display.wrapper.ownerDocument.body.focus({ preventScroll: true }); display.input.focus(); }, 20); }
  6945. else
  6946. { display.input.focus(); }
  6947. }
  6948. });
  6949. var mouseMove = function (e2) {
  6950. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6951. };
  6952. var dragStart = function () { return moved = true; };
  6953. // Let the drag handler handle this.
  6954. if (webkit) { display.scroller.draggable = true; }
  6955. cm.state.draggingText = dragEnd;
  6956. dragEnd.copy = !behavior.moveOnDrag;
  6957. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6958. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6959. on(display.scroller, "dragstart", dragStart);
  6960. on(display.scroller, "drop", dragEnd);
  6961. cm.state.delayingBlurEvent = true;
  6962. setTimeout(function () { return display.input.focus(); }, 20);
  6963. // IE's approach to draggable
  6964. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6965. }
  6966. function rangeForUnit(cm, pos, unit) {
  6967. if (unit == "char") { return new Range(pos, pos) }
  6968. if (unit == "word") { return cm.findWordAt(pos) }
  6969. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6970. var result = unit(cm, pos);
  6971. return new Range(result.from, result.to)
  6972. }
  6973. // Normal selection, as opposed to text dragging.
  6974. function leftButtonSelect(cm, event, start, behavior) {
  6975. if (ie) { delayBlurEvent(cm); }
  6976. var display = cm.display, doc$1 = cm.doc;
  6977. e_preventDefault(event);
  6978. var ourRange, ourIndex, startSel = doc$1.sel, ranges = startSel.ranges;
  6979. if (behavior.addNew && !behavior.extend) {
  6980. ourIndex = doc$1.sel.contains(start);
  6981. if (ourIndex > -1)
  6982. { ourRange = ranges[ourIndex]; }
  6983. else
  6984. { ourRange = new Range(start, start); }
  6985. } else {
  6986. ourRange = doc$1.sel.primary();
  6987. ourIndex = doc$1.sel.primIndex;
  6988. }
  6989. if (behavior.unit == "rectangle") {
  6990. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6991. start = posFromMouse(cm, event, true, true);
  6992. ourIndex = -1;
  6993. } else {
  6994. var range = rangeForUnit(cm, start, behavior.unit);
  6995. if (behavior.extend)
  6996. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  6997. else
  6998. { ourRange = range; }
  6999. }
  7000. if (!behavior.addNew) {
  7001. ourIndex = 0;
  7002. setSelection(doc$1, new Selection([ourRange], 0), sel_mouse);
  7003. startSel = doc$1.sel;
  7004. } else if (ourIndex == -1) {
  7005. ourIndex = ranges.length;
  7006. setSelection(doc$1, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  7007. { scroll: false, origin: "*mouse" });
  7008. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  7009. setSelection(doc$1, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  7010. { scroll: false, origin: "*mouse" });
  7011. startSel = doc$1.sel;
  7012. } else {
  7013. replaceOneSelection(doc$1, ourIndex, ourRange, sel_mouse);
  7014. }
  7015. var lastPos = start;
  7016. function extendTo(pos) {
  7017. if (cmp(lastPos, pos) == 0) { return }
  7018. lastPos = pos;
  7019. if (behavior.unit == "rectangle") {
  7020. var ranges = [], tabSize = cm.options.tabSize;
  7021. var startCol = countColumn(getLine(doc$1, start.line).text, start.ch, tabSize);
  7022. var posCol = countColumn(getLine(doc$1, pos.line).text, pos.ch, tabSize);
  7023. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  7024. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)) ;
  7025. line <= end; line++) {
  7026. var text = getLine(doc$1, line).text, leftPos = findColumn(text, left, tabSize);
  7027. if (left == right)
  7028. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  7029. else if (text.length > leftPos)
  7030. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  7031. }
  7032. if (!ranges.length) { ranges.push(new Range(start, start)); }
  7033. setSelection(doc$1, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  7034. { origin: "*mouse", scroll: false });
  7035. cm.scrollIntoView(pos);
  7036. } else {
  7037. var oldRange = ourRange;
  7038. var range = rangeForUnit(cm, pos, behavior.unit);
  7039. var anchor = oldRange.anchor, head;
  7040. if (cmp(range.anchor, anchor) > 0) {
  7041. head = range.head;
  7042. anchor = minPos(oldRange.from(), range.anchor);
  7043. } else {
  7044. head = range.anchor;
  7045. anchor = maxPos(oldRange.to(), range.head);
  7046. }
  7047. var ranges$1 = startSel.ranges.slice(0);
  7048. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc$1, anchor), head));
  7049. setSelection(doc$1, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  7050. }
  7051. }
  7052. var editorSize = display.wrapper.getBoundingClientRect();
  7053. // Used to ensure timeout re-tries don't fire when another extend
  7054. // happened in the meantime (clearTimeout isn't reliable -- at
  7055. // least on Chrome, the timeouts still happen even when cleared,
  7056. // if the clear happens after their scheduled firing time).
  7057. var counter = 0;
  7058. function extend(e) {
  7059. var curCount = ++counter;
  7060. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  7061. if (!cur) { return }
  7062. if (cmp(cur, lastPos) != 0) {
  7063. cm.curOp.focus = activeElt(doc(cm));
  7064. extendTo(cur);
  7065. var visible = visibleLines(display, doc$1);
  7066. if (cur.line >= visible.to || cur.line < visible.from)
  7067. { setTimeout(operation(cm, function () { if (counter == curCount) { extend(e); } }), 150); }
  7068. } else {
  7069. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  7070. if (outside) {
  7071. setTimeout(operation(cm, function () {
  7072. if (counter != curCount) { return }
  7073. display.scroller.scrollTop += outside;
  7074. extend(e);
  7075. }), 50);
  7076. }
  7077. }
  7078. }
  7079. function done(e) {
  7080. cm.state.selectingText = false;
  7081. counter = Infinity;
  7082. // If e is null or undefined we interpret this as someone trying
  7083. // to explicitly cancel the selection rather than the user
  7084. // letting go of the mouse button.
  7085. if (e) {
  7086. e_preventDefault(e);
  7087. display.input.focus();
  7088. }
  7089. off(display.wrapper.ownerDocument, "mousemove", move);
  7090. off(display.wrapper.ownerDocument, "mouseup", up);
  7091. doc$1.history.lastSelOrigin = null;
  7092. }
  7093. var move = operation(cm, function (e) {
  7094. if (e.buttons === 0 || !e_button(e)) { done(e); }
  7095. else { extend(e); }
  7096. });
  7097. var up = operation(cm, done);
  7098. cm.state.selectingText = up;
  7099. on(display.wrapper.ownerDocument, "mousemove", move);
  7100. on(display.wrapper.ownerDocument, "mouseup", up);
  7101. }
  7102. // Used when mouse-selecting to adjust the anchor to the proper side
  7103. // of a bidi jump depending on the visual position of the head.
  7104. function bidiSimplify(cm, range) {
  7105. var anchor = range.anchor;
  7106. var head = range.head;
  7107. var anchorLine = getLine(cm.doc, anchor.line);
  7108. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  7109. var order = getOrder(anchorLine);
  7110. if (!order) { return range }
  7111. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  7112. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  7113. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  7114. if (boundary == 0 || boundary == order.length) { return range }
  7115. // Compute the relative visual position of the head compared to the
  7116. // anchor (<0 is to the left, >0 to the right)
  7117. var leftSide;
  7118. if (head.line != anchor.line) {
  7119. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  7120. } else {
  7121. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  7122. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  7123. if (headIndex == boundary - 1 || headIndex == boundary)
  7124. { leftSide = dir < 0; }
  7125. else
  7126. { leftSide = dir > 0; }
  7127. }
  7128. var usePart = order[boundary + (leftSide ? -1 : 0)];
  7129. var from = leftSide == (usePart.level == 1);
  7130. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  7131. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  7132. }
  7133. // Determines whether an event happened in the gutter, and fires the
  7134. // handlers for the corresponding event.
  7135. function gutterEvent(cm, e, type, prevent) {
  7136. var mX, mY;
  7137. if (e.touches) {
  7138. mX = e.touches[0].clientX;
  7139. mY = e.touches[0].clientY;
  7140. } else {
  7141. try { mX = e.clientX; mY = e.clientY; }
  7142. catch (e$1) { return false }
  7143. }
  7144. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  7145. if (prevent) { e_preventDefault(e); }
  7146. var display = cm.display;
  7147. var lineBox = display.lineDiv.getBoundingClientRect();
  7148. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  7149. mY -= lineBox.top - display.viewOffset;
  7150. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  7151. var g = display.gutters.childNodes[i];
  7152. if (g && g.getBoundingClientRect().right >= mX) {
  7153. var line = lineAtHeight(cm.doc, mY);
  7154. var gutter = cm.display.gutterSpecs[i];
  7155. signal(cm, type, cm, line, gutter.className, e);
  7156. return e_defaultPrevented(e)
  7157. }
  7158. }
  7159. }
  7160. function clickInGutter(cm, e) {
  7161. return gutterEvent(cm, e, "gutterClick", true)
  7162. }
  7163. // CONTEXT MENU HANDLING
  7164. // To make the context menu work, we need to briefly unhide the
  7165. // textarea (making it as unobtrusive as possible) to let the
  7166. // right-click take effect on it.
  7167. function onContextMenu(cm, e) {
  7168. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  7169. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  7170. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  7171. }
  7172. function contextMenuInGutter(cm, e) {
  7173. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  7174. return gutterEvent(cm, e, "gutterContextMenu", false)
  7175. }
  7176. function themeChanged(cm) {
  7177. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  7178. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  7179. clearCaches(cm);
  7180. }
  7181. var Init = { toString: function () { return "CodeMirror.Init" } };
  7182. var defaults = {};
  7183. var optionHandlers = {};
  7184. function defineOptions(CodeMirror) {
  7185. var optionHandlers = CodeMirror.optionHandlers;
  7186. function option(name, deflt, handle, notOnInit) {
  7187. CodeMirror.defaults[name] = deflt;
  7188. if (handle) {
  7189. optionHandlers[name] =
  7190. notOnInit ? function (cm, val, old) { if (old != Init) { handle(cm, val, old); } } : handle;
  7191. }
  7192. }
  7193. CodeMirror.defineOption = option;
  7194. // Passed to option handlers when there is no old value.
  7195. CodeMirror.Init = Init;
  7196. // These two are, on init, called from the constructor because they
  7197. // have to be initialized before the editor can start at all.
  7198. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  7199. option("mode", null, function (cm, val) {
  7200. cm.doc.modeOption = val;
  7201. loadMode(cm);
  7202. }, true);
  7203. option("indentUnit", 2, loadMode, true);
  7204. option("indentWithTabs", false);
  7205. option("smartIndent", true);
  7206. option("tabSize", 4, function (cm) {
  7207. resetModeState(cm);
  7208. clearCaches(cm);
  7209. regChange(cm);
  7210. }, true);
  7211. option("lineSeparator", null, function (cm, val) {
  7212. cm.doc.lineSep = val;
  7213. if (!val) { return }
  7214. var newBreaks = [], lineNo = cm.doc.first;
  7215. cm.doc.iter(function (line) {
  7216. for (var pos = 0; ;) {
  7217. var found = line.text.indexOf(val, pos);
  7218. if (found == -1) { break }
  7219. pos = found + val.length;
  7220. newBreaks.push(Pos(lineNo, found));
  7221. }
  7222. lineNo++;
  7223. });
  7224. for (var i = newBreaks.length - 1; i >= 0; i--)
  7225. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  7226. });
  7227. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  7228. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  7229. if (old != Init) { cm.refresh(); }
  7230. });
  7231. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  7232. option("electricChars", true);
  7233. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  7234. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  7235. }, true);
  7236. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  7237. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  7238. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  7239. option("rtlMoveVisually", !windows);
  7240. option("wholeLineUpdateBefore", true);
  7241. option("theme", "default", function (cm) {
  7242. themeChanged(cm);
  7243. updateGutters(cm);
  7244. }, true);
  7245. option("keyMap", "default", function (cm, val, old) {
  7246. var next = getKeyMap(val);
  7247. var prev = old != Init && getKeyMap(old);
  7248. if (prev && prev.detach) { prev.detach(cm, next); }
  7249. if (next.attach) { next.attach(cm, prev || null); }
  7250. });
  7251. option("extraKeys", null);
  7252. option("configureMouse", null);
  7253. option("lineWrapping", false, wrappingChanged, true);
  7254. option("gutters", [], function (cm, val) {
  7255. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7256. updateGutters(cm);
  7257. }, true);
  7258. option("fixedGutter", true, function (cm, val) {
  7259. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7260. cm.refresh();
  7261. }, true);
  7262. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7263. option("scrollbarStyle", "native", function (cm) {
  7264. initScrollbars(cm);
  7265. updateScrollbars(cm);
  7266. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7267. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7268. }, true);
  7269. option("lineNumbers", false, function (cm, val) {
  7270. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7271. updateGutters(cm);
  7272. }, true);
  7273. option("firstLineNumber", 1, updateGutters, true);
  7274. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7275. option("showCursorWhenSelecting", false, updateSelection, true);
  7276. option("resetSelectionOnContextMenu", true);
  7277. option("lineWiseCopyCut", true);
  7278. option("pasteLinesPerSelection", true);
  7279. option("selectionsMayTouch", false);
  7280. option("readOnly", false, function (cm, val) {
  7281. if (val == "nocursor") {
  7282. onBlur(cm);
  7283. cm.display.input.blur();
  7284. }
  7285. cm.display.input.readOnlyChanged(val);
  7286. });
  7287. option("screenReaderLabel", null, function (cm, val) {
  7288. val = (val === '') ? null : val;
  7289. cm.display.input.screenReaderLabelChanged(val);
  7290. });
  7291. option("disableInput", false, function (cm, val) { if (!val) { cm.display.input.reset(); } }, true);
  7292. option("dragDrop", true, dragDropChanged);
  7293. option("allowDropFileTypes", null);
  7294. option("cursorBlinkRate", 530);
  7295. option("cursorScrollMargin", 0);
  7296. option("cursorHeight", 1, updateSelection, true);
  7297. option("singleCursorHeightPerLine", true, updateSelection, true);
  7298. option("workTime", 100);
  7299. option("workDelay", 100);
  7300. option("flattenSpans", true, resetModeState, true);
  7301. option("addModeClass", false, resetModeState, true);
  7302. option("pollInterval", 100);
  7303. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7304. option("historyEventDelay", 1250);
  7305. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7306. option("maxHighlightLength", 10000, resetModeState, true);
  7307. option("moveInputWithCursor", true, function (cm, val) {
  7308. if (!val) { cm.display.input.resetPosition(); }
  7309. });
  7310. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7311. option("autofocus", null);
  7312. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7313. option("phrases", null);
  7314. }
  7315. function dragDropChanged(cm, value, old) {
  7316. var wasOn = old && old != Init;
  7317. if (!value != !wasOn) {
  7318. var funcs = cm.display.dragFunctions;
  7319. var toggle = value ? on : off;
  7320. toggle(cm.display.scroller, "dragstart", funcs.start);
  7321. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7322. toggle(cm.display.scroller, "dragover", funcs.over);
  7323. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7324. toggle(cm.display.scroller, "drop", funcs.drop);
  7325. }
  7326. }
  7327. function wrappingChanged(cm) {
  7328. if (cm.options.lineWrapping) {
  7329. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7330. cm.display.sizer.style.minWidth = "";
  7331. cm.display.sizerWidth = null;
  7332. } else {
  7333. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7334. findMaxLine(cm);
  7335. }
  7336. estimateLineHeights(cm);
  7337. regChange(cm);
  7338. clearCaches(cm);
  7339. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7340. }
  7341. // A CodeMirror instance represents an editor. This is the object
  7342. // that user code is usually dealing with.
  7343. function CodeMirror(place, options) {
  7344. var this$1 = this;
  7345. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7346. this.options = options = options ? copyObj(options) : {};
  7347. // Determine effective options based on given values and defaults.
  7348. copyObj(defaults, options, false);
  7349. var doc = options.value;
  7350. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7351. else if (options.mode) { doc.modeOption = options.mode; }
  7352. this.doc = doc;
  7353. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7354. var display = this.display = new Display(place, doc, input, options);
  7355. display.wrapper.CodeMirror = this;
  7356. themeChanged(this);
  7357. if (options.lineWrapping)
  7358. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7359. initScrollbars(this);
  7360. this.state = {
  7361. keyMaps: [], // stores maps added by addKeyMap
  7362. overlays: [], // highlighting overlays, as added by addOverlay
  7363. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7364. overwrite: false,
  7365. delayingBlurEvent: false,
  7366. focused: false,
  7367. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7368. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7369. selectingText: false,
  7370. draggingText: false,
  7371. highlight: new Delayed(), // stores highlight worker timeout
  7372. keySeq: null, // Unfinished key sequence
  7373. specialChars: null
  7374. };
  7375. if (options.autofocus && !mobile) { display.input.focus(); }
  7376. // Override magic textarea content restore that IE sometimes does
  7377. // on our hidden textarea on reload
  7378. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7379. registerEventHandlers(this);
  7380. ensureGlobalHandlers();
  7381. startOperation(this);
  7382. this.curOp.forceUpdate = true;
  7383. attachDoc(this, doc);
  7384. if ((options.autofocus && !mobile) || this.hasFocus()) {
  7385. setTimeout(function () {
  7386. if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  7387. }, 20);
  7388. }
  7389. else { onBlur(this); }
  7390. for (var opt in optionHandlers) {
  7391. if (optionHandlers.hasOwnProperty(opt))
  7392. { optionHandlers[opt](this, options[opt], Init); }
  7393. }
  7394. maybeUpdateLineNumberWidth(this);
  7395. if (options.finishInit) { options.finishInit(this); }
  7396. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7397. endOperation(this);
  7398. // Suppress optimizelegibility in Webkit, since it breaks text
  7399. // measuring on line wrapping boundaries.
  7400. if (webkit && options.lineWrapping &&
  7401. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7402. { display.lineDiv.style.textRendering = "auto"; }
  7403. }
  7404. // The default configuration options.
  7405. CodeMirror.defaults = defaults;
  7406. // Functions to run when options are changed.
  7407. CodeMirror.optionHandlers = optionHandlers;
  7408. // Attach the necessary event handlers when initializing the editor
  7409. function registerEventHandlers(cm) {
  7410. var d = cm.display;
  7411. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7412. // Older IE's will not fire a second mousedown for a double click
  7413. if (ie && ie_version < 11) {
  7414. on(d.scroller, "dblclick", operation(cm, function (e) {
  7415. if (signalDOMEvent(cm, e)) { return }
  7416. var pos = posFromMouse(cm, e);
  7417. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7418. e_preventDefault(e);
  7419. var word = cm.findWordAt(pos);
  7420. extendSelection(cm.doc, word.anchor, word.head);
  7421. }));
  7422. }
  7423. else { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7424. // Some browsers fire contextmenu *after* opening the menu, at
  7425. // which point we can't mess with it anymore. Context menu is
  7426. // handled in onMouseDown for these browsers.
  7427. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7428. on(d.input.getField(), "contextmenu", function (e) {
  7429. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7430. });
  7431. // Used to suppress mouse event handling when a touch happens
  7432. var touchFinished, prevTouch = { end: 0 };
  7433. function finishTouch() {
  7434. if (d.activeTouch) {
  7435. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7436. prevTouch = d.activeTouch;
  7437. prevTouch.end = +new Date;
  7438. }
  7439. }
  7440. function isMouseLikeTouchEvent(e) {
  7441. if (e.touches.length != 1) { return false }
  7442. var touch = e.touches[0];
  7443. return touch.radiusX <= 1 && touch.radiusY <= 1
  7444. }
  7445. function farAway(touch, other) {
  7446. if (other.left == null) { return true }
  7447. var dx = other.left - touch.left, dy = other.top - touch.top;
  7448. return dx * dx + dy * dy > 20 * 20
  7449. }
  7450. on(d.scroller, "touchstart", function (e) {
  7451. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7452. d.input.ensurePolled();
  7453. clearTimeout(touchFinished);
  7454. var now = +new Date;
  7455. d.activeTouch = {
  7456. start: now, moved: false,
  7457. prev: now - prevTouch.end <= 300 ? prevTouch : null
  7458. };
  7459. if (e.touches.length == 1) {
  7460. d.activeTouch.left = e.touches[0].pageX;
  7461. d.activeTouch.top = e.touches[0].pageY;
  7462. }
  7463. }
  7464. });
  7465. on(d.scroller, "touchmove", function () {
  7466. if (d.activeTouch) { d.activeTouch.moved = true; }
  7467. });
  7468. on(d.scroller, "touchend", function (e) {
  7469. var touch = d.activeTouch;
  7470. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7471. !touch.moved && new Date - touch.start < 300) {
  7472. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7473. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7474. { range = new Range(pos, pos); }
  7475. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7476. { range = cm.findWordAt(pos); }
  7477. else // Triple tap
  7478. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7479. cm.setSelection(range.anchor, range.head);
  7480. cm.focus();
  7481. e_preventDefault(e);
  7482. }
  7483. finishTouch();
  7484. });
  7485. on(d.scroller, "touchcancel", finishTouch);
  7486. // Sync scrolling between fake scrollbars and real scrollable
  7487. // area, ensure viewport is updated when scrolling.
  7488. on(d.scroller, "scroll", function () {
  7489. if (d.scroller.clientHeight) {
  7490. updateScrollTop(cm, d.scroller.scrollTop);
  7491. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7492. signal(cm, "scroll", cm);
  7493. }
  7494. });
  7495. // Listen to wheel events in order to try and update the viewport on time.
  7496. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7497. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7498. // Prevent wrapper from ever scrolling
  7499. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7500. d.dragFunctions = {
  7501. enter: function (e) { if (!signalDOMEvent(cm, e)) { e_stop(e); } },
  7502. over: function (e) { if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); } },
  7503. start: function (e) { return onDragStart(cm, e); },
  7504. drop: operation(cm, onDrop),
  7505. leave: function (e) { if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); } }
  7506. };
  7507. var inp = d.input.getField();
  7508. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7509. on(inp, "keydown", operation(cm, onKeyDown));
  7510. on(inp, "keypress", operation(cm, onKeyPress));
  7511. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7512. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7513. }
  7514. var initHooks = [];
  7515. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7516. // Indent the given line. The how parameter can be "smart",
  7517. // "add"/null, "subtract", or "prev". When aggressive is false
  7518. // (typically set to true for forced single-line indents), empty
  7519. // lines are not indented, and places where the mode returns Pass
  7520. // are left alone.
  7521. function indentLine(cm, n, how, aggressive) {
  7522. var doc = cm.doc, state;
  7523. if (how == null) { how = "add"; }
  7524. if (how == "smart") {
  7525. // Fall back to "prev" when the mode doesn't have an indentation
  7526. // method.
  7527. if (!doc.mode.indent) { how = "prev"; }
  7528. else { state = getContextBefore(cm, n).state; }
  7529. }
  7530. var tabSize = cm.options.tabSize;
  7531. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7532. if (line.stateAfter) { line.stateAfter = null; }
  7533. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7534. if (!aggressive && !/\S/.test(line.text)) {
  7535. indentation = 0;
  7536. how = "not";
  7537. } else if (how == "smart") {
  7538. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7539. if (indentation == Pass || indentation > 150) {
  7540. if (!aggressive) { return }
  7541. how = "prev";
  7542. }
  7543. }
  7544. if (how == "prev") {
  7545. if (n > doc.first) { indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); }
  7546. else { indentation = 0; }
  7547. } else if (how == "add") {
  7548. indentation = curSpace + cm.options.indentUnit;
  7549. } else if (how == "subtract") {
  7550. indentation = curSpace - cm.options.indentUnit;
  7551. } else if (typeof how == "number") {
  7552. indentation = curSpace + how;
  7553. }
  7554. indentation = Math.max(0, indentation);
  7555. var indentString = "", pos = 0;
  7556. if (cm.options.indentWithTabs)
  7557. { for (var i = Math.floor(indentation / tabSize) ; i; --i) { pos += tabSize; indentString += "\t"; } }
  7558. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7559. if (indentString != curSpaceString) {
  7560. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7561. line.stateAfter = null;
  7562. return true
  7563. } else {
  7564. // Ensure that, if the cursor was in the whitespace at the start
  7565. // of the line, it is moved to the end of that space.
  7566. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7567. var range = doc.sel.ranges[i$1];
  7568. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7569. var pos$1 = Pos(n, curSpaceString.length);
  7570. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7571. break
  7572. }
  7573. }
  7574. }
  7575. }
  7576. // This will be set to a {lineWise: bool, text: [string]} object, so
  7577. // that, when pasting, we know what kind of selections the copied
  7578. // text was made out of.
  7579. var lastCopied = null;
  7580. function setLastCopied(newLastCopied) {
  7581. lastCopied = newLastCopied;
  7582. }
  7583. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7584. var doc = cm.doc;
  7585. cm.display.shift = false;
  7586. if (!sel) { sel = doc.sel; }
  7587. var recent = +new Date - 200;
  7588. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7589. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7590. // When pasting N lines into N selections, insert one line per selection
  7591. if (paste && sel.ranges.length > 1) {
  7592. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7593. if (sel.ranges.length % lastCopied.text.length == 0) {
  7594. multiPaste = [];
  7595. for (var i = 0; i < lastCopied.text.length; i++)
  7596. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7597. }
  7598. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7599. multiPaste = map(textLines, function (l) { return [l]; });
  7600. }
  7601. }
  7602. var updateInput = cm.curOp.updateInput;
  7603. // Normal behavior is to insert the new text into every selection
  7604. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7605. var range = sel.ranges[i$1];
  7606. var from = range.from(), to = range.to();
  7607. if (range.empty()) {
  7608. if (deleted && deleted > 0) // Handle deletion
  7609. { from = Pos(from.line, from.ch - deleted); }
  7610. else if (cm.state.overwrite && !paste) // Handle overwrite
  7611. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7612. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  7613. { from = to = Pos(from.line, 0); }
  7614. }
  7615. var changeEvent = {
  7616. from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7617. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")
  7618. };
  7619. makeChange(cm.doc, changeEvent);
  7620. signalLater(cm, "inputRead", cm, changeEvent);
  7621. }
  7622. if (inserted && !paste)
  7623. { triggerElectric(cm, inserted); }
  7624. ensureCursorVisible(cm);
  7625. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7626. cm.curOp.typing = true;
  7627. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7628. }
  7629. function handlePaste(e, cm) {
  7630. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7631. if (pasted) {
  7632. e.preventDefault();
  7633. if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
  7634. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7635. return true
  7636. }
  7637. }
  7638. function triggerElectric(cm, inserted) {
  7639. // When an 'electric' character is inserted, immediately trigger a reindent
  7640. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7641. var sel = cm.doc.sel;
  7642. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7643. var range = sel.ranges[i];
  7644. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7645. var mode = cm.getModeAt(range.head);
  7646. var indented = false;
  7647. if (mode.electricChars) {
  7648. for (var j = 0; j < mode.electricChars.length; j++) {
  7649. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7650. indented = indentLine(cm, range.head.line, "smart");
  7651. break
  7652. }
  7653. }
  7654. } else if (mode.electricInput) {
  7655. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7656. { indented = indentLine(cm, range.head.line, "smart"); }
  7657. }
  7658. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  7659. }
  7660. }
  7661. function copyableRanges(cm) {
  7662. var text = [], ranges = [];
  7663. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7664. var line = cm.doc.sel.ranges[i].head.line;
  7665. var lineRange = { anchor: Pos(line, 0), head: Pos(line + 1, 0) };
  7666. ranges.push(lineRange);
  7667. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7668. }
  7669. return { text: text, ranges: ranges }
  7670. }
  7671. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7672. field.setAttribute("autocorrect", autocorrect ? "on" : "off");
  7673. field.setAttribute("autocapitalize", autocapitalize ? "on" : "off");
  7674. field.setAttribute("spellcheck", !!spellcheck);
  7675. }
  7676. function hiddenTextarea() {
  7677. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
  7678. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7679. // The textarea is kept positioned near the cursor to prevent the
  7680. // fact that it'll be scrolled into view on input from scrolling
  7681. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7682. // very slow. So make the area wide instead.
  7683. if (webkit) { te.style.width = "1000px"; }
  7684. else { te.setAttribute("wrap", "off"); }
  7685. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7686. if (ios) { te.style.border = "1px solid black"; }
  7687. return div
  7688. }
  7689. // The publicly visible API. Note that methodOp(f) means
  7690. // 'wrap f in an operation, performed on its `this` parameter'.
  7691. // This is not the complete set of editor methods. Most of the
  7692. // methods defined on the Doc type are also injected into
  7693. // CodeMirror.prototype, for backwards compatibility and
  7694. // convenience.
  7695. function addEditorMethods(CodeMirror) {
  7696. var optionHandlers = CodeMirror.optionHandlers;
  7697. var helpers = CodeMirror.helpers = {};
  7698. CodeMirror.prototype = {
  7699. constructor: CodeMirror,
  7700. focus: function () { win(this).focus(); this.display.input.focus(); },
  7701. setOption: function (option, value) {
  7702. var options = this.options, old = options[option];
  7703. if (options[option] == value && option != "mode") { return }
  7704. options[option] = value;
  7705. if (optionHandlers.hasOwnProperty(option))
  7706. { operation(this, optionHandlers[option])(this, value, old); }
  7707. signal(this, "optionChange", this, option);
  7708. },
  7709. getOption: function (option) { return this.options[option] },
  7710. getDoc: function () { return this.doc },
  7711. addKeyMap: function (map, bottom) {
  7712. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  7713. },
  7714. removeKeyMap: function (map) {
  7715. var maps = this.state.keyMaps;
  7716. for (var i = 0; i < maps.length; ++i) {
  7717. if (maps[i] == map || maps[i].name == map) {
  7718. maps.splice(i, 1);
  7719. return true
  7720. }
  7721. }
  7722. },
  7723. addOverlay: methodOp(function (spec, options) {
  7724. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7725. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7726. insertSorted(this.state.overlays,
  7727. {
  7728. mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7729. priority: (options && options.priority) || 0
  7730. },
  7731. function (overlay) { return overlay.priority; });
  7732. this.state.modeGen++;
  7733. regChange(this);
  7734. }),
  7735. removeOverlay: methodOp(function (spec) {
  7736. var overlays = this.state.overlays;
  7737. for (var i = 0; i < overlays.length; ++i) {
  7738. var cur = overlays[i].modeSpec;
  7739. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7740. overlays.splice(i, 1);
  7741. this.state.modeGen++;
  7742. regChange(this);
  7743. return
  7744. }
  7745. }
  7746. }),
  7747. indentLine: methodOp(function (n, dir, aggressive) {
  7748. if (typeof dir != "string" && typeof dir != "number") {
  7749. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7750. else { dir = dir ? "add" : "subtract"; }
  7751. }
  7752. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7753. }),
  7754. indentSelection: methodOp(function (how) {
  7755. var ranges = this.doc.sel.ranges, end = -1;
  7756. for (var i = 0; i < ranges.length; i++) {
  7757. var range = ranges[i];
  7758. if (!range.empty()) {
  7759. var from = range.from(), to = range.to();
  7760. var start = Math.max(end, from.line);
  7761. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7762. for (var j = start; j < end; ++j)
  7763. { indentLine(this, j, how); }
  7764. var newRanges = this.doc.sel.ranges;
  7765. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7766. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7767. } else if (range.head.line > end) {
  7768. indentLine(this, range.head.line, how, true);
  7769. end = range.head.line;
  7770. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  7771. }
  7772. }
  7773. }),
  7774. // Fetch the parser token for a given character. Useful for hacks
  7775. // that want to inspect the mode state (say, for completion).
  7776. getTokenAt: function (pos, precise) {
  7777. return takeToken(this, pos, precise)
  7778. },
  7779. getLineTokens: function (line, precise) {
  7780. return takeToken(this, Pos(line), precise, true)
  7781. },
  7782. getTokenTypeAt: function (pos) {
  7783. pos = clipPos(this.doc, pos);
  7784. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7785. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7786. var type;
  7787. if (ch == 0) { type = styles[2]; }
  7788. else {
  7789. for (; ;) {
  7790. var mid = (before + after) >> 1;
  7791. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7792. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7793. else { type = styles[mid * 2 + 2]; break }
  7794. }
  7795. }
  7796. var cut = type ? type.indexOf("overlay ") : -1;
  7797. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7798. },
  7799. getModeAt: function (pos) {
  7800. var mode = this.doc.mode;
  7801. if (!mode.innerMode) { return mode }
  7802. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7803. },
  7804. getHelper: function (pos, type) {
  7805. return this.getHelpers(pos, type)[0]
  7806. },
  7807. getHelpers: function (pos, type) {
  7808. var found = [];
  7809. if (!helpers.hasOwnProperty(type)) { return found }
  7810. var help = helpers[type], mode = this.getModeAt(pos);
  7811. if (typeof mode[type] == "string") {
  7812. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7813. } else if (mode[type]) {
  7814. for (var i = 0; i < mode[type].length; i++) {
  7815. var val = help[mode[type][i]];
  7816. if (val) { found.push(val); }
  7817. }
  7818. } else if (mode.helperType && help[mode.helperType]) {
  7819. found.push(help[mode.helperType]);
  7820. } else if (help[mode.name]) {
  7821. found.push(help[mode.name]);
  7822. }
  7823. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7824. var cur = help._global[i$1];
  7825. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  7826. { found.push(cur.val); }
  7827. }
  7828. return found
  7829. },
  7830. getStateAfter: function (line, precise) {
  7831. var doc = this.doc;
  7832. line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line);
  7833. return getContextBefore(this, line + 1, precise).state
  7834. },
  7835. cursorCoords: function (start, mode) {
  7836. var pos, range = this.doc.sel.primary();
  7837. if (start == null) { pos = range.head; }
  7838. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7839. else { pos = start ? range.from() : range.to(); }
  7840. return cursorCoords(this, pos, mode || "page")
  7841. },
  7842. charCoords: function (pos, mode) {
  7843. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7844. },
  7845. coordsChar: function (coords, mode) {
  7846. coords = fromCoordSystem(this, coords, mode || "page");
  7847. return coordsChar(this, coords.left, coords.top)
  7848. },
  7849. lineAtHeight: function (height, mode) {
  7850. height = fromCoordSystem(this, { top: height, left: 0 }, mode || "page").top;
  7851. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7852. },
  7853. heightAtLine: function (line, mode, includeWidgets) {
  7854. var end = false, lineObj;
  7855. if (typeof line == "number") {
  7856. var last = this.doc.first + this.doc.size - 1;
  7857. if (line < this.doc.first) { line = this.doc.first; }
  7858. else if (line > last) { line = last; end = true; }
  7859. lineObj = getLine(this.doc, line);
  7860. } else {
  7861. lineObj = line;
  7862. }
  7863. return intoCoordSystem(this, lineObj, { top: 0, left: 0 }, mode || "page", includeWidgets || end).top +
  7864. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7865. },
  7866. defaultTextHeight: function () { return textHeight(this.display) },
  7867. defaultCharWidth: function () { return charWidth(this.display) },
  7868. getViewport: function () { return { from: this.display.viewFrom, to: this.display.viewTo } },
  7869. addWidget: function (pos, node, scroll, vert, horiz) {
  7870. var display = this.display;
  7871. pos = cursorCoords(this, clipPos(this.doc, pos));
  7872. var top = pos.bottom, left = pos.left;
  7873. node.style.position = "absolute";
  7874. node.setAttribute("cm-ignore-events", "true");
  7875. this.display.input.setUneditable(node);
  7876. display.sizer.appendChild(node);
  7877. if (vert == "over") {
  7878. top = pos.top;
  7879. } else if (vert == "above" || vert == "near") {
  7880. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7881. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7882. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7883. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7884. { top = pos.top - node.offsetHeight; }
  7885. else if (pos.bottom + node.offsetHeight <= vspace)
  7886. { top = pos.bottom; }
  7887. if (left + node.offsetWidth > hspace)
  7888. { left = hspace - node.offsetWidth; }
  7889. }
  7890. node.style.top = top + "px";
  7891. node.style.left = node.style.right = "";
  7892. if (horiz == "right") {
  7893. left = display.sizer.clientWidth - node.offsetWidth;
  7894. node.style.right = "0px";
  7895. } else {
  7896. if (horiz == "left") { left = 0; }
  7897. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7898. node.style.left = left + "px";
  7899. }
  7900. if (scroll)
  7901. { scrollIntoView(this, { left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight }); }
  7902. },
  7903. triggerOnKeyDown: methodOp(onKeyDown),
  7904. triggerOnKeyPress: methodOp(onKeyPress),
  7905. triggerOnKeyUp: onKeyUp,
  7906. triggerOnMouseDown: methodOp(onMouseDown),
  7907. execCommand: function (cmd) {
  7908. if (commands.hasOwnProperty(cmd))
  7909. { return commands[cmd].call(null, this) }
  7910. },
  7911. triggerElectric: methodOp(function (text) { triggerElectric(this, text); }),
  7912. findPosH: function (from, amount, unit, visually) {
  7913. var dir = 1;
  7914. if (amount < 0) { dir = -1; amount = -amount; }
  7915. var cur = clipPos(this.doc, from);
  7916. for (var i = 0; i < amount; ++i) {
  7917. cur = findPosH(this.doc, cur, dir, unit, visually);
  7918. if (cur.hitSide) { break }
  7919. }
  7920. return cur
  7921. },
  7922. moveH: methodOp(function (dir, unit) {
  7923. var this$1 = this;
  7924. this.extendSelectionsBy(function (range) {
  7925. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7926. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7927. else
  7928. { return dir < 0 ? range.from() : range.to() }
  7929. }, sel_move);
  7930. }),
  7931. deleteH: methodOp(function (dir, unit) {
  7932. var sel = this.doc.sel, doc = this.doc;
  7933. if (sel.somethingSelected())
  7934. { doc.replaceSelection("", null, "+delete"); }
  7935. else
  7936. {
  7937. deleteNearSelection(this, function (range) {
  7938. var other = findPosH(doc, range.head, dir, unit, false);
  7939. return dir < 0 ? { from: other, to: range.head } : { from: range.head, to: other }
  7940. });
  7941. }
  7942. }),
  7943. findPosV: function (from, amount, unit, goalColumn) {
  7944. var dir = 1, x = goalColumn;
  7945. if (amount < 0) { dir = -1; amount = -amount; }
  7946. var cur = clipPos(this.doc, from);
  7947. for (var i = 0; i < amount; ++i) {
  7948. var coords = cursorCoords(this, cur, "div");
  7949. if (x == null) { x = coords.left; }
  7950. else { coords.left = x; }
  7951. cur = findPosV(this, coords, dir, unit);
  7952. if (cur.hitSide) { break }
  7953. }
  7954. return cur
  7955. },
  7956. moveV: methodOp(function (dir, unit) {
  7957. var this$1 = this;
  7958. var doc = this.doc, goals = [];
  7959. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7960. doc.extendSelectionsBy(function (range) {
  7961. if (collapse)
  7962. { return dir < 0 ? range.from() : range.to() }
  7963. var headPos = cursorCoords(this$1, range.head, "div");
  7964. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  7965. goals.push(headPos.left);
  7966. var pos = findPosV(this$1, headPos, dir, unit);
  7967. if (unit == "page" && range == doc.sel.primary())
  7968. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7969. return pos
  7970. }, sel_move);
  7971. if (goals.length) {
  7972. for (var i = 0; i < doc.sel.ranges.length; i++)
  7973. { doc.sel.ranges[i].goalColumn = goals[i]; }
  7974. }
  7975. }),
  7976. // Find the word at the given position (as returned by coordsChar).
  7977. findWordAt: function (pos) {
  7978. var doc = this.doc, line = getLine(doc, pos.line).text;
  7979. var start = pos.ch, end = pos.ch;
  7980. if (line) {
  7981. var helper = this.getHelper(pos, "wordChars");
  7982. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7983. var startChar = line.charAt(start);
  7984. var check = isWordChar(startChar, helper)
  7985. ? function (ch) { return isWordChar(ch, helper); }
  7986. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7987. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7988. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7989. while (end < line.length && check(line.charAt(end))) { ++end; }
  7990. }
  7991. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7992. },
  7993. toggleOverwrite: function (value) {
  7994. if (value != null && value == this.state.overwrite) { return }
  7995. if (this.state.overwrite = !this.state.overwrite)
  7996. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7997. else
  7998. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7999. signal(this, "overwriteToggle", this, this.state.overwrite);
  8000. },
  8001. hasFocus: function () { return this.display.input.getField() == activeElt(doc(this)) },
  8002. isReadOnly: function () { return !!(this.options.readOnly || this.doc.cantEdit) },
  8003. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  8004. getScrollInfo: function () {
  8005. var scroller = this.display.scroller;
  8006. return {
  8007. left: scroller.scrollLeft, top: scroller.scrollTop,
  8008. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  8009. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  8010. clientHeight: displayHeight(this), clientWidth: displayWidth(this)
  8011. }
  8012. },
  8013. scrollIntoView: methodOp(function (range, margin) {
  8014. if (range == null) {
  8015. range = { from: this.doc.sel.primary().head, to: null };
  8016. if (margin == null) { margin = this.options.cursorScrollMargin; }
  8017. } else if (typeof range == "number") {
  8018. range = { from: Pos(range, 0), to: null };
  8019. } else if (range.from == null) {
  8020. range = { from: range, to: null };
  8021. }
  8022. if (!range.to) { range.to = range.from; }
  8023. range.margin = margin || 0;
  8024. if (range.from.line != null) {
  8025. scrollToRange(this, range);
  8026. } else {
  8027. scrollToCoordsRange(this, range.from, range.to, range.margin);
  8028. }
  8029. }),
  8030. setSize: methodOp(function (width, height) {
  8031. var this$1 = this;
  8032. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  8033. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  8034. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  8035. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  8036. var lineNo = this.display.viewFrom;
  8037. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  8038. if (line.widgets) {
  8039. for (var i = 0; i < line.widgets.length; i++)
  8040. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } }
  8041. }
  8042. ++lineNo;
  8043. });
  8044. this.curOp.forceUpdate = true;
  8045. signal(this, "refresh", this);
  8046. }),
  8047. operation: function (f) { return runInOp(this, f) },
  8048. startOperation: function () { return startOperation(this) },
  8049. endOperation: function () { return endOperation(this) },
  8050. refresh: methodOp(function () {
  8051. var oldHeight = this.display.cachedTextHeight;
  8052. regChange(this);
  8053. this.curOp.forceUpdate = true;
  8054. clearCaches(this);
  8055. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  8056. updateGutterSpace(this.display);
  8057. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  8058. { estimateLineHeights(this); }
  8059. signal(this, "refresh", this);
  8060. }),
  8061. swapDoc: methodOp(function (doc) {
  8062. var old = this.doc;
  8063. old.cm = null;
  8064. // Cancel the current text selection if any (#5821)
  8065. if (this.state.selectingText) { this.state.selectingText(); }
  8066. attachDoc(this, doc);
  8067. clearCaches(this);
  8068. this.display.input.reset();
  8069. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  8070. this.curOp.forceScroll = true;
  8071. signalLater(this, "swapDoc", this, old);
  8072. return old
  8073. }),
  8074. phrase: function (phraseText) {
  8075. var phrases = this.options.phrases;
  8076. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  8077. },
  8078. getInputField: function () { return this.display.input.getField() },
  8079. getWrapperElement: function () { return this.display.wrapper },
  8080. getScrollerElement: function () { return this.display.scroller },
  8081. getGutterElement: function () { return this.display.gutters }
  8082. };
  8083. eventMixin(CodeMirror);
  8084. CodeMirror.registerHelper = function (type, name, value) {
  8085. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = { _global: [] }; }
  8086. helpers[type][name] = value;
  8087. };
  8088. CodeMirror.registerGlobalHelper = function (type, name, predicate, value) {
  8089. CodeMirror.registerHelper(type, name, value);
  8090. helpers[type]._global.push({ pred: predicate, val: value });
  8091. };
  8092. }
  8093. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  8094. // right), unit can be "codepoint", "char", "column" (like char, but
  8095. // doesn't cross line boundaries), "word" (across next word), or
  8096. // "group" (to the start of next group of word or
  8097. // non-word-non-whitespace chars). The visually param controls
  8098. // whether, in right-to-left text, direction 1 means to move towards
  8099. // the next index in the string, or towards the character to the right
  8100. // of the current position. The resulting position will have a
  8101. // hitSide=true property if it reached the end of the document.
  8102. function findPosH(doc, pos, dir, unit, visually) {
  8103. var oldPos = pos;
  8104. var origDir = dir;
  8105. var lineObj = getLine(doc, pos.line);
  8106. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  8107. function findNextLine() {
  8108. var l = pos.line + lineDir;
  8109. if (l < doc.first || l >= doc.first + doc.size) { return false }
  8110. pos = new Pos(l, pos.ch, pos.sticky);
  8111. return lineObj = getLine(doc, l)
  8112. }
  8113. function moveOnce(boundToLine) {
  8114. var next;
  8115. if (unit == "codepoint") {
  8116. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  8117. if (isNaN(ch)) {
  8118. next = null;
  8119. } else {
  8120. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  8121. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  8122. }
  8123. } else if (visually) {
  8124. next = moveVisually(doc.cm, lineObj, pos, dir);
  8125. } else {
  8126. next = moveLogically(lineObj, pos, dir);
  8127. }
  8128. if (next == null) {
  8129. if (!boundToLine && findNextLine())
  8130. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  8131. else
  8132. { return false }
  8133. } else {
  8134. pos = next;
  8135. }
  8136. return true
  8137. }
  8138. if (unit == "char" || unit == "codepoint") {
  8139. moveOnce();
  8140. } else if (unit == "column") {
  8141. moveOnce(true);
  8142. } else if (unit == "word" || unit == "group") {
  8143. var sawType = null, group = unit == "group";
  8144. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  8145. for (var first = true; ; first = false) {
  8146. if (dir < 0 && !moveOnce(!first)) { break }
  8147. var cur = lineObj.text.charAt(pos.ch) || "\n";
  8148. var type = isWordChar(cur, helper) ? "w"
  8149. : group && cur == "\n" ? "n"
  8150. : !group || /\s/.test(cur) ? null
  8151. : "p";
  8152. if (group && !first && !type) { type = "s"; }
  8153. if (sawType && sawType != type) {
  8154. if (dir < 0) { dir = 1; moveOnce(); pos.sticky = "after"; }
  8155. break
  8156. }
  8157. if (type) { sawType = type; }
  8158. if (dir > 0 && !moveOnce(!first)) { break }
  8159. }
  8160. }
  8161. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  8162. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  8163. return result
  8164. }
  8165. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  8166. // "page" or "line". The resulting position will have a hitSide=true
  8167. // property if it reached the end of the document.
  8168. function findPosV(cm, pos, dir, unit) {
  8169. var doc = cm.doc, x = pos.left, y;
  8170. if (unit == "page") {
  8171. var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);
  8172. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  8173. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  8174. } else if (unit == "line") {
  8175. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  8176. }
  8177. var target;
  8178. for (; ;) {
  8179. target = coordsChar(cm, x, y);
  8180. if (!target.outside) { break }
  8181. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  8182. y += dir * 5;
  8183. }
  8184. return target
  8185. }
  8186. // CONTENTEDITABLE INPUT STYLE
  8187. var ContentEditableInput = function (cm) {
  8188. this.cm = cm;
  8189. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  8190. this.polling = new Delayed();
  8191. this.composing = null;
  8192. this.gracePeriod = false;
  8193. this.readDOMTimeout = null;
  8194. };
  8195. ContentEditableInput.prototype.init = function (display) {
  8196. var this$1 = this;
  8197. var input = this, cm = input.cm;
  8198. var div = input.div = display.lineDiv;
  8199. div.contentEditable = true;
  8200. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  8201. function belongsToInput(e) {
  8202. for (var t = e.target; t; t = t.parentNode) {
  8203. if (t == div) { return true }
  8204. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  8205. }
  8206. return false
  8207. }
  8208. on(div, "paste", function (e) {
  8209. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8210. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  8211. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  8212. });
  8213. on(div, "compositionstart", function (e) {
  8214. this$1.composing = { data: e.data, done: false };
  8215. });
  8216. on(div, "compositionupdate", function (e) {
  8217. if (!this$1.composing) { this$1.composing = { data: e.data, done: false }; }
  8218. });
  8219. on(div, "compositionend", function (e) {
  8220. if (this$1.composing) {
  8221. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  8222. this$1.composing.done = true;
  8223. }
  8224. });
  8225. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  8226. on(div, "input", function () {
  8227. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  8228. });
  8229. function onCopyCut(e) {
  8230. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  8231. if (cm.somethingSelected()) {
  8232. setLastCopied({ lineWise: false, text: cm.getSelections() });
  8233. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  8234. } else if (!cm.options.lineWiseCopyCut) {
  8235. return
  8236. } else {
  8237. var ranges = copyableRanges(cm);
  8238. setLastCopied({ lineWise: true, text: ranges.text });
  8239. if (e.type == "cut") {
  8240. cm.operation(function () {
  8241. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  8242. cm.replaceSelection("", null, "cut");
  8243. });
  8244. }
  8245. }
  8246. if (e.clipboardData) {
  8247. e.clipboardData.clearData();
  8248. var content = lastCopied.text.join("\n");
  8249. // iOS exposes the clipboard API, but seems to discard content inserted into it
  8250. e.clipboardData.setData("Text", content);
  8251. if (e.clipboardData.getData("Text") == content) {
  8252. e.preventDefault();
  8253. return
  8254. }
  8255. }
  8256. // Old-fashioned briefly-focus-a-textarea hack
  8257. var kludge = hiddenTextarea(), te = kludge.firstChild;
  8258. disableBrowserMagic(te);
  8259. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  8260. te.value = lastCopied.text.join("\n");
  8261. var hadFocus = activeElt(div.ownerDocument);
  8262. selectInput(te);
  8263. setTimeout(function () {
  8264. cm.display.lineSpace.removeChild(kludge);
  8265. hadFocus.focus();
  8266. if (hadFocus == div) { input.showPrimarySelection(); }
  8267. }, 50);
  8268. }
  8269. on(div, "copy", onCopyCut);
  8270. on(div, "cut", onCopyCut);
  8271. };
  8272. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8273. // Label for screenreaders, accessibility
  8274. if (label) {
  8275. this.div.setAttribute('aria-label', label);
  8276. } else {
  8277. this.div.removeAttribute('aria-label');
  8278. }
  8279. };
  8280. ContentEditableInput.prototype.prepareSelection = function () {
  8281. var result = prepareSelection(this.cm, false);
  8282. result.focus = activeElt(this.div.ownerDocument) == this.div;
  8283. return result
  8284. };
  8285. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8286. if (!info || !this.cm.display.view.length) { return }
  8287. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8288. this.showMultipleSelections(info);
  8289. };
  8290. ContentEditableInput.prototype.getSelection = function () {
  8291. return this.cm.display.wrapper.ownerDocument.getSelection()
  8292. };
  8293. ContentEditableInput.prototype.showPrimarySelection = function () {
  8294. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8295. var from = prim.from(), to = prim.to();
  8296. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8297. sel.removeAllRanges();
  8298. return
  8299. }
  8300. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8301. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8302. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8303. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8304. cmp(maxPos(curAnchor, curFocus), to) == 0)
  8305. { return }
  8306. var view = cm.display.view;
  8307. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8308. { node: view[0].measure.map[2], offset: 0 };
  8309. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8310. if (!end) {
  8311. var measure = view[view.length - 1].measure;
  8312. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8313. end = { node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3] };
  8314. }
  8315. if (!start || !end) {
  8316. sel.removeAllRanges();
  8317. return
  8318. }
  8319. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8320. try { rng = range(start.node, start.offset, end.offset, end.node); }
  8321. catch (e) { } // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8322. if (rng) {
  8323. if (!gecko && cm.state.focused) {
  8324. sel.collapse(start.node, start.offset);
  8325. if (!rng.collapsed) {
  8326. sel.removeAllRanges();
  8327. sel.addRange(rng);
  8328. }
  8329. } else {
  8330. sel.removeAllRanges();
  8331. sel.addRange(rng);
  8332. }
  8333. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8334. else if (gecko) { this.startGracePeriod(); }
  8335. }
  8336. this.rememberSelection();
  8337. };
  8338. ContentEditableInput.prototype.startGracePeriod = function () {
  8339. var this$1 = this;
  8340. clearTimeout(this.gracePeriod);
  8341. this.gracePeriod = setTimeout(function () {
  8342. this$1.gracePeriod = false;
  8343. if (this$1.selectionChanged())
  8344. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8345. }, 20);
  8346. };
  8347. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8348. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8349. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8350. };
  8351. ContentEditableInput.prototype.rememberSelection = function () {
  8352. var sel = this.getSelection();
  8353. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8354. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8355. };
  8356. ContentEditableInput.prototype.selectionInEditor = function () {
  8357. var sel = this.getSelection();
  8358. if (!sel.rangeCount) { return false }
  8359. var node = sel.getRangeAt(0).commonAncestorContainer;
  8360. return contains(this.div, node)
  8361. };
  8362. ContentEditableInput.prototype.focus = function () {
  8363. if (this.cm.options.readOnly != "nocursor") {
  8364. if (!this.selectionInEditor() || activeElt(this.div.ownerDocument) != this.div)
  8365. { this.showSelection(this.prepareSelection(), true); }
  8366. this.div.focus();
  8367. }
  8368. };
  8369. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8370. ContentEditableInput.prototype.getField = function () { return this.div };
  8371. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8372. ContentEditableInput.prototype.receivedFocus = function () {
  8373. var this$1 = this;
  8374. var input = this;
  8375. if (this.selectionInEditor())
  8376. { setTimeout(function () { return this$1.pollSelection(); }, 20); }
  8377. else
  8378. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8379. function poll() {
  8380. if (input.cm.state.focused) {
  8381. input.pollSelection();
  8382. input.polling.set(input.cm.options.pollInterval, poll);
  8383. }
  8384. }
  8385. this.polling.set(this.cm.options.pollInterval, poll);
  8386. };
  8387. ContentEditableInput.prototype.selectionChanged = function () {
  8388. var sel = this.getSelection();
  8389. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8390. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8391. };
  8392. ContentEditableInput.prototype.pollSelection = function () {
  8393. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8394. var sel = this.getSelection(), cm = this.cm;
  8395. // On Android Chrome (version 56, at least), backspacing into an
  8396. // uneditable block element will put the cursor in that element,
  8397. // and then, because it's not editable, hide the virtual keyboard.
  8398. // Because Android doesn't allow us to actually detect backspace
  8399. // presses in a sane way, this code checks for when that happens
  8400. // and simulates a backspace press in this case.
  8401. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8402. this.cm.triggerOnKeyDown({ type: "keydown", keyCode: 8, preventDefault: Math.abs });
  8403. this.blur();
  8404. this.focus();
  8405. return
  8406. }
  8407. if (this.composing) { return }
  8408. this.rememberSelection();
  8409. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8410. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8411. if (anchor && head) {
  8412. runInOp(cm, function () {
  8413. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8414. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8415. });
  8416. }
  8417. };
  8418. ContentEditableInput.prototype.pollContent = function () {
  8419. if (this.readDOMTimeout != null) {
  8420. clearTimeout(this.readDOMTimeout);
  8421. this.readDOMTimeout = null;
  8422. }
  8423. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8424. var from = sel.from(), to = sel.to();
  8425. if (from.ch == 0 && from.line > cm.firstLine())
  8426. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8427. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8428. { to = Pos(to.line + 1, 0); }
  8429. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8430. var fromIndex, fromLine, fromNode;
  8431. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8432. fromLine = lineNo(display.view[0].line);
  8433. fromNode = display.view[0].node;
  8434. } else {
  8435. fromLine = lineNo(display.view[fromIndex].line);
  8436. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8437. }
  8438. var toIndex = findViewIndex(cm, to.line);
  8439. var toLine, toNode;
  8440. if (toIndex == display.view.length - 1) {
  8441. toLine = display.viewTo - 1;
  8442. toNode = display.lineDiv.lastChild;
  8443. } else {
  8444. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8445. toNode = display.view[toIndex + 1].node.previousSibling;
  8446. }
  8447. if (!fromNode) { return false }
  8448. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8449. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8450. while (newText.length > 1 && oldText.length > 1) {
  8451. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8452. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8453. else { break }
  8454. }
  8455. var cutFront = 0, cutEnd = 0;
  8456. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8457. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8458. { ++cutFront; }
  8459. var newBot = lst(newText), oldBot = lst(oldText);
  8460. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8461. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8462. while (cutEnd < maxCutEnd &&
  8463. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8464. { ++cutEnd; }
  8465. // Try to move start of change to start of selection if ambiguous
  8466. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8467. while (cutFront && cutFront > from.ch &&
  8468. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8469. cutFront--;
  8470. cutEnd++;
  8471. }
  8472. }
  8473. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8474. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8475. var chFrom = Pos(fromLine, cutFront);
  8476. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8477. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8478. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8479. return true
  8480. }
  8481. };
  8482. ContentEditableInput.prototype.ensurePolled = function () {
  8483. this.forceCompositionEnd();
  8484. };
  8485. ContentEditableInput.prototype.reset = function () {
  8486. this.forceCompositionEnd();
  8487. };
  8488. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8489. if (!this.composing) { return }
  8490. clearTimeout(this.readDOMTimeout);
  8491. this.composing = null;
  8492. this.updateFromDOM();
  8493. this.div.blur();
  8494. this.div.focus();
  8495. };
  8496. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8497. var this$1 = this;
  8498. if (this.readDOMTimeout != null) { return }
  8499. this.readDOMTimeout = setTimeout(function () {
  8500. this$1.readDOMTimeout = null;
  8501. if (this$1.composing) {
  8502. if (this$1.composing.done) { this$1.composing = null; }
  8503. else { return }
  8504. }
  8505. this$1.updateFromDOM();
  8506. }, 80);
  8507. };
  8508. ContentEditableInput.prototype.updateFromDOM = function () {
  8509. var this$1 = this;
  8510. if (this.cm.isReadOnly() || !this.pollContent())
  8511. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8512. };
  8513. ContentEditableInput.prototype.setUneditable = function (node) {
  8514. node.contentEditable = "false";
  8515. };
  8516. ContentEditableInput.prototype.onKeyPress = function (e) {
  8517. if (e.charCode == 0 || this.composing) { return }
  8518. e.preventDefault();
  8519. if (!this.cm.isReadOnly())
  8520. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8521. };
  8522. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8523. this.div.contentEditable = String(val != "nocursor");
  8524. };
  8525. ContentEditableInput.prototype.onContextMenu = function () { };
  8526. ContentEditableInput.prototype.resetPosition = function () { };
  8527. ContentEditableInput.prototype.needsContentAttribute = true;
  8528. function posToDOM(cm, pos) {
  8529. var view = findViewForLine(cm, pos.line);
  8530. if (!view || view.hidden) { return null }
  8531. var line = getLine(cm.doc, pos.line);
  8532. var info = mapFromLineView(view, line, pos.line);
  8533. var order = getOrder(line, cm.doc.direction), side = "left";
  8534. if (order) {
  8535. var partPos = getBidiPartAt(order, pos.ch);
  8536. side = partPos % 2 ? "right" : "left";
  8537. }
  8538. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8539. result.offset = result.collapse == "right" ? result.end : result.start;
  8540. return result
  8541. }
  8542. function isInGutter(node) {
  8543. for (var scan = node; scan; scan = scan.parentNode)
  8544. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8545. return false
  8546. }
  8547. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8548. function domTextBetween(cm, from, to, fromLine, toLine) {
  8549. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8550. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8551. function close() {
  8552. if (closing) {
  8553. text += lineSep;
  8554. if (extraLinebreak) { text += lineSep; }
  8555. closing = extraLinebreak = false;
  8556. }
  8557. }
  8558. function addText(str) {
  8559. if (str) {
  8560. close();
  8561. text += str;
  8562. }
  8563. }
  8564. function walk(node) {
  8565. if (node.nodeType == 1) {
  8566. var cmText = node.getAttribute("cm-text");
  8567. if (cmText) {
  8568. addText(cmText);
  8569. return
  8570. }
  8571. var markerID = node.getAttribute("cm-marker"), range;
  8572. if (markerID) {
  8573. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8574. if (found.length && (range = found[0].find(0)))
  8575. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  8576. return
  8577. }
  8578. if (node.getAttribute("contenteditable") == "false") { return }
  8579. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8580. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8581. if (isBlock) { close(); }
  8582. for (var i = 0; i < node.childNodes.length; i++)
  8583. { walk(node.childNodes[i]); }
  8584. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8585. if (isBlock) { closing = true; }
  8586. } else if (node.nodeType == 3) {
  8587. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8588. }
  8589. }
  8590. for (; ;) {
  8591. walk(from);
  8592. if (from == to) { break }
  8593. from = from.nextSibling;
  8594. extraLinebreak = false;
  8595. }
  8596. return text
  8597. }
  8598. function domToPos(cm, node, offset) {
  8599. var lineNode;
  8600. if (node == cm.display.lineDiv) {
  8601. lineNode = cm.display.lineDiv.childNodes[offset];
  8602. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8603. node = null; offset = 0;
  8604. } else {
  8605. for (lineNode = node; ; lineNode = lineNode.parentNode) {
  8606. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8607. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8608. }
  8609. }
  8610. for (var i = 0; i < cm.display.view.length; i++) {
  8611. var lineView = cm.display.view[i];
  8612. if (lineView.node == lineNode)
  8613. { return locateNodeInLineView(lineView, node, offset) }
  8614. }
  8615. }
  8616. function locateNodeInLineView(lineView, node, offset) {
  8617. var wrapper = lineView.text.firstChild, bad = false;
  8618. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8619. if (node == wrapper) {
  8620. bad = true;
  8621. node = wrapper.childNodes[offset];
  8622. offset = 0;
  8623. if (!node) {
  8624. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8625. return badPos(Pos(lineNo(line), line.text.length), bad)
  8626. }
  8627. }
  8628. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8629. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8630. textNode = node.firstChild;
  8631. if (offset) { offset = textNode.nodeValue.length; }
  8632. }
  8633. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8634. var measure = lineView.measure, maps = measure.maps;
  8635. function find(textNode, topNode, offset) {
  8636. for (var i = -1; i < (maps ? maps.length : 0) ; i++) {
  8637. var map = i < 0 ? measure.map : maps[i];
  8638. for (var j = 0; j < map.length; j += 3) {
  8639. var curNode = map[j + 2];
  8640. if (curNode == textNode || curNode == topNode) {
  8641. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8642. var ch = map[j] + offset;
  8643. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  8644. return Pos(line, ch)
  8645. }
  8646. }
  8647. }
  8648. }
  8649. var found = find(textNode, topNode, offset);
  8650. if (found) { return badPos(found, bad) }
  8651. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8652. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8653. found = find(after, after.firstChild, 0);
  8654. if (found)
  8655. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8656. else
  8657. { dist += after.textContent.length; }
  8658. }
  8659. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8660. found = find(before, before.firstChild, -1);
  8661. if (found)
  8662. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8663. else
  8664. { dist$1 += before.textContent.length; }
  8665. }
  8666. }
  8667. // TEXTAREA INPUT STYLE
  8668. var TextareaInput = function (cm) {
  8669. this.cm = cm;
  8670. // See input.poll and input.reset
  8671. this.prevInput = "";
  8672. // Flag that indicates whether we expect input to appear real soon
  8673. // now (after some event like 'keypress' or 'input') and are
  8674. // polling intensively.
  8675. this.pollingFast = false;
  8676. // Self-resetting timeout for the poller
  8677. this.polling = new Delayed();
  8678. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8679. this.hasSelection = false;
  8680. this.composing = null;
  8681. this.resetting = false;
  8682. };
  8683. TextareaInput.prototype.init = function (display) {
  8684. var this$1 = this;
  8685. var input = this, cm = this.cm;
  8686. this.createField(display);
  8687. var te = this.textarea;
  8688. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8689. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8690. if (ios) { te.style.width = "0px"; }
  8691. on(te, "input", function () {
  8692. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8693. input.poll();
  8694. });
  8695. on(te, "paste", function (e) {
  8696. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8697. cm.state.pasteIncoming = +new Date;
  8698. input.fastPoll();
  8699. });
  8700. function prepareCopyCut(e) {
  8701. if (signalDOMEvent(cm, e)) { return }
  8702. if (cm.somethingSelected()) {
  8703. setLastCopied({ lineWise: false, text: cm.getSelections() });
  8704. } else if (!cm.options.lineWiseCopyCut) {
  8705. return
  8706. } else {
  8707. var ranges = copyableRanges(cm);
  8708. setLastCopied({ lineWise: true, text: ranges.text });
  8709. if (e.type == "cut") {
  8710. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8711. } else {
  8712. input.prevInput = "";
  8713. te.value = ranges.text.join("\n");
  8714. selectInput(te);
  8715. }
  8716. }
  8717. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8718. }
  8719. on(te, "cut", prepareCopyCut);
  8720. on(te, "copy", prepareCopyCut);
  8721. on(display.scroller, "paste", function (e) {
  8722. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8723. if (!te.dispatchEvent) {
  8724. cm.state.pasteIncoming = +new Date;
  8725. input.focus();
  8726. return
  8727. }
  8728. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8729. var event = new Event("paste");
  8730. event.clipboardData = e.clipboardData;
  8731. te.dispatchEvent(event);
  8732. });
  8733. // Prevent normal selection in the editor (we handle our own)
  8734. on(display.lineSpace, "selectstart", function (e) {
  8735. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8736. });
  8737. on(te, "compositionstart", function () {
  8738. var start = cm.getCursor("from");
  8739. if (input.composing) { input.composing.range.clear(); }
  8740. input.composing = {
  8741. start: start,
  8742. range: cm.markText(start, cm.getCursor("to"), { className: "CodeMirror-composing" })
  8743. };
  8744. });
  8745. on(te, "compositionend", function () {
  8746. if (input.composing) {
  8747. input.poll();
  8748. input.composing.range.clear();
  8749. input.composing = null;
  8750. }
  8751. });
  8752. };
  8753. TextareaInput.prototype.createField = function (_display) {
  8754. // Wraps and hides input textarea
  8755. this.wrapper = hiddenTextarea();
  8756. // The semihidden textarea that is focused when the editor is
  8757. // focused, and receives input.
  8758. this.textarea = this.wrapper.firstChild;
  8759. var opts = this.cm.options;
  8760. disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);
  8761. };
  8762. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  8763. // Label for screenreaders, accessibility
  8764. if (label) {
  8765. this.textarea.setAttribute('aria-label', label);
  8766. } else {
  8767. this.textarea.removeAttribute('aria-label');
  8768. }
  8769. };
  8770. TextareaInput.prototype.prepareSelection = function () {
  8771. // Redraw the selection and/or cursor
  8772. var cm = this.cm, display = cm.display, doc = cm.doc;
  8773. var result = prepareSelection(cm);
  8774. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8775. if (cm.options.moveInputWithCursor) {
  8776. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8777. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8778. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8779. headPos.top + lineOff.top - wrapOff.top));
  8780. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8781. headPos.left + lineOff.left - wrapOff.left));
  8782. }
  8783. return result
  8784. };
  8785. TextareaInput.prototype.showSelection = function (drawn) {
  8786. var cm = this.cm, display = cm.display;
  8787. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8788. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8789. if (drawn.teTop != null) {
  8790. this.wrapper.style.top = drawn.teTop + "px";
  8791. this.wrapper.style.left = drawn.teLeft + "px";
  8792. }
  8793. };
  8794. // Reset the input to correspond to the selection (or to be empty,
  8795. // when not typing and nothing is selected)
  8796. TextareaInput.prototype.reset = function (typing) {
  8797. if (this.contextMenuPending || this.composing && typing) { return }
  8798. var cm = this.cm;
  8799. this.resetting = true;
  8800. if (cm.somethingSelected()) {
  8801. this.prevInput = "";
  8802. var content = cm.getSelection();
  8803. this.textarea.value = content;
  8804. if (cm.state.focused) { selectInput(this.textarea); }
  8805. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8806. } else if (!typing) {
  8807. this.prevInput = this.textarea.value = "";
  8808. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8809. }
  8810. this.resetting = false;
  8811. };
  8812. TextareaInput.prototype.getField = function () { return this.textarea };
  8813. TextareaInput.prototype.supportsTouch = function () { return false };
  8814. TextareaInput.prototype.focus = function () {
  8815. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(this.textarea.ownerDocument) != this.textarea)) {
  8816. try { this.textarea.focus(); }
  8817. catch (e) { } // IE8 will throw if the textarea is display: none or not in DOM
  8818. }
  8819. };
  8820. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8821. TextareaInput.prototype.resetPosition = function () {
  8822. this.wrapper.style.top = this.wrapper.style.left = 0;
  8823. };
  8824. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8825. // Poll for input changes, using the normal rate of polling. This
  8826. // runs as long as the editor is focused.
  8827. TextareaInput.prototype.slowPoll = function () {
  8828. var this$1 = this;
  8829. if (this.pollingFast) { return }
  8830. this.polling.set(this.cm.options.pollInterval, function () {
  8831. this$1.poll();
  8832. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8833. });
  8834. };
  8835. // When an event has just come in that is likely to add or change
  8836. // something in the input textarea, we poll faster, to ensure that
  8837. // the change appears on the screen quickly.
  8838. TextareaInput.prototype.fastPoll = function () {
  8839. var missed = false, input = this;
  8840. input.pollingFast = true;
  8841. function p() {
  8842. var changed = input.poll();
  8843. if (!changed && !missed) { missed = true; input.polling.set(60, p); }
  8844. else { input.pollingFast = false; input.slowPoll(); }
  8845. }
  8846. input.polling.set(20, p);
  8847. };
  8848. // Read input from the textarea, and update the document to match.
  8849. // When something is selected, it is present in the textarea, and
  8850. // selected (unless it is huge, in which case a placeholder is
  8851. // used). When nothing is selected, the cursor sits after previously
  8852. // seen text (can be empty), which is stored in prevInput (we must
  8853. // not reset the textarea when typing, because that breaks IME).
  8854. TextareaInput.prototype.poll = function () {
  8855. var this$1 = this;
  8856. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8857. // Since this is called a *lot*, try to bail out as cheaply as
  8858. // possible when it is clear that nothing happened. hasSelection
  8859. // will be the case when there is a lot of text in the textarea,
  8860. // in which case reading its value would be expensive.
  8861. if (this.contextMenuPending || this.resetting || !cm.state.focused ||
  8862. (hasSelection(input) && !prevInput && !this.composing) ||
  8863. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8864. { return false }
  8865. var text = input.value;
  8866. // If nothing changed, bail.
  8867. if (text == prevInput && !cm.somethingSelected()) { return false }
  8868. // Work around nonsensical selection resetting in IE9/10, and
  8869. // inexplicable appearance of private area unicode characters on
  8870. // some key combos in Mac (#2689).
  8871. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8872. mac && /[\uf700-\uf7ff]/.test(text)) {
  8873. cm.display.input.reset();
  8874. return false
  8875. }
  8876. if (cm.doc.sel == cm.display.selForContextMenu) {
  8877. var first = text.charCodeAt(0);
  8878. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8879. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8880. }
  8881. // Find the part of the input that is actually new
  8882. var same = 0, l = Math.min(prevInput.length, text.length);
  8883. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8884. runInOp(cm, function () {
  8885. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8886. null, this$1.composing ? "*compose" : null);
  8887. // Don't leave long text in the textarea, since it makes further polling slow
  8888. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8889. else { this$1.prevInput = text; }
  8890. if (this$1.composing) {
  8891. this$1.composing.range.clear();
  8892. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8893. { className: "CodeMirror-composing" });
  8894. }
  8895. });
  8896. return true
  8897. };
  8898. TextareaInput.prototype.ensurePolled = function () {
  8899. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8900. };
  8901. TextareaInput.prototype.onKeyPress = function () {
  8902. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8903. this.fastPoll();
  8904. };
  8905. TextareaInput.prototype.onContextMenu = function (e) {
  8906. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8907. if (input.contextMenuPending) { input.contextMenuPending(); }
  8908. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8909. if (!pos || presto) { return } // Opera is difficult.
  8910. // Reset the current text selection only if the click is done outside of the selection
  8911. // and 'resetSelectionOnContextMenu' option is true.
  8912. var reset = cm.options.resetSelectionOnContextMenu;
  8913. if (reset && cm.doc.sel.contains(pos) == -1)
  8914. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8915. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8916. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8917. input.wrapper.style.cssText = "position: static";
  8918. te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  8919. var oldScrollY;
  8920. if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)
  8921. display.input.focus();
  8922. if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }
  8923. display.input.reset();
  8924. // Adds "Select all" to context menu in FF
  8925. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8926. input.contextMenuPending = rehide;
  8927. display.selForContextMenu = cm.doc.sel;
  8928. clearTimeout(display.detectingSelectAll);
  8929. // Select-all will be greyed out if there's nothing to select, so
  8930. // this adds a zero-width space so that we can later check whether
  8931. // it got selected.
  8932. function prepareSelectAllHack() {
  8933. if (te.selectionStart != null) {
  8934. var selected = cm.somethingSelected();
  8935. var extval = "\u200b" + (selected ? te.value : "");
  8936. te.value = "\u21da"; // Used to catch context-menu undo
  8937. te.value = extval;
  8938. input.prevInput = selected ? "" : "\u200b";
  8939. te.selectionStart = 1; te.selectionEnd = extval.length;
  8940. // Re-set this, in case some other handler touched the
  8941. // selection in the meantime.
  8942. display.selForContextMenu = cm.doc.sel;
  8943. }
  8944. }
  8945. function rehide() {
  8946. if (input.contextMenuPending != rehide) { return }
  8947. input.contextMenuPending = false;
  8948. input.wrapper.style.cssText = oldWrapperCSS;
  8949. te.style.cssText = oldCSS;
  8950. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8951. // Try to detect the user choosing select-all
  8952. if (te.selectionStart != null) {
  8953. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8954. var i = 0, poll = function () {
  8955. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8956. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8957. operation(cm, selectAll)(cm);
  8958. } else if (i++ < 10) {
  8959. display.detectingSelectAll = setTimeout(poll, 500);
  8960. } else {
  8961. display.selForContextMenu = null;
  8962. display.input.reset();
  8963. }
  8964. };
  8965. display.detectingSelectAll = setTimeout(poll, 200);
  8966. }
  8967. }
  8968. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8969. if (captureRightClick) {
  8970. e_stop(e);
  8971. var mouseup = function () {
  8972. off(window, "mouseup", mouseup);
  8973. setTimeout(rehide, 20);
  8974. };
  8975. on(window, "mouseup", mouseup);
  8976. } else {
  8977. setTimeout(rehide, 50);
  8978. }
  8979. };
  8980. TextareaInput.prototype.readOnlyChanged = function (val) {
  8981. if (!val) { this.reset(); }
  8982. this.textarea.disabled = val == "nocursor";
  8983. this.textarea.readOnly = !!val;
  8984. };
  8985. TextareaInput.prototype.setUneditable = function () { };
  8986. TextareaInput.prototype.needsContentAttribute = false;
  8987. function fromTextArea(textarea, options) {
  8988. options = options ? copyObj(options) : {};
  8989. options.value = textarea.value;
  8990. if (!options.tabindex && textarea.tabIndex)
  8991. { options.tabindex = textarea.tabIndex; }
  8992. if (!options.placeholder && textarea.placeholder)
  8993. { options.placeholder = textarea.placeholder; }
  8994. // Set autofocus to true if this textarea is focused, or if it has
  8995. // autofocus and no other element is focused.
  8996. if (options.autofocus == null) {
  8997. var hasFocus = activeElt(textarea.ownerDocument);
  8998. options.autofocus = hasFocus == textarea ||
  8999. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  9000. }
  9001. function save() { textarea.value = cm.getValue(); }
  9002. var realSubmit;
  9003. if (textarea.form) {
  9004. on(textarea.form, "submit", save);
  9005. // Deplorable hack to make the submit method do the right thing.
  9006. if (!options.leaveSubmitMethodAlone) {
  9007. var form = textarea.form;
  9008. realSubmit = form.submit;
  9009. try {
  9010. var wrappedSubmit = form.submit = function () {
  9011. save();
  9012. form.submit = realSubmit;
  9013. form.submit();
  9014. form.submit = wrappedSubmit;
  9015. };
  9016. } catch (e) { }
  9017. }
  9018. }
  9019. options.finishInit = function (cm) {
  9020. cm.save = save;
  9021. cm.getTextArea = function () { return textarea; };
  9022. cm.toTextArea = function () {
  9023. cm.toTextArea = isNaN; // Prevent this from being ran twice
  9024. save();
  9025. textarea.parentNode.removeChild(cm.getWrapperElement());
  9026. textarea.style.display = "";
  9027. if (textarea.form) {
  9028. off(textarea.form, "submit", save);
  9029. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  9030. { textarea.form.submit = realSubmit; }
  9031. }
  9032. };
  9033. };
  9034. textarea.style.display = "none";
  9035. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  9036. options);
  9037. return cm
  9038. }
  9039. function addLegacyProps(CodeMirror) {
  9040. CodeMirror.off = off;
  9041. CodeMirror.on = on;
  9042. CodeMirror.wheelEventPixels = wheelEventPixels;
  9043. CodeMirror.Doc = Doc;
  9044. CodeMirror.splitLines = splitLinesAuto;
  9045. CodeMirror.countColumn = countColumn;
  9046. CodeMirror.findColumn = findColumn;
  9047. CodeMirror.isWordChar = isWordCharBasic;
  9048. CodeMirror.Pass = Pass;
  9049. CodeMirror.signal = signal;
  9050. CodeMirror.Line = Line;
  9051. CodeMirror.changeEnd = changeEnd;
  9052. CodeMirror.scrollbarModel = scrollbarModel;
  9053. CodeMirror.Pos = Pos;
  9054. CodeMirror.cmpPos = cmp;
  9055. CodeMirror.modes = modes;
  9056. CodeMirror.mimeModes = mimeModes;
  9057. CodeMirror.resolveMode = resolveMode;
  9058. CodeMirror.getMode = getMode;
  9059. CodeMirror.modeExtensions = modeExtensions;
  9060. CodeMirror.extendMode = extendMode;
  9061. CodeMirror.copyState = copyState;
  9062. CodeMirror.startState = startState;
  9063. CodeMirror.innerMode = innerMode;
  9064. CodeMirror.commands = commands;
  9065. CodeMirror.keyMap = keyMap;
  9066. CodeMirror.keyName = keyName;
  9067. CodeMirror.isModifierKey = isModifierKey;
  9068. CodeMirror.lookupKey = lookupKey;
  9069. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  9070. CodeMirror.StringStream = StringStream;
  9071. CodeMirror.SharedTextMarker = SharedTextMarker;
  9072. CodeMirror.TextMarker = TextMarker;
  9073. CodeMirror.LineWidget = LineWidget;
  9074. CodeMirror.e_preventDefault = e_preventDefault;
  9075. CodeMirror.e_stopPropagation = e_stopPropagation;
  9076. CodeMirror.e_stop = e_stop;
  9077. CodeMirror.addClass = addClass;
  9078. CodeMirror.contains = contains;
  9079. CodeMirror.rmClass = rmClass;
  9080. CodeMirror.keyNames = keyNames;
  9081. }
  9082. // EDITOR CONSTRUCTOR
  9083. defineOptions(CodeMirror);
  9084. addEditorMethods(CodeMirror);
  9085. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  9086. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  9087. for (var prop in Doc.prototype) {
  9088. if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) {
  9089. CodeMirror.prototype[prop] = (function (method) {
  9090. return function () { return method.apply(this.doc, arguments) }
  9091. })(Doc.prototype[prop]);
  9092. }
  9093. }
  9094. eventMixin(Doc);
  9095. CodeMirror.inputStyles = { "textarea": TextareaInput, "contenteditable": ContentEditableInput };
  9096. // Extra arguments are stored as the mode's dependencies, which is
  9097. // used by (legacy) mechanisms like loadmode.js to automatically
  9098. // load a mode. (Preferred mechanism is the require/define calls.)
  9099. CodeMirror.defineMode = function (name/*, mode, ¡­*/) {
  9100. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  9101. defineMode.apply(this, arguments);
  9102. };
  9103. CodeMirror.defineMIME = defineMIME;
  9104. // Minimal default mode.
  9105. CodeMirror.defineMode("null", function () { return ({ token: function (stream) { return stream.skipToEnd(); } }); });
  9106. CodeMirror.defineMIME("text/plain", "null");
  9107. // EXTENSIONS
  9108. CodeMirror.defineExtension = function (name, func) {
  9109. CodeMirror.prototype[name] = func;
  9110. };
  9111. CodeMirror.defineDocExtension = function (name, func) {
  9112. Doc.prototype[name] = func;
  9113. };
  9114. CodeMirror.fromTextArea = fromTextArea;
  9115. addLegacyProps(CodeMirror);
  9116. CodeMirror.version = "5.65.13";
  9117. return CodeMirror;
  9118. })));