codemirror.js 339 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global.CodeMirror = factory());
  12. }(this, (function () { 'use strict';
  13. // Kludges for bugs and behavior differences that can't be feature
  14. // detected are enabled based on userAgent etc sniffing.
  15. var userAgent = navigator.userAgent
  16. var platform = navigator.platform
  17. var gecko = /gecko\/\d/i.test(userAgent)
  18. var ie_upto10 = /MSIE \d/.test(userAgent)
  19. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
  20. var ie = ie_upto10 || ie_11up
  21. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1])
  22. var webkit = /WebKit\//.test(userAgent)
  23. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
  24. var chrome = /Chrome\//.test(userAgent)
  25. var presto = /Opera\//.test(userAgent)
  26. var safari = /Apple Computer/.test(navigator.vendor)
  27. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
  28. var phantom = /PhantomJS/.test(userAgent)
  29. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent)
  30. // This is woefully incomplete. Suggestions for alternative methods welcome.
  31. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
  32. var mac = ios || /Mac/.test(platform)
  33. var chromeOS = /\bCrOS\b/.test(userAgent)
  34. var windows = /win/i.test(platform)
  35. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
  36. if (presto_version) { presto_version = Number(presto_version[1]) }
  37. if (presto_version && presto_version >= 15) { presto = false; webkit = true }
  38. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  39. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))
  40. var captureRightClick = gecko || (ie && ie_version >= 9)
  41. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  42. var rmClass = function(node, cls) {
  43. var current = node.className
  44. var match = classTest(cls).exec(current)
  45. if (match) {
  46. var after = current.slice(match.index + match[0].length)
  47. node.className = current.slice(0, match.index) + (after ? match[1] + after : "")
  48. }
  49. }
  50. function removeChildren(e) {
  51. for (var count = e.childNodes.length; count > 0; --count)
  52. { e.removeChild(e.firstChild) }
  53. return e
  54. }
  55. function removeChildrenAndAdd(parent, e) {
  56. return removeChildren(parent).appendChild(e)
  57. }
  58. function elt(tag, content, className, style) {
  59. var e = document.createElement(tag)
  60. if (className) { e.className = className }
  61. if (style) { e.style.cssText = style }
  62. if (typeof content == "string") { e.appendChild(document.createTextNode(content)) }
  63. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } }
  64. return e
  65. }
  66. var range
  67. if (document.createRange) { range = function(node, start, end, endNode) {
  68. var r = document.createRange()
  69. r.setEnd(endNode || node, end)
  70. r.setStart(node, start)
  71. return r
  72. } }
  73. else { range = function(node, start, end) {
  74. var r = document.body.createTextRange()
  75. try { r.moveToElementText(node.parentNode) }
  76. catch(e) { return r }
  77. r.collapse(true)
  78. r.moveEnd("character", end)
  79. r.moveStart("character", start)
  80. return r
  81. } }
  82. function contains(parent, child) {
  83. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  84. { child = child.parentNode }
  85. if (parent.contains)
  86. { return parent.contains(child) }
  87. do {
  88. if (child.nodeType == 11) { child = child.host }
  89. if (child == parent) { return true }
  90. } while (child = child.parentNode)
  91. }
  92. function activeElt() {
  93. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  94. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  95. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  96. var activeElement
  97. try {
  98. activeElement = document.activeElement
  99. } catch(e) {
  100. activeElement = document.body || null
  101. }
  102. while (activeElement && activeElement.root && activeElement.root.activeElement)
  103. { activeElement = activeElement.root.activeElement }
  104. return activeElement
  105. }
  106. function addClass(node, cls) {
  107. var current = node.className
  108. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
  109. }
  110. function joinClasses(a, b) {
  111. var as = a.split(" ")
  112. for (var i = 0; i < as.length; i++)
  113. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
  114. return b
  115. }
  116. var selectInput = function(node) { node.select() }
  117. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  118. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
  119. else if (ie) // Suppress mysterious IE10 errors
  120. { selectInput = function(node) { try { node.select() } catch(_e) {} } }
  121. function bind(f) {
  122. var args = Array.prototype.slice.call(arguments, 1)
  123. return function(){return f.apply(null, args)}
  124. }
  125. function copyObj(obj, target, overwrite) {
  126. if (!target) { target = {} }
  127. for (var prop in obj)
  128. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  129. { target[prop] = obj[prop] } }
  130. return target
  131. }
  132. // Counts the column offset in a string, taking tabs into account.
  133. // Used mostly to find indentation.
  134. function countColumn(string, end, tabSize, startIndex, startValue) {
  135. if (end == null) {
  136. end = string.search(/[^\s\u00a0]/)
  137. if (end == -1) { end = string.length }
  138. }
  139. for (var i = startIndex || 0, n = startValue || 0;;) {
  140. var nextTab = string.indexOf("\t", i)
  141. if (nextTab < 0 || nextTab >= end)
  142. { return n + (end - i) }
  143. n += nextTab - i
  144. n += tabSize - (n % tabSize)
  145. i = nextTab + 1
  146. }
  147. }
  148. function Delayed() {this.id = null}
  149. Delayed.prototype.set = function(ms, f) {
  150. clearTimeout(this.id)
  151. this.id = setTimeout(f, ms)
  152. }
  153. function indexOf(array, elt) {
  154. for (var i = 0; i < array.length; ++i)
  155. { if (array[i] == elt) { return i } }
  156. return -1
  157. }
  158. // Number of pixels added to scroller and sizer to hide scrollbar
  159. var scrollerGap = 30
  160. // Returned or thrown by various protocols to signal 'I'm not
  161. // handling this'.
  162. var Pass = {toString: function(){return "CodeMirror.Pass"}}
  163. // Reused option objects for setSelection & friends
  164. var sel_dontScroll = {scroll: false};
  165. var sel_mouse = {origin: "*mouse"};
  166. var sel_move = {origin: "+move"}
  167. // The inverse of countColumn -- find the offset that corresponds to
  168. // a particular column.
  169. function findColumn(string, goal, tabSize) {
  170. for (var pos = 0, col = 0;;) {
  171. var nextTab = string.indexOf("\t", pos)
  172. if (nextTab == -1) { nextTab = string.length }
  173. var skipped = nextTab - pos
  174. if (nextTab == string.length || col + skipped >= goal)
  175. { return pos + Math.min(skipped, goal - col) }
  176. col += nextTab - pos
  177. col += tabSize - (col % tabSize)
  178. pos = nextTab + 1
  179. if (col >= goal) { return pos }
  180. }
  181. }
  182. var spaceStrs = [""]
  183. function spaceStr(n) {
  184. while (spaceStrs.length <= n)
  185. { spaceStrs.push(lst(spaceStrs) + " ") }
  186. return spaceStrs[n]
  187. }
  188. function lst(arr) { return arr[arr.length-1] }
  189. function map(array, f) {
  190. var out = []
  191. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
  192. return out
  193. }
  194. function insertSorted(array, value, score) {
  195. var pos = 0, priority = score(value)
  196. while (pos < array.length && score(array[pos]) <= priority) { pos++ }
  197. array.splice(pos, 0, value)
  198. }
  199. function nothing() {}
  200. function createObj(base, props) {
  201. var inst
  202. if (Object.create) {
  203. inst = Object.create(base)
  204. } else {
  205. nothing.prototype = base
  206. inst = new nothing()
  207. }
  208. if (props) { copyObj(props, inst) }
  209. return inst
  210. }
  211. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
  212. function isWordCharBasic(ch) {
  213. return /\w/.test(ch) || ch > "\x80" &&
  214. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  215. }
  216. function isWordChar(ch, helper) {
  217. if (!helper) { return isWordCharBasic(ch) }
  218. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  219. return helper.test(ch)
  220. }
  221. function isEmpty(obj) {
  222. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  223. return true
  224. }
  225. // Extending unicode characters. A series of a non-extending char +
  226. // any number of extending chars is treated as a single unit as far
  227. // as editing and measuring is concerned. This is not fully correct,
  228. // since some scripts/fonts/browsers also treat other configurations
  229. // of code points as a group.
  230. 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]/
  231. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  232. // The display handles the DOM integration, both for input reading
  233. // and content drawing. It holds references to DOM nodes and
  234. // display-related state.
  235. function Display(place, doc, input) {
  236. var d = this
  237. this.input = input
  238. // Covers bottom-right square when both scrollbars are present.
  239. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
  240. d.scrollbarFiller.setAttribute("cm-not-content", "true")
  241. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  242. // and h scrollbar is present.
  243. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
  244. d.gutterFiller.setAttribute("cm-not-content", "true")
  245. // Will contain the actual code, positioned to cover the viewport.
  246. d.lineDiv = elt("div", null, "CodeMirror-code")
  247. // Elements are added to these to represent selection and cursors.
  248. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
  249. d.cursorDiv = elt("div", null, "CodeMirror-cursors")
  250. // A visibility: hidden element used to find the size of things.
  251. d.measure = elt("div", null, "CodeMirror-measure")
  252. // When lines outside of the viewport are measured, they are drawn in this.
  253. d.lineMeasure = elt("div", null, "CodeMirror-measure")
  254. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  255. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  256. null, "position: relative; outline: none")
  257. // Moved around its parent to cover visible view.
  258. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative")
  259. // Set to the height of the document, allowing scrolling.
  260. d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
  261. d.sizerWidth = null
  262. // Behavior of elts with overflow: auto and padding is
  263. // inconsistent across browsers. This is used to ensure the
  264. // scrollable area is big enough.
  265. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
  266. // Will contain the gutters, if any.
  267. d.gutters = elt("div", null, "CodeMirror-gutters")
  268. d.lineGutter = null
  269. // Actual scrollable element.
  270. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
  271. d.scroller.setAttribute("tabIndex", "-1")
  272. // The element in which the editor lives.
  273. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
  274. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  275. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
  276. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
  277. if (place) {
  278. if (place.appendChild) { place.appendChild(d.wrapper) }
  279. else { place(d.wrapper) }
  280. }
  281. // Current rendered range (may be bigger than the view window).
  282. d.viewFrom = d.viewTo = doc.first
  283. d.reportedViewFrom = d.reportedViewTo = doc.first
  284. // Information about the rendered lines.
  285. d.view = []
  286. d.renderedView = null
  287. // Holds info about a single rendered line when it was rendered
  288. // for measurement, while not in view.
  289. d.externalMeasured = null
  290. // Empty space (in pixels) above the view
  291. d.viewOffset = 0
  292. d.lastWrapHeight = d.lastWrapWidth = 0
  293. d.updateLineNumbers = null
  294. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  295. d.scrollbarsClipped = false
  296. // Used to only resize the line number gutter when necessary (when
  297. // the amount of lines crosses a boundary that makes its width change)
  298. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  299. // Set to true when a non-horizontal-scrolling line widget is
  300. // added. As an optimization, line widget aligning is skipped when
  301. // this is false.
  302. d.alignWidgets = false
  303. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  304. // Tracks the maximum line length so that the horizontal scrollbar
  305. // can be kept static when scrolling.
  306. d.maxLine = null
  307. d.maxLineLength = 0
  308. d.maxLineChanged = false
  309. // Used for measuring wheel scrolling granularity
  310. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  311. // True when shift is held down.
  312. d.shift = false
  313. // Used to track whether anything happened since the context menu
  314. // was opened.
  315. d.selForContextMenu = null
  316. d.activeTouch = null
  317. input.init(d)
  318. }
  319. // Find the line object corresponding to the given line number.
  320. function getLine(doc, n) {
  321. n -= doc.first
  322. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  323. var chunk = doc
  324. while (!chunk.lines) {
  325. for (var i = 0;; ++i) {
  326. var child = chunk.children[i], sz = child.chunkSize()
  327. if (n < sz) { chunk = child; break }
  328. n -= sz
  329. }
  330. }
  331. return chunk.lines[n]
  332. }
  333. // Get the part of a document between two positions, as an array of
  334. // strings.
  335. function getBetween(doc, start, end) {
  336. var out = [], n = start.line
  337. doc.iter(start.line, end.line + 1, function (line) {
  338. var text = line.text
  339. if (n == end.line) { text = text.slice(0, end.ch) }
  340. if (n == start.line) { text = text.slice(start.ch) }
  341. out.push(text)
  342. ++n
  343. })
  344. return out
  345. }
  346. // Get the lines between from and to, as array of strings.
  347. function getLines(doc, from, to) {
  348. var out = []
  349. doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
  350. return out
  351. }
  352. // Update the height of a line, propagating the height change
  353. // upwards to parent nodes.
  354. function updateLineHeight(line, height) {
  355. var diff = height - line.height
  356. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
  357. }
  358. // Given a line object, find its line number by walking up through
  359. // its parent links.
  360. function lineNo(line) {
  361. if (line.parent == null) { return null }
  362. var cur = line.parent, no = indexOf(cur.lines, line)
  363. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  364. for (var i = 0;; ++i) {
  365. if (chunk.children[i] == cur) { break }
  366. no += chunk.children[i].chunkSize()
  367. }
  368. }
  369. return no + cur.first
  370. }
  371. // Find the line at the given vertical position, using the height
  372. // information in the document tree.
  373. function lineAtHeight(chunk, h) {
  374. var n = chunk.first
  375. outer: do {
  376. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  377. var child = chunk.children[i$1], ch = child.height
  378. if (h < ch) { chunk = child; continue outer }
  379. h -= ch
  380. n += child.chunkSize()
  381. }
  382. return n
  383. } while (!chunk.lines)
  384. var i = 0
  385. for (; i < chunk.lines.length; ++i) {
  386. var line = chunk.lines[i], lh = line.height
  387. if (h < lh) { break }
  388. h -= lh
  389. }
  390. return n + i
  391. }
  392. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  393. function lineNumberFor(options, i) {
  394. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  395. }
  396. // A Pos instance represents a position within the text.
  397. function Pos (line, ch) {
  398. if (!(this instanceof Pos)) { return new Pos(line, ch) }
  399. this.line = line; this.ch = ch
  400. }
  401. // Compare two positions, return 0 if they are the same, a negative
  402. // number when a is less, and a positive number otherwise.
  403. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  404. function copyPos(x) {return Pos(x.line, x.ch)}
  405. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  406. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  407. // Most of the external API clips given positions to make sure they
  408. // actually exist within the document.
  409. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  410. function clipPos(doc, pos) {
  411. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  412. var last = doc.first + doc.size - 1
  413. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  414. return clipToLen(pos, getLine(doc, pos.line).text.length)
  415. }
  416. function clipToLen(pos, linelen) {
  417. var ch = pos.ch
  418. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  419. else if (ch < 0) { return Pos(pos.line, 0) }
  420. else { return pos }
  421. }
  422. function clipPosArray(doc, array) {
  423. var out = []
  424. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
  425. return out
  426. }
  427. // Optimize some code when these features are not used.
  428. var sawReadOnlySpans = false;
  429. var sawCollapsedSpans = false
  430. function seeReadOnlySpans() {
  431. sawReadOnlySpans = true
  432. }
  433. function seeCollapsedSpans() {
  434. sawCollapsedSpans = true
  435. }
  436. // TEXTMARKER SPANS
  437. function MarkedSpan(marker, from, to) {
  438. this.marker = marker
  439. this.from = from; this.to = to
  440. }
  441. // Search an array of spans for a span matching the given marker.
  442. function getMarkedSpanFor(spans, marker) {
  443. if (spans) { for (var i = 0; i < spans.length; ++i) {
  444. var span = spans[i]
  445. if (span.marker == marker) { return span }
  446. } }
  447. }
  448. // Remove a span from an array, returning undefined if no spans are
  449. // left (we don't store arrays for lines without spans).
  450. function removeMarkedSpan(spans, span) {
  451. var r
  452. for (var i = 0; i < spans.length; ++i)
  453. { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
  454. return r
  455. }
  456. // Add a span to a line.
  457. function addMarkedSpan(line, span) {
  458. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  459. span.marker.attachLine(line)
  460. }
  461. // Used for the algorithm that adjusts markers for a change in the
  462. // document. These functions cut an array of spans at a given
  463. // character position, returning an array of remaining chunks (or
  464. // undefined if nothing remains).
  465. function markedSpansBefore(old, startCh, isInsert) {
  466. var nw
  467. if (old) { for (var i = 0; i < old.length; ++i) {
  468. var span = old[i], marker = span.marker
  469. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  470. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  471. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
  472. }
  473. } }
  474. return nw
  475. }
  476. function markedSpansAfter(old, endCh, isInsert) {
  477. var nw
  478. if (old) { for (var i = 0; i < old.length; ++i) {
  479. var span = old[i], marker = span.marker
  480. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
  481. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  482. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  483. span.to == null ? null : span.to - endCh))
  484. }
  485. } }
  486. return nw
  487. }
  488. // Given a change object, compute the new set of marker spans that
  489. // cover the line in which the change took place. Removes spans
  490. // entirely within the change, reconnects spans belonging to the
  491. // same marker that appear on both sides of the change, and cuts off
  492. // spans partially within the change. Returns an array of span
  493. // arrays with one element for each line in (after) the change.
  494. function stretchSpansOverChange(doc, change) {
  495. if (change.full) { return null }
  496. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
  497. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
  498. if (!oldFirst && !oldLast) { return null }
  499. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
  500. // Get the spans that 'stick out' on both sides
  501. var first = markedSpansBefore(oldFirst, startCh, isInsert)
  502. var last = markedSpansAfter(oldLast, endCh, isInsert)
  503. // Next, merge those two ends
  504. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
  505. if (first) {
  506. // Fix up .to properties of first
  507. for (var i = 0; i < first.length; ++i) {
  508. var span = first[i]
  509. if (span.to == null) {
  510. var found = getMarkedSpanFor(last, span.marker)
  511. if (!found) { span.to = startCh }
  512. else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
  513. }
  514. }
  515. }
  516. if (last) {
  517. // Fix up .from in last (or move them into first in case of sameLine)
  518. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  519. var span$1 = last[i$1]
  520. if (span$1.to != null) { span$1.to += offset }
  521. if (span$1.from == null) {
  522. var found$1 = getMarkedSpanFor(first, span$1.marker)
  523. if (!found$1) {
  524. span$1.from = offset
  525. if (sameLine) { (first || (first = [])).push(span$1) }
  526. }
  527. } else {
  528. span$1.from += offset
  529. if (sameLine) { (first || (first = [])).push(span$1) }
  530. }
  531. }
  532. }
  533. // Make sure we didn't create any zero-length spans
  534. if (first) { first = clearEmptySpans(first) }
  535. if (last && last != first) { last = clearEmptySpans(last) }
  536. var newMarkers = [first]
  537. if (!sameLine) {
  538. // Fill gap with whole-line-spans
  539. var gap = change.text.length - 2, gapMarkers
  540. if (gap > 0 && first)
  541. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  542. { if (first[i$2].to == null)
  543. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
  544. for (var i$3 = 0; i$3 < gap; ++i$3)
  545. { newMarkers.push(gapMarkers) }
  546. newMarkers.push(last)
  547. }
  548. return newMarkers
  549. }
  550. // Remove spans that are empty and don't have a clearWhenEmpty
  551. // option of false.
  552. function clearEmptySpans(spans) {
  553. for (var i = 0; i < spans.length; ++i) {
  554. var span = spans[i]
  555. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  556. { spans.splice(i--, 1) }
  557. }
  558. if (!spans.length) { return null }
  559. return spans
  560. }
  561. // Used to 'clip' out readOnly ranges when making a change.
  562. function removeReadOnlyRanges(doc, from, to) {
  563. var markers = null
  564. doc.iter(from.line, to.line + 1, function (line) {
  565. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  566. var mark = line.markedSpans[i].marker
  567. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  568. { (markers || (markers = [])).push(mark) }
  569. } }
  570. })
  571. if (!markers) { return null }
  572. var parts = [{from: from, to: to}]
  573. for (var i = 0; i < markers.length; ++i) {
  574. var mk = markers[i], m = mk.find(0)
  575. for (var j = 0; j < parts.length; ++j) {
  576. var p = parts[j]
  577. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  578. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
  579. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  580. { newParts.push({from: p.from, to: m.from}) }
  581. if (dto > 0 || !mk.inclusiveRight && !dto)
  582. { newParts.push({from: m.to, to: p.to}) }
  583. parts.splice.apply(parts, newParts)
  584. j += newParts.length - 1
  585. }
  586. }
  587. return parts
  588. }
  589. // Connect or disconnect spans from a line.
  590. function detachMarkedSpans(line) {
  591. var spans = line.markedSpans
  592. if (!spans) { return }
  593. for (var i = 0; i < spans.length; ++i)
  594. { spans[i].marker.detachLine(line) }
  595. line.markedSpans = null
  596. }
  597. function attachMarkedSpans(line, spans) {
  598. if (!spans) { return }
  599. for (var i = 0; i < spans.length; ++i)
  600. { spans[i].marker.attachLine(line) }
  601. line.markedSpans = spans
  602. }
  603. // Helpers used when computing which overlapping collapsed span
  604. // counts as the larger one.
  605. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  606. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  607. // Returns a number indicating which of two overlapping collapsed
  608. // spans is larger (and thus includes the other). Falls back to
  609. // comparing ids when the spans cover exactly the same range.
  610. function compareCollapsedMarkers(a, b) {
  611. var lenDiff = a.lines.length - b.lines.length
  612. if (lenDiff != 0) { return lenDiff }
  613. var aPos = a.find(), bPos = b.find()
  614. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
  615. if (fromCmp) { return -fromCmp }
  616. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
  617. if (toCmp) { return toCmp }
  618. return b.id - a.id
  619. }
  620. // Find out whether a line ends or starts in a collapsed span. If
  621. // so, return the marker for that span.
  622. function collapsedSpanAtSide(line, start) {
  623. var sps = sawCollapsedSpans && line.markedSpans, found
  624. if (sps) { for (var sp = void 0, i = 0; i < sps.length; ++i) {
  625. sp = sps[i]
  626. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  627. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  628. { found = sp.marker }
  629. } }
  630. return found
  631. }
  632. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  633. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  634. // Test whether there exists a collapsed span that partially
  635. // overlaps (covers the start or end, but not both) of a new span.
  636. // Such overlap is not allowed.
  637. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  638. var line = getLine(doc, lineNo$$1)
  639. var sps = sawCollapsedSpans && line.markedSpans
  640. if (sps) { for (var i = 0; i < sps.length; ++i) {
  641. var sp = sps[i]
  642. if (!sp.marker.collapsed) { continue }
  643. var found = sp.marker.find(0)
  644. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  645. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  646. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  647. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  648. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  649. { return true }
  650. } }
  651. }
  652. // A visual line is a line as drawn on the screen. Folding, for
  653. // example, can cause multiple logical lines to appear on the same
  654. // visual line. This finds the start of the visual line that the
  655. // given line is part of (usually that is the line itself).
  656. function visualLine(line) {
  657. var merged
  658. while (merged = collapsedSpanAtStart(line))
  659. { line = merged.find(-1, true).line }
  660. return line
  661. }
  662. // Returns an array of logical lines that continue the visual line
  663. // started by the argument, or undefined if there are no such lines.
  664. function visualLineContinued(line) {
  665. var merged, lines
  666. while (merged = collapsedSpanAtEnd(line)) {
  667. line = merged.find(1, true).line
  668. ;(lines || (lines = [])).push(line)
  669. }
  670. return lines
  671. }
  672. // Get the line number of the start of the visual line that the
  673. // given line number is part of.
  674. function visualLineNo(doc, lineN) {
  675. var line = getLine(doc, lineN), vis = visualLine(line)
  676. if (line == vis) { return lineN }
  677. return lineNo(vis)
  678. }
  679. // Get the line number of the start of the next visual line after
  680. // the given line.
  681. function visualLineEndNo(doc, lineN) {
  682. if (lineN > doc.lastLine()) { return lineN }
  683. var line = getLine(doc, lineN), merged
  684. if (!lineIsHidden(doc, line)) { return lineN }
  685. while (merged = collapsedSpanAtEnd(line))
  686. { line = merged.find(1, true).line }
  687. return lineNo(line) + 1
  688. }
  689. // Compute whether a line is hidden. Lines count as hidden when they
  690. // are part of a visual line that starts with another line, or when
  691. // they are entirely covered by collapsed, non-widget span.
  692. function lineIsHidden(doc, line) {
  693. var sps = sawCollapsedSpans && line.markedSpans
  694. if (sps) { for (var sp = void 0, i = 0; i < sps.length; ++i) {
  695. sp = sps[i]
  696. if (!sp.marker.collapsed) { continue }
  697. if (sp.from == null) { return true }
  698. if (sp.marker.widgetNode) { continue }
  699. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  700. { return true }
  701. } }
  702. }
  703. function lineIsHiddenInner(doc, line, span) {
  704. if (span.to == null) {
  705. var end = span.marker.find(1, true)
  706. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  707. }
  708. if (span.marker.inclusiveRight && span.to == line.text.length)
  709. { return true }
  710. for (var sp = void 0, i = 0; i < line.markedSpans.length; ++i) {
  711. sp = line.markedSpans[i]
  712. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  713. (sp.to == null || sp.to != span.from) &&
  714. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  715. lineIsHiddenInner(doc, line, sp)) { return true }
  716. }
  717. }
  718. // Find the height above the given line.
  719. function heightAtLine(lineObj) {
  720. lineObj = visualLine(lineObj)
  721. var h = 0, chunk = lineObj.parent
  722. for (var i = 0; i < chunk.lines.length; ++i) {
  723. var line = chunk.lines[i]
  724. if (line == lineObj) { break }
  725. else { h += line.height }
  726. }
  727. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  728. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  729. var cur = p.children[i$1]
  730. if (cur == chunk) { break }
  731. else { h += cur.height }
  732. }
  733. }
  734. return h
  735. }
  736. // Compute the character length of a line, taking into account
  737. // collapsed ranges (see markText) that might hide parts, and join
  738. // other lines onto it.
  739. function lineLength(line) {
  740. if (line.height == 0) { return 0 }
  741. var len = line.text.length, merged, cur = line
  742. while (merged = collapsedSpanAtStart(cur)) {
  743. var found = merged.find(0, true)
  744. cur = found.from.line
  745. len += found.from.ch - found.to.ch
  746. }
  747. cur = line
  748. while (merged = collapsedSpanAtEnd(cur)) {
  749. var found$1 = merged.find(0, true)
  750. len -= cur.text.length - found$1.from.ch
  751. cur = found$1.to.line
  752. len += cur.text.length - found$1.to.ch
  753. }
  754. return len
  755. }
  756. // Find the longest line in the document.
  757. function findMaxLine(cm) {
  758. var d = cm.display, doc = cm.doc
  759. d.maxLine = getLine(doc, doc.first)
  760. d.maxLineLength = lineLength(d.maxLine)
  761. d.maxLineChanged = true
  762. doc.iter(function (line) {
  763. var len = lineLength(line)
  764. if (len > d.maxLineLength) {
  765. d.maxLineLength = len
  766. d.maxLine = line
  767. }
  768. })
  769. }
  770. // BIDI HELPERS
  771. function iterateBidiSections(order, from, to, f) {
  772. if (!order) { return f(from, to, "ltr") }
  773. var found = false
  774. for (var i = 0; i < order.length; ++i) {
  775. var part = order[i]
  776. if (part.from < to && part.to > from || from == to && part.to == from) {
  777. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr")
  778. found = true
  779. }
  780. }
  781. if (!found) { f(from, to, "ltr") }
  782. }
  783. function bidiLeft(part) { return part.level % 2 ? part.to : part.from }
  784. function bidiRight(part) { return part.level % 2 ? part.from : part.to }
  785. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0 }
  786. function lineRight(line) {
  787. var order = getOrder(line)
  788. if (!order) { return line.text.length }
  789. return bidiRight(lst(order))
  790. }
  791. function compareBidiLevel(order, a, b) {
  792. var linedir = order[0].level
  793. if (a == linedir) { return true }
  794. if (b == linedir) { return false }
  795. return a < b
  796. }
  797. var bidiOther = null
  798. function getBidiPartAt(order, pos) {
  799. var found
  800. bidiOther = null
  801. for (var i = 0; i < order.length; ++i) {
  802. var cur = order[i]
  803. if (cur.from < pos && cur.to > pos) { return i }
  804. if ((cur.from == pos || cur.to == pos)) {
  805. if (found == null) {
  806. found = i
  807. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  808. if (cur.from != cur.to) { bidiOther = found }
  809. return i
  810. } else {
  811. if (cur.from != cur.to) { bidiOther = i }
  812. return found
  813. }
  814. }
  815. }
  816. return found
  817. }
  818. function moveInLine(line, pos, dir, byUnit) {
  819. if (!byUnit) { return pos + dir }
  820. do { pos += dir }
  821. while (pos > 0 && isExtendingChar(line.text.charAt(pos)))
  822. return pos
  823. }
  824. // This is needed in order to move 'visually' through bi-directional
  825. // text -- i.e., pressing left should make the cursor go left, even
  826. // when in RTL text. The tricky part is the 'jumps', where RTL and
  827. // LTR text touch each other. This often requires the cursor offset
  828. // to move more than one unit, in order to visually move one unit.
  829. function moveVisually(line, start, dir, byUnit) {
  830. var bidi = getOrder(line)
  831. if (!bidi) { return moveLogically(line, start, dir, byUnit) }
  832. var pos = getBidiPartAt(bidi, start), part = bidi[pos]
  833. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit)
  834. for (;;) {
  835. if (target > part.from && target < part.to) { return target }
  836. if (target == part.from || target == part.to) {
  837. if (getBidiPartAt(bidi, target) == pos) { return target }
  838. part = bidi[pos += dir]
  839. return (dir > 0) == part.level % 2 ? part.to : part.from
  840. } else {
  841. part = bidi[pos += dir]
  842. if (!part) { return null }
  843. if ((dir > 0) == part.level % 2)
  844. { target = moveInLine(line, part.to, -1, byUnit) }
  845. else
  846. { target = moveInLine(line, part.from, 1, byUnit) }
  847. }
  848. }
  849. }
  850. function moveLogically(line, start, dir, byUnit) {
  851. var target = start + dir
  852. if (byUnit) { while (target > 0 && isExtendingChar(line.text.charAt(target))) { target += dir } }
  853. return target < 0 || target > line.text.length ? null : target
  854. }
  855. // Bidirectional ordering algorithm
  856. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  857. // that this (partially) implements.
  858. // One-char codes used for character types:
  859. // L (L): Left-to-Right
  860. // R (R): Right-to-Left
  861. // r (AL): Right-to-Left Arabic
  862. // 1 (EN): European Number
  863. // + (ES): European Number Separator
  864. // % (ET): European Number Terminator
  865. // n (AN): Arabic Number
  866. // , (CS): Common Number Separator
  867. // m (NSM): Non-Spacing Mark
  868. // b (BN): Boundary Neutral
  869. // s (B): Paragraph Separator
  870. // t (S): Segment Separator
  871. // w (WS): Whitespace
  872. // N (ON): Other Neutrals
  873. // Returns null if characters are ordered as they appear
  874. // (left-to-right), or an array of sections ({from, to, level}
  875. // objects) in the order in which they occur visually.
  876. var bidiOrdering = (function() {
  877. // Character types for codepoints 0 to 0xff
  878. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
  879. // Character types for codepoints 0x600 to 0x6ff
  880. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"
  881. function charType(code) {
  882. if (code <= 0xf7) { return lowTypes.charAt(code) }
  883. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  884. else if (0x600 <= code && code <= 0x6ed) { return arabicTypes.charAt(code - 0x600) }
  885. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  886. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  887. else if (code == 0x200c) { return "b" }
  888. else { return "L" }
  889. }
  890. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  891. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
  892. // Browsers seem to always treat the boundaries of block elements as being L.
  893. var outerType = "L"
  894. function BidiSpan(level, from, to) {
  895. this.level = level
  896. this.from = from; this.to = to
  897. }
  898. return function(str) {
  899. if (!bidiRE.test(str)) { return false }
  900. var len = str.length, types = []
  901. for (var i = 0; i < len; ++i)
  902. { types.push(charType(str.charCodeAt(i))) }
  903. // W1. Examine each non-spacing mark (NSM) in the level run, and
  904. // change the type of the NSM to the type of the previous
  905. // character. If the NSM is at the start of the level run, it will
  906. // get the type of sor.
  907. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  908. var type = types[i$1]
  909. if (type == "m") { types[i$1] = prev }
  910. else { prev = type }
  911. }
  912. // W2. Search backwards from each instance of a European number
  913. // until the first strong type (R, L, AL, or sor) is found. If an
  914. // AL is found, change the type of the European number to Arabic
  915. // number.
  916. // W3. Change all ALs to R.
  917. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  918. var type$1 = types[i$2]
  919. if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
  920. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
  921. }
  922. // W4. A single European separator between two European numbers
  923. // changes to a European number. A single common separator between
  924. // two numbers of the same type changes to that type.
  925. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  926. var type$2 = types[i$3]
  927. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
  928. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  929. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
  930. prev$1 = type$2
  931. }
  932. // W5. A sequence of European terminators adjacent to European
  933. // numbers changes to all European numbers.
  934. // W6. Otherwise, separators and terminators change to Other
  935. // Neutral.
  936. for (var i$4 = 0; i$4 < len; ++i$4) {
  937. var type$3 = types[i$4]
  938. if (type$3 == ",") { types[i$4] = "N" }
  939. else if (type$3 == "%") {
  940. var end = void 0
  941. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  942. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
  943. for (var j = i$4; j < end; ++j) { types[j] = replace }
  944. i$4 = end - 1
  945. }
  946. }
  947. // W7. Search backwards from each instance of a European number
  948. // until the first strong type (R, L, or sor) is found. If an L is
  949. // found, then change the type of the European number to L.
  950. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  951. var type$4 = types[i$5]
  952. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
  953. else if (isStrong.test(type$4)) { cur$1 = type$4 }
  954. }
  955. // N1. A sequence of neutrals takes the direction of the
  956. // surrounding strong text if the text on both sides has the same
  957. // direction. European and Arabic numbers act as if they were R in
  958. // terms of their influence on neutrals. Start-of-level-run (sor)
  959. // and end-of-level-run (eor) are used at level run boundaries.
  960. // N2. Any remaining neutrals take the embedding direction.
  961. for (var i$6 = 0; i$6 < len; ++i$6) {
  962. if (isNeutral.test(types[i$6])) {
  963. var end$1 = void 0
  964. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  965. var before = (i$6 ? types[i$6-1] : outerType) == "L"
  966. var after = (end$1 < len ? types[end$1] : outerType) == "L"
  967. var replace$1 = before || after ? "L" : "R"
  968. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
  969. i$6 = end$1 - 1
  970. }
  971. }
  972. // Here we depart from the documented algorithm, in order to avoid
  973. // building up an actual levels array. Since there are only three
  974. // levels (0, 1, 2) in an implementation that doesn't take
  975. // explicit embedding into account, we can build up the order on
  976. // the fly, without following the level-based algorithm.
  977. var order = [], m
  978. for (var i$7 = 0; i$7 < len;) {
  979. if (countsAsLeft.test(types[i$7])) {
  980. var start = i$7
  981. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  982. order.push(new BidiSpan(0, start, i$7))
  983. } else {
  984. var pos = i$7, at = order.length
  985. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  986. for (var j$2 = pos; j$2 < i$7;) {
  987. if (countsAsNum.test(types[j$2])) {
  988. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
  989. var nstart = j$2
  990. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  991. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  992. pos = j$2
  993. } else { ++j$2 }
  994. }
  995. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
  996. }
  997. }
  998. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  999. order[0].from = m[0].length
  1000. order.unshift(new BidiSpan(0, 0, m[0].length))
  1001. }
  1002. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  1003. lst(order).to -= m[0].length
  1004. order.push(new BidiSpan(0, len - m[0].length, len))
  1005. }
  1006. if (order[0].level == 2)
  1007. { order.unshift(new BidiSpan(1, order[0].to, order[0].to)) }
  1008. if (order[0].level != lst(order).level)
  1009. { order.push(new BidiSpan(order[0].level, len, len)) }
  1010. return order
  1011. }
  1012. })()
  1013. // Get the bidi ordering for the given line (and cache it). Returns
  1014. // false for lines that are fully left-to-right, and an array of
  1015. // BidiSpan objects otherwise.
  1016. function getOrder(line) {
  1017. var order = line.order
  1018. if (order == null) { order = line.order = bidiOrdering(line.text) }
  1019. return order
  1020. }
  1021. // EVENT HANDLING
  1022. // Lightweight event framework. on/off also work on DOM nodes,
  1023. // registering native DOM handlers.
  1024. var noHandlers = []
  1025. var on = function(emitter, type, f) {
  1026. if (emitter.addEventListener) {
  1027. emitter.addEventListener(type, f, false)
  1028. } else if (emitter.attachEvent) {
  1029. emitter.attachEvent("on" + type, f)
  1030. } else {
  1031. var map$$1 = emitter._handlers || (emitter._handlers = {})
  1032. map$$1[type] = (map$$1[type] || noHandlers).concat(f)
  1033. }
  1034. }
  1035. function getHandlers(emitter, type) {
  1036. return emitter._handlers && emitter._handlers[type] || noHandlers
  1037. }
  1038. function off(emitter, type, f) {
  1039. if (emitter.removeEventListener) {
  1040. emitter.removeEventListener(type, f, false)
  1041. } else if (emitter.detachEvent) {
  1042. emitter.detachEvent("on" + type, f)
  1043. } else {
  1044. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]
  1045. if (arr) {
  1046. var index = indexOf(arr, f)
  1047. if (index > -1)
  1048. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
  1049. }
  1050. }
  1051. }
  1052. function signal(emitter, type /*, values...*/) {
  1053. var handlers = getHandlers(emitter, type)
  1054. if (!handlers.length) { return }
  1055. var args = Array.prototype.slice.call(arguments, 2)
  1056. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
  1057. }
  1058. // The DOM events that CodeMirror handles can be overridden by
  1059. // registering a (non-DOM) handler on the editor for the event name,
  1060. // and preventDefault-ing the event in that handler.
  1061. function signalDOMEvent(cm, e, override) {
  1062. if (typeof e == "string")
  1063. { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
  1064. signal(cm, override || e.type, cm, e)
  1065. return e_defaultPrevented(e) || e.codemirrorIgnore
  1066. }
  1067. function signalCursorActivity(cm) {
  1068. var arr = cm._handlers && cm._handlers.cursorActivity
  1069. if (!arr) { return }
  1070. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  1071. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1072. { set.push(arr[i]) } }
  1073. }
  1074. function hasHandler(emitter, type) {
  1075. return getHandlers(emitter, type).length > 0
  1076. }
  1077. // Add on and off methods to a constructor's prototype, to make
  1078. // registering events on such objects more convenient.
  1079. function eventMixin(ctor) {
  1080. ctor.prototype.on = function(type, f) {on(this, type, f)}
  1081. ctor.prototype.off = function(type, f) {off(this, type, f)}
  1082. }
  1083. // Due to the fact that we still support jurassic IE versions, some
  1084. // compatibility wrappers are needed.
  1085. function e_preventDefault(e) {
  1086. if (e.preventDefault) { e.preventDefault() }
  1087. else { e.returnValue = false }
  1088. }
  1089. function e_stopPropagation(e) {
  1090. if (e.stopPropagation) { e.stopPropagation() }
  1091. else { e.cancelBubble = true }
  1092. }
  1093. function e_defaultPrevented(e) {
  1094. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1095. }
  1096. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
  1097. function e_target(e) {return e.target || e.srcElement}
  1098. function e_button(e) {
  1099. var b = e.which
  1100. if (b == null) {
  1101. if (e.button & 1) { b = 1 }
  1102. else if (e.button & 2) { b = 3 }
  1103. else if (e.button & 4) { b = 2 }
  1104. }
  1105. if (mac && e.ctrlKey && b == 1) { b = 3 }
  1106. return b
  1107. }
  1108. // Detect drag-and-drop
  1109. var dragAndDrop = function() {
  1110. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1111. // couldn't get it to work yet.
  1112. if (ie && ie_version < 9) { return false }
  1113. var div = elt('div')
  1114. return "draggable" in div || "dragDrop" in div
  1115. }()
  1116. var zwspSupported
  1117. function zeroWidthElement(measure) {
  1118. if (zwspSupported == null) {
  1119. var test = elt("span", "\u200b")
  1120. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
  1121. if (measure.firstChild.offsetHeight != 0)
  1122. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
  1123. }
  1124. var node = zwspSupported ? elt("span", "\u200b") :
  1125. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  1126. node.setAttribute("cm-text", "")
  1127. return node
  1128. }
  1129. // Feature-detect IE's crummy client rect reporting for bidi text
  1130. var badBidiRects
  1131. function hasBadBidiRects(measure) {
  1132. if (badBidiRects != null) { return badBidiRects }
  1133. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  1134. var r0 = range(txt, 0, 1).getBoundingClientRect()
  1135. var r1 = range(txt, 1, 2).getBoundingClientRect()
  1136. removeChildren(measure)
  1137. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1138. return badBidiRects = (r1.right - r0.right < 3)
  1139. }
  1140. // See if "".split is the broken IE version, if so, provide an
  1141. // alternative way to split lines.
  1142. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1143. var pos = 0, result = [], l = string.length
  1144. while (pos <= l) {
  1145. var nl = string.indexOf("\n", pos)
  1146. if (nl == -1) { nl = string.length }
  1147. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
  1148. var rt = line.indexOf("\r")
  1149. if (rt != -1) {
  1150. result.push(line.slice(0, rt))
  1151. pos += rt + 1
  1152. } else {
  1153. result.push(line)
  1154. pos = nl + 1
  1155. }
  1156. }
  1157. return result
  1158. } : function (string) { return string.split(/\r\n?|\n/); }
  1159. var hasSelection = window.getSelection ? function (te) {
  1160. try { return te.selectionStart != te.selectionEnd }
  1161. catch(e) { return false }
  1162. } : function (te) {
  1163. var range$$1
  1164. try {range$$1 = te.ownerDocument.selection.createRange()}
  1165. catch(e) {}
  1166. if (!range$$1 || range$$1.parentElement() != te) { return false }
  1167. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  1168. }
  1169. var hasCopyEvent = (function () {
  1170. var e = elt("div")
  1171. if ("oncopy" in e) { return true }
  1172. e.setAttribute("oncopy", "return;")
  1173. return typeof e.oncopy == "function"
  1174. })()
  1175. var badZoomedRects = null
  1176. function hasBadZoomedRects(measure) {
  1177. if (badZoomedRects != null) { return badZoomedRects }
  1178. var node = removeChildrenAndAdd(measure, elt("span", "x"))
  1179. var normal = node.getBoundingClientRect()
  1180. var fromRange = range(node, 0, 1).getBoundingClientRect()
  1181. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1182. }
  1183. // Known modes, by name and by MIME
  1184. var modes = {};
  1185. var mimeModes = {}
  1186. // Extra arguments are stored as the mode's dependencies, which is
  1187. // used by (legacy) mechanisms like loadmode.js to automatically
  1188. // load a mode. (Preferred mechanism is the require/define calls.)
  1189. function defineMode(name, mode) {
  1190. if (arguments.length > 2)
  1191. { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
  1192. modes[name] = mode
  1193. }
  1194. function defineMIME(mime, spec) {
  1195. mimeModes[mime] = spec
  1196. }
  1197. // Given a MIME type, a {name, ...options} config object, or a name
  1198. // string, return a mode config object.
  1199. function resolveMode(spec) {
  1200. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1201. spec = mimeModes[spec]
  1202. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1203. var found = mimeModes[spec.name]
  1204. if (typeof found == "string") { found = {name: found} }
  1205. spec = createObj(found, spec)
  1206. spec.name = found.name
  1207. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1208. return resolveMode("application/xml")
  1209. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1210. return resolveMode("application/json")
  1211. }
  1212. if (typeof spec == "string") { return {name: spec} }
  1213. else { return spec || {name: "null"} }
  1214. }
  1215. // Given a mode spec (anything that resolveMode accepts), find and
  1216. // initialize an actual mode object.
  1217. function getMode(options, spec) {
  1218. spec = resolveMode(spec)
  1219. var mfactory = modes[spec.name]
  1220. if (!mfactory) { return getMode(options, "text/plain") }
  1221. var modeObj = mfactory(options, spec)
  1222. if (modeExtensions.hasOwnProperty(spec.name)) {
  1223. var exts = modeExtensions[spec.name]
  1224. for (var prop in exts) {
  1225. if (!exts.hasOwnProperty(prop)) { continue }
  1226. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
  1227. modeObj[prop] = exts[prop]
  1228. }
  1229. }
  1230. modeObj.name = spec.name
  1231. if (spec.helperType) { modeObj.helperType = spec.helperType }
  1232. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1233. { modeObj[prop$1] = spec.modeProps[prop$1] } }
  1234. return modeObj
  1235. }
  1236. // This can be used to attach properties to mode objects from
  1237. // outside the actual mode definition.
  1238. var modeExtensions = {}
  1239. function extendMode(mode, properties) {
  1240. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  1241. copyObj(properties, exts)
  1242. }
  1243. function copyState(mode, state) {
  1244. if (state === true) { return state }
  1245. if (mode.copyState) { return mode.copyState(state) }
  1246. var nstate = {}
  1247. for (var n in state) {
  1248. var val = state[n]
  1249. if (val instanceof Array) { val = val.concat([]) }
  1250. nstate[n] = val
  1251. }
  1252. return nstate
  1253. }
  1254. // Given a mode and a state (for that mode), find the inner mode and
  1255. // state at the position that the state refers to.
  1256. function innerMode(mode, state) {
  1257. var info
  1258. while (mode.innerMode) {
  1259. info = mode.innerMode(state)
  1260. if (!info || info.mode == mode) { break }
  1261. state = info.state
  1262. mode = info.mode
  1263. }
  1264. return info || {mode: mode, state: state}
  1265. }
  1266. function startState(mode, a1, a2) {
  1267. return mode.startState ? mode.startState(a1, a2) : true
  1268. }
  1269. // STRING STREAM
  1270. // Fed to the mode parsers, provides helper functions to make
  1271. // parsers more succinct.
  1272. var StringStream = function(string, tabSize) {
  1273. this.pos = this.start = 0
  1274. this.string = string
  1275. this.tabSize = tabSize || 8
  1276. this.lastColumnPos = this.lastColumnValue = 0
  1277. this.lineStart = 0
  1278. }
  1279. StringStream.prototype = {
  1280. eol: function() {return this.pos >= this.string.length},
  1281. sol: function() {return this.pos == this.lineStart},
  1282. peek: function() {return this.string.charAt(this.pos) || undefined},
  1283. next: function() {
  1284. if (this.pos < this.string.length)
  1285. { return this.string.charAt(this.pos++) }
  1286. },
  1287. eat: function(match) {
  1288. var ch = this.string.charAt(this.pos)
  1289. var ok
  1290. if (typeof match == "string") { ok = ch == match }
  1291. else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
  1292. if (ok) {++this.pos; return ch}
  1293. },
  1294. eatWhile: function(match) {
  1295. var start = this.pos
  1296. while (this.eat(match)){}
  1297. return this.pos > start
  1298. },
  1299. eatSpace: function() {
  1300. var this$1 = this;
  1301. var start = this.pos
  1302. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
  1303. return this.pos > start
  1304. },
  1305. skipToEnd: function() {this.pos = this.string.length},
  1306. skipTo: function(ch) {
  1307. var found = this.string.indexOf(ch, this.pos)
  1308. if (found > -1) {this.pos = found; return true}
  1309. },
  1310. backUp: function(n) {this.pos -= n},
  1311. column: function() {
  1312. if (this.lastColumnPos < this.start) {
  1313. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1314. this.lastColumnPos = this.start
  1315. }
  1316. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1317. },
  1318. indentation: function() {
  1319. return countColumn(this.string, null, this.tabSize) -
  1320. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1321. },
  1322. match: function(pattern, consume, caseInsensitive) {
  1323. if (typeof pattern == "string") {
  1324. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
  1325. var substr = this.string.substr(this.pos, pattern.length)
  1326. if (cased(substr) == cased(pattern)) {
  1327. if (consume !== false) { this.pos += pattern.length }
  1328. return true
  1329. }
  1330. } else {
  1331. var match = this.string.slice(this.pos).match(pattern)
  1332. if (match && match.index > 0) { return null }
  1333. if (match && consume !== false) { this.pos += match[0].length }
  1334. return match
  1335. }
  1336. },
  1337. current: function(){return this.string.slice(this.start, this.pos)},
  1338. hideFirstChars: function(n, inner) {
  1339. this.lineStart += n
  1340. try { return inner() }
  1341. finally { this.lineStart -= n }
  1342. }
  1343. }
  1344. // Compute a style array (an array starting with a mode generation
  1345. // -- for invalidation -- followed by pairs of end positions and
  1346. // style strings), which is used to highlight the tokens on the
  1347. // line.
  1348. function highlightLine(cm, line, state, forceToEnd) {
  1349. // A styles array always starts with a number identifying the
  1350. // mode/overlays that it is based on (for easy invalidation).
  1351. var st = [cm.state.modeGen], lineClasses = {}
  1352. // Compute the base array of styles
  1353. runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); },
  1354. lineClasses, forceToEnd)
  1355. // Run overlays, adjust style array.
  1356. var loop = function ( o ) {
  1357. var overlay = cm.state.overlays[o], i = 1, at = 0
  1358. runMode(cm, line.text, overlay.mode, true, function (end, style) {
  1359. var start = i
  1360. // Ensure there's a token end at the current position, and that i points at it
  1361. while (at < end) {
  1362. var i_end = st[i]
  1363. if (i_end > end)
  1364. { st.splice(i, 1, end, st[i+1], i_end) }
  1365. i += 2
  1366. at = Math.min(end, i_end)
  1367. }
  1368. if (!style) { return }
  1369. if (overlay.opaque) {
  1370. st.splice(start, i - start, end, "overlay " + style)
  1371. i = start + 2
  1372. } else {
  1373. for (; start < i; start += 2) {
  1374. var cur = st[start+1]
  1375. st[start+1] = (cur ? cur + " " : "") + "overlay " + style
  1376. }
  1377. }
  1378. }, lineClasses)
  1379. };
  1380. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1381. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1382. }
  1383. function getLineStyles(cm, line, updateFrontier) {
  1384. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1385. var state = getStateBefore(cm, lineNo(line))
  1386. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state)
  1387. line.stateAfter = state
  1388. line.styles = result.styles
  1389. if (result.classes) { line.styleClasses = result.classes }
  1390. else if (line.styleClasses) { line.styleClasses = null }
  1391. if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ }
  1392. }
  1393. return line.styles
  1394. }
  1395. function getStateBefore(cm, n, precise) {
  1396. var doc = cm.doc, display = cm.display
  1397. if (!doc.mode.startState) { return true }
  1398. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter
  1399. if (!state) { state = startState(doc.mode) }
  1400. else { state = copyState(doc.mode, state) }
  1401. doc.iter(pos, n, function (line) {
  1402. processLine(cm, line.text, state)
  1403. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo
  1404. line.stateAfter = save ? copyState(doc.mode, state) : null
  1405. ++pos
  1406. })
  1407. if (precise) { doc.frontier = pos }
  1408. return state
  1409. }
  1410. // Lightweight form of highlight -- proceed over this line and
  1411. // update state, but don't save a style array. Used for lines that
  1412. // aren't currently visible.
  1413. function processLine(cm, text, state, startAt) {
  1414. var mode = cm.doc.mode
  1415. var stream = new StringStream(text, cm.options.tabSize)
  1416. stream.start = stream.pos = startAt || 0
  1417. if (text == "") { callBlankLine(mode, state) }
  1418. while (!stream.eol()) {
  1419. readToken(mode, stream, state)
  1420. stream.start = stream.pos
  1421. }
  1422. }
  1423. function callBlankLine(mode, state) {
  1424. if (mode.blankLine) { return mode.blankLine(state) }
  1425. if (!mode.innerMode) { return }
  1426. var inner = innerMode(mode, state)
  1427. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1428. }
  1429. function readToken(mode, stream, state, inner) {
  1430. for (var i = 0; i < 10; i++) {
  1431. if (inner) { inner[0] = innerMode(mode, state).mode }
  1432. var style = mode.token(stream, state)
  1433. if (stream.pos > stream.start) { return style }
  1434. }
  1435. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1436. }
  1437. // Utility for getTokenAt and getLineTokens
  1438. function takeToken(cm, pos, precise, asArray) {
  1439. var getObj = function (copy) { return ({
  1440. start: stream.start, end: stream.pos,
  1441. string: stream.current(),
  1442. type: style || null,
  1443. state: copy ? copyState(doc.mode, state) : state
  1444. }); }
  1445. var doc = cm.doc, mode = doc.mode, style
  1446. pos = clipPos(doc, pos)
  1447. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise)
  1448. var stream = new StringStream(line.text, cm.options.tabSize), tokens
  1449. if (asArray) { tokens = [] }
  1450. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1451. stream.start = stream.pos
  1452. style = readToken(mode, stream, state)
  1453. if (asArray) { tokens.push(getObj(true)) }
  1454. }
  1455. return asArray ? tokens : getObj()
  1456. }
  1457. function extractLineClasses(type, output) {
  1458. if (type) { for (;;) {
  1459. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1460. if (!lineClass) { break }
  1461. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1462. var prop = lineClass[1] ? "bgClass" : "textClass"
  1463. if (output[prop] == null)
  1464. { output[prop] = lineClass[2] }
  1465. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1466. { output[prop] += " " + lineClass[2] }
  1467. } }
  1468. return type
  1469. }
  1470. // Run the given mode's parser over a line, calling f for each token.
  1471. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  1472. var flattenSpans = mode.flattenSpans
  1473. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
  1474. var curStart = 0, curStyle = null
  1475. var stream = new StringStream(text, cm.options.tabSize), style
  1476. var inner = cm.options.addModeClass && [null]
  1477. if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses) }
  1478. while (!stream.eol()) {
  1479. if (stream.pos > cm.options.maxHighlightLength) {
  1480. flattenSpans = false
  1481. if (forceToEnd) { processLine(cm, text, state, stream.pos) }
  1482. stream.pos = text.length
  1483. style = null
  1484. } else {
  1485. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses)
  1486. }
  1487. if (inner) {
  1488. var mName = inner[0].name
  1489. if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
  1490. }
  1491. if (!flattenSpans || curStyle != style) {
  1492. while (curStart < stream.start) {
  1493. curStart = Math.min(stream.start, curStart + 5000)
  1494. f(curStart, curStyle)
  1495. }
  1496. curStyle = style
  1497. }
  1498. stream.start = stream.pos
  1499. }
  1500. while (curStart < stream.pos) {
  1501. // Webkit seems to refuse to render text nodes longer than 57444
  1502. // characters, and returns inaccurate measurements in nodes
  1503. // starting around 5000 chars.
  1504. var pos = Math.min(stream.pos, curStart + 5000)
  1505. f(pos, curStyle)
  1506. curStart = pos
  1507. }
  1508. }
  1509. // Finds the line to start with when starting a parse. Tries to
  1510. // find a line with a stateAfter, so that it can start with a
  1511. // valid state. If that fails, it returns the line with the
  1512. // smallest indentation, which tends to need the least context to
  1513. // parse correctly.
  1514. function findStartLine(cm, n, precise) {
  1515. var minindent, minline, doc = cm.doc
  1516. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1517. for (var search = n; search > lim; --search) {
  1518. if (search <= doc.first) { return doc.first }
  1519. var line = getLine(doc, search - 1)
  1520. if (line.stateAfter && (!precise || search <= doc.frontier)) { return search }
  1521. var indented = countColumn(line.text, null, cm.options.tabSize)
  1522. if (minline == null || minindent > indented) {
  1523. minline = search - 1
  1524. minindent = indented
  1525. }
  1526. }
  1527. return minline
  1528. }
  1529. // LINE DATA STRUCTURE
  1530. // Line objects. These hold state related to a line, including
  1531. // highlighting info (the styles array).
  1532. function Line(text, markedSpans, estimateHeight) {
  1533. this.text = text
  1534. attachMarkedSpans(this, markedSpans)
  1535. this.height = estimateHeight ? estimateHeight(this) : 1
  1536. }
  1537. eventMixin(Line)
  1538. Line.prototype.lineNo = function() { return lineNo(this) }
  1539. // Change the content (text, markers) of a line. Automatically
  1540. // invalidates cached information and tries to re-estimate the
  1541. // line's height.
  1542. function updateLine(line, text, markedSpans, estimateHeight) {
  1543. line.text = text
  1544. if (line.stateAfter) { line.stateAfter = null }
  1545. if (line.styles) { line.styles = null }
  1546. if (line.order != null) { line.order = null }
  1547. detachMarkedSpans(line)
  1548. attachMarkedSpans(line, markedSpans)
  1549. var estHeight = estimateHeight ? estimateHeight(line) : 1
  1550. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  1551. }
  1552. // Detach a line from the document tree and its markers.
  1553. function cleanUpLine(line) {
  1554. line.parent = null
  1555. detachMarkedSpans(line)
  1556. }
  1557. // Convert a style as returned by a mode (either null, or a string
  1558. // containing one or more styles) to a CSS style. This is cached,
  1559. // and also looks for line-wide styles.
  1560. var styleToClassCache = {};
  1561. var styleToClassCacheWithMode = {}
  1562. function interpretTokenStyle(style, options) {
  1563. if (!style || /^\s*$/.test(style)) { return null }
  1564. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  1565. return cache[style] ||
  1566. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1567. }
  1568. // Render the DOM representation of the text of a line. Also builds
  1569. // up a 'line map', which points at the DOM nodes that represent
  1570. // specific stretches of text, and is used by the measuring code.
  1571. // The returned object contains the DOM node, this map, and
  1572. // information about line-wide styles that were set by the mode.
  1573. function buildLineContent(cm, lineView) {
  1574. // The padding-right forces the element to have a 'border', which
  1575. // is needed on Webkit to be able to get line-level bounding
  1576. // rectangles for it (in measureChar).
  1577. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null)
  1578. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  1579. col: 0, pos: 0, cm: cm,
  1580. trailingSpace: false,
  1581. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
  1582. lineView.measure = {}
  1583. // Iterate over the logical lines that make up this visual line.
  1584. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1585. var line = i ? lineView.rest[i - 1] : lineView.line, order = void 0
  1586. builder.pos = 0
  1587. builder.addToken = buildToken
  1588. // Optionally wire in some hacks into the token-rendering
  1589. // algorithm, to deal with browser quirks.
  1590. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  1591. { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
  1592. builder.map = []
  1593. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  1594. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  1595. if (line.styleClasses) {
  1596. if (line.styleClasses.bgClass)
  1597. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
  1598. if (line.styleClasses.textClass)
  1599. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
  1600. }
  1601. // Ensure at least a single node is present, for measuring.
  1602. if (builder.map.length == 0)
  1603. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
  1604. // Store the map and a cache object for the current logical line
  1605. if (i == 0) {
  1606. lineView.measure.map = builder.map
  1607. lineView.measure.cache = {}
  1608. } else {
  1609. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1610. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  1611. }
  1612. }
  1613. // See issue #2901
  1614. if (webkit) {
  1615. var last = builder.content.lastChild
  1616. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1617. { builder.content.className = "cm-tab-wrap-hack" }
  1618. }
  1619. signal(cm, "renderLine", cm, lineView.line, builder.pre)
  1620. if (builder.pre.className)
  1621. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
  1622. return builder
  1623. }
  1624. function defaultSpecialCharPlaceholder(ch) {
  1625. var token = elt("span", "\u2022", "cm-invalidchar")
  1626. token.title = "\\u" + ch.charCodeAt(0).toString(16)
  1627. token.setAttribute("aria-label", token.title)
  1628. return token
  1629. }
  1630. // Build up the DOM representation for a single token, and add it to
  1631. // the line map. Takes care to render special characters separately.
  1632. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1633. if (!text) { return }
  1634. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  1635. var special = builder.cm.state.specialChars, mustWrap = false
  1636. var content
  1637. if (!special.test(text)) {
  1638. builder.col += text.length
  1639. content = document.createTextNode(displayText)
  1640. builder.map.push(builder.pos, builder.pos + text.length, content)
  1641. if (ie && ie_version < 9) { mustWrap = true }
  1642. builder.pos += text.length
  1643. } else {
  1644. content = document.createDocumentFragment()
  1645. var pos = 0
  1646. while (true) {
  1647. special.lastIndex = pos
  1648. var m = special.exec(text)
  1649. var skipped = m ? m.index - pos : text.length - pos
  1650. if (skipped) {
  1651. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  1652. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
  1653. else { content.appendChild(txt) }
  1654. builder.map.push(builder.pos, builder.pos + skipped, txt)
  1655. builder.col += skipped
  1656. builder.pos += skipped
  1657. }
  1658. if (!m) { break }
  1659. pos += skipped + 1
  1660. var txt$1 = void 0
  1661. if (m[0] == "\t") {
  1662. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
  1663. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
  1664. txt$1.setAttribute("role", "presentation")
  1665. txt$1.setAttribute("cm-text", "\t")
  1666. builder.col += tabWidth
  1667. } else if (m[0] == "\r" || m[0] == "\n") {
  1668. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
  1669. txt$1.setAttribute("cm-text", m[0])
  1670. builder.col += 1
  1671. } else {
  1672. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  1673. txt$1.setAttribute("cm-text", m[0])
  1674. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
  1675. else { content.appendChild(txt$1) }
  1676. builder.col += 1
  1677. }
  1678. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  1679. builder.pos++
  1680. }
  1681. }
  1682. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  1683. if (style || startStyle || endStyle || mustWrap || css) {
  1684. var fullStyle = style || ""
  1685. if (startStyle) { fullStyle += startStyle }
  1686. if (endStyle) { fullStyle += endStyle }
  1687. var token = elt("span", [content], fullStyle, css)
  1688. if (title) { token.title = title }
  1689. return builder.content.appendChild(token)
  1690. }
  1691. builder.content.appendChild(content)
  1692. }
  1693. function splitSpaces(text, trailingBefore) {
  1694. if (text.length > 1 && !/ /.test(text)) { return text }
  1695. var spaceBefore = trailingBefore, result = ""
  1696. for (var i = 0; i < text.length; i++) {
  1697. var ch = text.charAt(i)
  1698. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1699. { ch = "\u00a0" }
  1700. result += ch
  1701. spaceBefore = ch == " "
  1702. }
  1703. return result
  1704. }
  1705. // Work around nonsense dimensions being reported for stretches of
  1706. // right-to-left text.
  1707. function buildTokenBadBidi(inner, order) {
  1708. return function (builder, text, style, startStyle, endStyle, title, css) {
  1709. style = style ? style + " cm-force-border" : "cm-force-border"
  1710. var start = builder.pos, end = start + text.length
  1711. for (;;) {
  1712. // Find the part that overlaps with the start of this text
  1713. var part = void 0
  1714. for (var i = 0; i < order.length; i++) {
  1715. part = order[i]
  1716. if (part.to > start && part.from <= start) { break }
  1717. }
  1718. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1719. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
  1720. startStyle = null
  1721. text = text.slice(part.to - start)
  1722. start = part.to
  1723. }
  1724. }
  1725. }
  1726. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1727. var widget = !ignoreWidget && marker.widgetNode
  1728. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
  1729. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1730. if (!widget)
  1731. { widget = builder.content.appendChild(document.createElement("span")) }
  1732. widget.setAttribute("cm-marker", marker.id)
  1733. }
  1734. if (widget) {
  1735. builder.cm.display.input.setUneditable(widget)
  1736. builder.content.appendChild(widget)
  1737. }
  1738. builder.pos += size
  1739. builder.trailingSpace = false
  1740. }
  1741. // Outputs a number of spans to make up a line, taking highlighting
  1742. // and marked text into account.
  1743. function insertLineContent(line, builder, styles) {
  1744. var spans = line.markedSpans, allText = line.text, at = 0
  1745. if (!spans) {
  1746. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1747. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
  1748. return
  1749. }
  1750. var len = allText.length, pos = 0, i = 1, text = "", style, css
  1751. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
  1752. for (;;) {
  1753. if (nextChange == pos) { // Update current marker set
  1754. spanStyle = spanEndStyle = spanStartStyle = title = css = ""
  1755. collapsed = null; nextChange = Infinity
  1756. var foundBookmarks = [], endStyles = void 0
  1757. for (var j = 0; j < spans.length; ++j) {
  1758. var sp = spans[j], m = sp.marker
  1759. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1760. foundBookmarks.push(m)
  1761. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1762. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1763. nextChange = sp.to
  1764. spanEndStyle = ""
  1765. }
  1766. if (m.className) { spanStyle += " " + m.className }
  1767. if (m.css) { css = (css ? css + ";" : "") + m.css }
  1768. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
  1769. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
  1770. if (m.title && !title) { title = m.title }
  1771. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1772. { collapsed = sp }
  1773. } else if (sp.from > pos && nextChange > sp.from) {
  1774. nextChange = sp.from
  1775. }
  1776. }
  1777. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1778. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
  1779. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1780. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
  1781. if (collapsed && (collapsed.from || 0) == pos) {
  1782. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1783. collapsed.marker, collapsed.from == null)
  1784. if (collapsed.to == null) { return }
  1785. if (collapsed.to == pos) { collapsed = false }
  1786. }
  1787. }
  1788. if (pos >= len) { break }
  1789. var upto = Math.min(len, nextChange)
  1790. while (true) {
  1791. if (text) {
  1792. var end = pos + text.length
  1793. if (!collapsed) {
  1794. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  1795. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1796. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
  1797. }
  1798. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1799. pos = end
  1800. spanStartStyle = ""
  1801. }
  1802. text = allText.slice(at, at = styles[i++])
  1803. style = interpretTokenStyle(styles[i++], builder.cm.options)
  1804. }
  1805. }
  1806. }
  1807. // These objects are used to represent the visible (currently drawn)
  1808. // part of the document. A LineView may correspond to multiple
  1809. // logical lines, if those are connected by collapsed ranges.
  1810. function LineView(doc, line, lineN) {
  1811. // The starting line
  1812. this.line = line
  1813. // Continuing lines, if any
  1814. this.rest = visualLineContinued(line)
  1815. // Number of logical lines in this visual line
  1816. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  1817. this.node = this.text = null
  1818. this.hidden = lineIsHidden(doc, line)
  1819. }
  1820. // Create a range of LineView objects for the given lines.
  1821. function buildViewArray(cm, from, to) {
  1822. var array = [], nextPos
  1823. for (var pos = from; pos < to; pos = nextPos) {
  1824. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  1825. nextPos = pos + view.size
  1826. array.push(view)
  1827. }
  1828. return array
  1829. }
  1830. var operationGroup = null
  1831. function pushOperation(op) {
  1832. if (operationGroup) {
  1833. operationGroup.ops.push(op)
  1834. } else {
  1835. op.ownsGroup = operationGroup = {
  1836. ops: [op],
  1837. delayedCallbacks: []
  1838. }
  1839. }
  1840. }
  1841. function fireCallbacksForOps(group) {
  1842. // Calls delayed callbacks and cursorActivity handlers until no
  1843. // new ones appear
  1844. var callbacks = group.delayedCallbacks, i = 0
  1845. do {
  1846. for (; i < callbacks.length; i++)
  1847. { callbacks[i].call(null) }
  1848. for (var j = 0; j < group.ops.length; j++) {
  1849. var op = group.ops[j]
  1850. if (op.cursorActivityHandlers)
  1851. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1852. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
  1853. }
  1854. } while (i < callbacks.length)
  1855. }
  1856. function finishOperation(op, endCb) {
  1857. var group = op.ownsGroup
  1858. if (!group) { return }
  1859. try { fireCallbacksForOps(group) }
  1860. finally {
  1861. operationGroup = null
  1862. endCb(group)
  1863. }
  1864. }
  1865. var orphanDelayedCallbacks = null
  1866. // Often, we want to signal events at a point where we are in the
  1867. // middle of some work, but don't want the handler to start calling
  1868. // other methods on the editor, which might be in an inconsistent
  1869. // state or simply not expect any other events to happen.
  1870. // signalLater looks whether there are any handlers, and schedules
  1871. // them to be executed when the last operation ends, or, if no
  1872. // operation is active, when a timeout fires.
  1873. function signalLater(emitter, type /*, values...*/) {
  1874. var arr = getHandlers(emitter, type)
  1875. if (!arr.length) { return }
  1876. var args = Array.prototype.slice.call(arguments, 2), list
  1877. if (operationGroup) {
  1878. list = operationGroup.delayedCallbacks
  1879. } else if (orphanDelayedCallbacks) {
  1880. list = orphanDelayedCallbacks
  1881. } else {
  1882. list = orphanDelayedCallbacks = []
  1883. setTimeout(fireOrphanDelayed, 0)
  1884. }
  1885. var loop = function ( i ) {
  1886. list.push(function () { return arr[i].apply(null, args); })
  1887. };
  1888. for (var i = 0; i < arr.length; ++i)
  1889. loop( i );
  1890. }
  1891. function fireOrphanDelayed() {
  1892. var delayed = orphanDelayedCallbacks
  1893. orphanDelayedCallbacks = null
  1894. for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
  1895. }
  1896. // When an aspect of a line changes, a string is added to
  1897. // lineView.changes. This updates the relevant part of the line's
  1898. // DOM structure.
  1899. function updateLineForChanges(cm, lineView, lineN, dims) {
  1900. for (var j = 0; j < lineView.changes.length; j++) {
  1901. var type = lineView.changes[j]
  1902. if (type == "text") { updateLineText(cm, lineView) }
  1903. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
  1904. else if (type == "class") { updateLineClasses(lineView) }
  1905. else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
  1906. }
  1907. lineView.changes = null
  1908. }
  1909. // Lines with gutter elements, widgets or a background class need to
  1910. // be wrapped, and have the extra elements added to the wrapper div
  1911. function ensureLineWrapped(lineView) {
  1912. if (lineView.node == lineView.text) {
  1913. lineView.node = elt("div", null, null, "position: relative")
  1914. if (lineView.text.parentNode)
  1915. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
  1916. lineView.node.appendChild(lineView.text)
  1917. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
  1918. }
  1919. return lineView.node
  1920. }
  1921. function updateLineBackground(lineView) {
  1922. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
  1923. if (cls) { cls += " CodeMirror-linebackground" }
  1924. if (lineView.background) {
  1925. if (cls) { lineView.background.className = cls }
  1926. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
  1927. } else if (cls) {
  1928. var wrap = ensureLineWrapped(lineView)
  1929. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
  1930. }
  1931. }
  1932. // Wrapper around buildLineContent which will reuse the structure
  1933. // in display.externalMeasured when possible.
  1934. function getLineContent(cm, lineView) {
  1935. var ext = cm.display.externalMeasured
  1936. if (ext && ext.line == lineView.line) {
  1937. cm.display.externalMeasured = null
  1938. lineView.measure = ext.measure
  1939. return ext.built
  1940. }
  1941. return buildLineContent(cm, lineView)
  1942. }
  1943. // Redraw the line's text. Interacts with the background and text
  1944. // classes because the mode may output tokens that influence these
  1945. // classes.
  1946. function updateLineText(cm, lineView) {
  1947. var cls = lineView.text.className
  1948. var built = getLineContent(cm, lineView)
  1949. if (lineView.text == lineView.node) { lineView.node = built.pre }
  1950. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  1951. lineView.text = built.pre
  1952. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1953. lineView.bgClass = built.bgClass
  1954. lineView.textClass = built.textClass
  1955. updateLineClasses(lineView)
  1956. } else if (cls) {
  1957. lineView.text.className = cls
  1958. }
  1959. }
  1960. function updateLineClasses(lineView) {
  1961. updateLineBackground(lineView)
  1962. if (lineView.line.wrapClass)
  1963. { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
  1964. else if (lineView.node != lineView.text)
  1965. { lineView.node.className = "" }
  1966. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
  1967. lineView.text.className = textClass || ""
  1968. }
  1969. function updateLineGutter(cm, lineView, lineN, dims) {
  1970. if (lineView.gutter) {
  1971. lineView.node.removeChild(lineView.gutter)
  1972. lineView.gutter = null
  1973. }
  1974. if (lineView.gutterBackground) {
  1975. lineView.node.removeChild(lineView.gutterBackground)
  1976. lineView.gutterBackground = null
  1977. }
  1978. if (lineView.line.gutterClass) {
  1979. var wrap = ensureLineWrapped(lineView)
  1980. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1981. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
  1982. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  1983. }
  1984. var markers = lineView.line.gutterMarkers
  1985. if (cm.options.lineNumbers || markers) {
  1986. var wrap$1 = ensureLineWrapped(lineView)
  1987. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
  1988. cm.display.input.setUneditable(gutterWrap)
  1989. wrap$1.insertBefore(gutterWrap, lineView.text)
  1990. if (lineView.line.gutterClass)
  1991. { gutterWrap.className += " " + lineView.line.gutterClass }
  1992. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  1993. { lineView.lineNumber = gutterWrap.appendChild(
  1994. elt("div", lineNumberFor(cm.options, lineN),
  1995. "CodeMirror-linenumber CodeMirror-gutter-elt",
  1996. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
  1997. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  1998. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
  1999. if (found)
  2000. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2001. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
  2002. } }
  2003. }
  2004. }
  2005. function updateLineWidgets(cm, lineView, dims) {
  2006. if (lineView.alignable) { lineView.alignable = null }
  2007. for (var node = lineView.node.firstChild, next = void 0; node; node = next) {
  2008. next = node.nextSibling
  2009. if (node.className == "CodeMirror-linewidget")
  2010. { lineView.node.removeChild(node) }
  2011. }
  2012. insertLineWidgets(cm, lineView, dims)
  2013. }
  2014. // Build a line's DOM representation from scratch
  2015. function buildLineElement(cm, lineView, lineN, dims) {
  2016. var built = getLineContent(cm, lineView)
  2017. lineView.text = lineView.node = built.pre
  2018. if (built.bgClass) { lineView.bgClass = built.bgClass }
  2019. if (built.textClass) { lineView.textClass = built.textClass }
  2020. updateLineClasses(lineView)
  2021. updateLineGutter(cm, lineView, lineN, dims)
  2022. insertLineWidgets(cm, lineView, dims)
  2023. return lineView.node
  2024. }
  2025. // A lineView may contain multiple logical lines (when merged by
  2026. // collapsed spans). The widgets for all of them need to be drawn.
  2027. function insertLineWidgets(cm, lineView, dims) {
  2028. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2029. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2030. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
  2031. }
  2032. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2033. if (!line.widgets) { return }
  2034. var wrap = ensureLineWrapped(lineView)
  2035. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2036. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
  2037. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
  2038. positionLineWidget(widget, node, lineView, dims)
  2039. cm.display.input.setUneditable(node)
  2040. if (allowAbove && widget.above)
  2041. { wrap.insertBefore(node, lineView.gutter || lineView.text) }
  2042. else
  2043. { wrap.appendChild(node) }
  2044. signalLater(widget, "redraw")
  2045. }
  2046. }
  2047. function positionLineWidget(widget, node, lineView, dims) {
  2048. if (widget.noHScroll) {
  2049. (lineView.alignable || (lineView.alignable = [])).push(node)
  2050. var width = dims.wrapperWidth
  2051. node.style.left = dims.fixedPos + "px"
  2052. if (!widget.coverGutter) {
  2053. width -= dims.gutterTotalWidth
  2054. node.style.paddingLeft = dims.gutterTotalWidth + "px"
  2055. }
  2056. node.style.width = width + "px"
  2057. }
  2058. if (widget.coverGutter) {
  2059. node.style.zIndex = 5
  2060. node.style.position = "relative"
  2061. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
  2062. }
  2063. }
  2064. function widgetHeight(widget) {
  2065. if (widget.height != null) { return widget.height }
  2066. var cm = widget.doc.cm
  2067. if (!cm) { return 0 }
  2068. if (!contains(document.body, widget.node)) {
  2069. var parentStyle = "position: relative;"
  2070. if (widget.coverGutter)
  2071. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
  2072. if (widget.noHScroll)
  2073. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
  2074. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
  2075. }
  2076. return widget.height = widget.node.parentNode.offsetHeight
  2077. }
  2078. // Return true when the given mouse event happened in a widget
  2079. function eventInWidget(display, e) {
  2080. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2081. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2082. (n.parentNode == display.sizer && n != display.mover))
  2083. { return true }
  2084. }
  2085. }
  2086. // POSITION MEASUREMENT
  2087. function paddingTop(display) {return display.lineSpace.offsetTop}
  2088. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2089. function paddingH(display) {
  2090. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2091. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  2092. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2093. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  2094. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
  2095. return data
  2096. }
  2097. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2098. function displayWidth(cm) {
  2099. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2100. }
  2101. function displayHeight(cm) {
  2102. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2103. }
  2104. // Ensure the lineView.wrapping.heights array is populated. This is
  2105. // an array of bottom offsets for the lines that make up a drawn
  2106. // line. When lineWrapping is on, there might be more than one
  2107. // height.
  2108. function ensureLineHeights(cm, lineView, rect) {
  2109. var wrapping = cm.options.lineWrapping
  2110. var curWidth = wrapping && displayWidth(cm)
  2111. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2112. var heights = lineView.measure.heights = []
  2113. if (wrapping) {
  2114. lineView.measure.width = curWidth
  2115. var rects = lineView.text.firstChild.getClientRects()
  2116. for (var i = 0; i < rects.length - 1; i++) {
  2117. var cur = rects[i], next = rects[i + 1]
  2118. if (Math.abs(cur.bottom - next.bottom) > 2)
  2119. { heights.push((cur.bottom + next.top) / 2 - rect.top) }
  2120. }
  2121. }
  2122. heights.push(rect.bottom - rect.top)
  2123. }
  2124. }
  2125. // Find a line map (mapping character offsets to text nodes) and a
  2126. // measurement cache for the given line number. (A line view might
  2127. // contain multiple lines when collapsed ranges are present.)
  2128. function mapFromLineView(lineView, line, lineN) {
  2129. if (lineView.line == line)
  2130. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2131. for (var i = 0; i < lineView.rest.length; i++)
  2132. { if (lineView.rest[i] == line)
  2133. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2134. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2135. { if (lineNo(lineView.rest[i$1]) > lineN)
  2136. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2137. }
  2138. // Render a line into the hidden node display.externalMeasured. Used
  2139. // when measurement is needed for a line that's not in the viewport.
  2140. function updateExternalMeasurement(cm, line) {
  2141. line = visualLine(line)
  2142. var lineN = lineNo(line)
  2143. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  2144. view.lineN = lineN
  2145. var built = view.built = buildLineContent(cm, view)
  2146. view.text = built.pre
  2147. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2148. return view
  2149. }
  2150. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2151. // for a given character.
  2152. function measureChar(cm, line, ch, bias) {
  2153. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2154. }
  2155. // Find a line view that corresponds to the given line number.
  2156. function findViewForLine(cm, lineN) {
  2157. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2158. { return cm.display.view[findViewIndex(cm, lineN)] }
  2159. var ext = cm.display.externalMeasured
  2160. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2161. { return ext }
  2162. }
  2163. // Measurement can be split in two steps, the set-up work that
  2164. // applies to the whole line, and the measurement of the actual
  2165. // character. Functions like coordsChar, that need to do a lot of
  2166. // measurements in a row, can thus ensure that the set-up work is
  2167. // only done once.
  2168. function prepareMeasureForLine(cm, line) {
  2169. var lineN = lineNo(line)
  2170. var view = findViewForLine(cm, lineN)
  2171. if (view && !view.text) {
  2172. view = null
  2173. } else if (view && view.changes) {
  2174. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2175. cm.curOp.forceUpdate = true
  2176. }
  2177. if (!view)
  2178. { view = updateExternalMeasurement(cm, line) }
  2179. var info = mapFromLineView(view, line, lineN)
  2180. return {
  2181. line: line, view: view, rect: null,
  2182. map: info.map, cache: info.cache, before: info.before,
  2183. hasHeights: false
  2184. }
  2185. }
  2186. // Given a prepared measurement object, measures the position of an
  2187. // actual character (or fetches it from the cache).
  2188. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2189. if (prepared.before) { ch = -1 }
  2190. var key = ch + (bias || ""), found
  2191. if (prepared.cache.hasOwnProperty(key)) {
  2192. found = prepared.cache[key]
  2193. } else {
  2194. if (!prepared.rect)
  2195. { prepared.rect = prepared.view.text.getBoundingClientRect() }
  2196. if (!prepared.hasHeights) {
  2197. ensureLineHeights(cm, prepared.view, prepared.rect)
  2198. prepared.hasHeights = true
  2199. }
  2200. found = measureCharInner(cm, prepared, ch, bias)
  2201. if (!found.bogus) { prepared.cache[key] = found }
  2202. }
  2203. return {left: found.left, right: found.right,
  2204. top: varHeight ? found.rtop : found.top,
  2205. bottom: varHeight ? found.rbottom : found.bottom}
  2206. }
  2207. var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  2208. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  2209. var node, start, end, collapse, mStart, mEnd
  2210. // First, search the line map for the text node corresponding to,
  2211. // or closest to, the target character.
  2212. for (var i = 0; i < map$$1.length; i += 3) {
  2213. mStart = map$$1[i]
  2214. mEnd = map$$1[i + 1]
  2215. if (ch < mStart) {
  2216. start = 0; end = 1
  2217. collapse = "left"
  2218. } else if (ch < mEnd) {
  2219. start = ch - mStart
  2220. end = start + 1
  2221. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  2222. end = mEnd - mStart
  2223. start = end - 1
  2224. if (ch >= mEnd) { collapse = "right" }
  2225. }
  2226. if (start != null) {
  2227. node = map$$1[i + 2]
  2228. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2229. { collapse = bias }
  2230. if (bias == "left" && start == 0)
  2231. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  2232. node = map$$1[(i -= 3) + 2]
  2233. collapse = "left"
  2234. } }
  2235. if (bias == "right" && start == mEnd - mStart)
  2236. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  2237. node = map$$1[(i += 3) + 2]
  2238. collapse = "right"
  2239. } }
  2240. break
  2241. }
  2242. }
  2243. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2244. }
  2245. function getUsefulRect(rects, bias) {
  2246. var rect = nullRect
  2247. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2248. if ((rect = rects[i]).left != rect.right) { break }
  2249. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2250. if ((rect = rects[i$1]).left != rect.right) { break }
  2251. } }
  2252. return rect
  2253. }
  2254. function measureCharInner(cm, prepared, ch, bias) {
  2255. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  2256. var node = place.node, start = place.start, end = place.end, collapse = place.collapse
  2257. var rect
  2258. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2259. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2260. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
  2261. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
  2262. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2263. { rect = node.parentNode.getBoundingClientRect() }
  2264. else
  2265. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
  2266. if (rect.left || rect.right || start == 0) { break }
  2267. end = start
  2268. start = start - 1
  2269. collapse = "right"
  2270. }
  2271. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
  2272. } else { // If it is a widget, simply get the box for the whole widget.
  2273. if (start > 0) { collapse = bias = "right" }
  2274. var rects
  2275. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2276. { rect = rects[bias == "right" ? rects.length - 1 : 0] }
  2277. else
  2278. { rect = node.getBoundingClientRect() }
  2279. }
  2280. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2281. var rSpan = node.parentNode.getClientRects()[0]
  2282. if (rSpan)
  2283. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
  2284. else
  2285. { rect = nullRect }
  2286. }
  2287. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  2288. var mid = (rtop + rbot) / 2
  2289. var heights = prepared.view.measure.heights
  2290. var i = 0
  2291. for (; i < heights.length - 1; i++)
  2292. { if (mid < heights[i]) { break } }
  2293. var top = i ? heights[i - 1] : 0, bot = heights[i]
  2294. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2295. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2296. top: top, bottom: bot}
  2297. if (!rect.left && !rect.right) { result.bogus = true }
  2298. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  2299. return result
  2300. }
  2301. // Work around problem with bounding client rects on ranges being
  2302. // returned incorrectly when zoomed on IE10 and below.
  2303. function maybeUpdateRectForZooming(measure, rect) {
  2304. if (!window.screen || screen.logicalXDPI == null ||
  2305. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2306. { return rect }
  2307. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  2308. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  2309. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2310. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2311. }
  2312. function clearLineMeasurementCacheFor(lineView) {
  2313. if (lineView.measure) {
  2314. lineView.measure.cache = {}
  2315. lineView.measure.heights = null
  2316. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2317. { lineView.measure.caches[i] = {} } }
  2318. }
  2319. }
  2320. function clearLineMeasurementCache(cm) {
  2321. cm.display.externalMeasure = null
  2322. removeChildren(cm.display.lineMeasure)
  2323. for (var i = 0; i < cm.display.view.length; i++)
  2324. { clearLineMeasurementCacheFor(cm.display.view[i]) }
  2325. }
  2326. function clearCaches(cm) {
  2327. clearLineMeasurementCache(cm)
  2328. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  2329. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
  2330. cm.display.lineNumChars = null
  2331. }
  2332. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft }
  2333. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop }
  2334. // Converts a {top, bottom, left, right} box from line-local
  2335. // coordinates into another coordinate system. Context may be one of
  2336. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2337. // or "page".
  2338. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2339. if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
  2340. var size = widgetHeight(lineObj.widgets[i])
  2341. rect.top += size; rect.bottom += size
  2342. } } }
  2343. if (context == "line") { return rect }
  2344. if (!context) { context = "local" }
  2345. var yOff = heightAtLine(lineObj)
  2346. if (context == "local") { yOff += paddingTop(cm.display) }
  2347. else { yOff -= cm.display.viewOffset }
  2348. if (context == "page" || context == "window") {
  2349. var lOff = cm.display.lineSpace.getBoundingClientRect()
  2350. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  2351. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  2352. rect.left += xOff; rect.right += xOff
  2353. }
  2354. rect.top += yOff; rect.bottom += yOff
  2355. return rect
  2356. }
  2357. // Coverts a box from "div" coords to another coordinate system.
  2358. // Context may be "window", "page", "div", or "local"./null.
  2359. function fromCoordSystem(cm, coords, context) {
  2360. if (context == "div") { return coords }
  2361. var left = coords.left, top = coords.top
  2362. // First move into "page" coordinate system
  2363. if (context == "page") {
  2364. left -= pageScrollX()
  2365. top -= pageScrollY()
  2366. } else if (context == "local" || !context) {
  2367. var localBox = cm.display.sizer.getBoundingClientRect()
  2368. left += localBox.left
  2369. top += localBox.top
  2370. }
  2371. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  2372. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2373. }
  2374. function charCoords(cm, pos, context, lineObj, bias) {
  2375. if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
  2376. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2377. }
  2378. // Returns a box for a given cursor position, which may have an
  2379. // 'other' property containing the position of the secondary cursor
  2380. // on a bidi boundary.
  2381. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2382. lineObj = lineObj || getLine(cm.doc, pos.line)
  2383. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2384. function get(ch, right) {
  2385. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  2386. if (right) { m.left = m.right; } else { m.right = m.left }
  2387. return intoCoordSystem(cm, lineObj, m, context)
  2388. }
  2389. function getBidi(ch, partPos) {
  2390. var part = order[partPos], right = part.level % 2
  2391. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2392. part = order[--partPos]
  2393. ch = bidiRight(part) - (part.level % 2 ? 0 : 1)
  2394. right = true
  2395. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2396. part = order[++partPos]
  2397. ch = bidiLeft(part) - part.level % 2
  2398. right = false
  2399. }
  2400. if (right && ch == part.to && ch > part.from) { return get(ch - 1) }
  2401. return get(ch, right)
  2402. }
  2403. var order = getOrder(lineObj), ch = pos.ch
  2404. if (!order) { return get(ch) }
  2405. var partPos = getBidiPartAt(order, ch)
  2406. var val = getBidi(ch, partPos)
  2407. if (bidiOther != null) { val.other = getBidi(ch, bidiOther) }
  2408. return val
  2409. }
  2410. // Used to cheaply estimate the coordinates for a position. Used for
  2411. // intermediate scroll updates.
  2412. function estimateCoords(cm, pos) {
  2413. var left = 0
  2414. pos = clipPos(cm.doc, pos)
  2415. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
  2416. var lineObj = getLine(cm.doc, pos.line)
  2417. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  2418. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2419. }
  2420. // Positions returned by coordsChar contain some extra information.
  2421. // xRel is the relative x position of the input coordinates compared
  2422. // to the found position (so xRel > 0 means the coordinates are to
  2423. // the right of the character position, for example). When outside
  2424. // is true, that means the coordinates lie outside the line's
  2425. // vertical range.
  2426. function PosWithInfo(line, ch, outside, xRel) {
  2427. var pos = Pos(line, ch)
  2428. pos.xRel = xRel
  2429. if (outside) { pos.outside = true }
  2430. return pos
  2431. }
  2432. // Compute the character position closest to the given coordinates.
  2433. // Input must be lineSpace-local ("div" coordinate system).
  2434. function coordsChar(cm, x, y) {
  2435. var doc = cm.doc
  2436. y += cm.display.viewOffset
  2437. if (y < 0) { return PosWithInfo(doc.first, 0, true, -1) }
  2438. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  2439. if (lineN > last)
  2440. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1) }
  2441. if (x < 0) { x = 0 }
  2442. var lineObj = getLine(doc, lineN)
  2443. for (;;) {
  2444. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  2445. var merged = collapsedSpanAtEnd(lineObj)
  2446. var mergedPos = merged && merged.find(0, true)
  2447. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2448. { lineN = lineNo(lineObj = mergedPos.to.line) }
  2449. else
  2450. { return found }
  2451. }
  2452. }
  2453. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  2454. var innerOff = y - heightAtLine(lineObj)
  2455. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth
  2456. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  2457. function getX(ch) {
  2458. var sp = cursorCoords(cm, Pos(lineNo$$1, ch), "line", lineObj, preparedMeasure)
  2459. wrongLine = true
  2460. if (innerOff > sp.bottom) { return sp.left - adjust }
  2461. else if (innerOff < sp.top) { return sp.left + adjust }
  2462. else { wrongLine = false }
  2463. return sp.left
  2464. }
  2465. var bidi = getOrder(lineObj), dist = lineObj.text.length
  2466. var from = lineLeft(lineObj), to = lineRight(lineObj)
  2467. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine
  2468. if (x > toX) { return PosWithInfo(lineNo$$1, to, toOutside, 1) }
  2469. // Do a binary search between these bounds.
  2470. for (;;) {
  2471. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2472. var ch = x < fromX || x - fromX <= toX - x ? from : to
  2473. var outside = ch == from ? fromOutside : toOutside
  2474. var xDiff = x - (ch == from ? fromX : toX)
  2475. // This is a kludge to handle the case where the coordinates
  2476. // are after a line-wrapped line. We should replace it with a
  2477. // more general handling of cursor positions around line
  2478. // breaks. (Issue #4078)
  2479. if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 &&
  2480. ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) {
  2481. var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right")
  2482. if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) {
  2483. outside = false
  2484. ch++
  2485. xDiff = x - charSize.right
  2486. }
  2487. }
  2488. while (isExtendingChar(lineObj.text.charAt(ch))) { ++ch }
  2489. var pos = PosWithInfo(lineNo$$1, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0)
  2490. return pos
  2491. }
  2492. var step = Math.ceil(dist / 2), middle = from + step
  2493. if (bidi) {
  2494. middle = from
  2495. for (var i = 0; i < step; ++i) { middle = moveVisually(lineObj, middle, 1) }
  2496. }
  2497. var middleX = getX(middle)
  2498. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) { toX += 1000; } dist = step}
  2499. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step}
  2500. }
  2501. }
  2502. var measureText
  2503. // Compute the default text height.
  2504. function textHeight(display) {
  2505. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2506. if (measureText == null) {
  2507. measureText = elt("pre")
  2508. // Measure a bunch of lines, for browsers that compute
  2509. // fractional heights.
  2510. for (var i = 0; i < 49; ++i) {
  2511. measureText.appendChild(document.createTextNode("x"))
  2512. measureText.appendChild(elt("br"))
  2513. }
  2514. measureText.appendChild(document.createTextNode("x"))
  2515. }
  2516. removeChildrenAndAdd(display.measure, measureText)
  2517. var height = measureText.offsetHeight / 50
  2518. if (height > 3) { display.cachedTextHeight = height }
  2519. removeChildren(display.measure)
  2520. return height || 1
  2521. }
  2522. // Compute the default character width.
  2523. function charWidth(display) {
  2524. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2525. var anchor = elt("span", "xxxxxxxxxx")
  2526. var pre = elt("pre", [anchor])
  2527. removeChildrenAndAdd(display.measure, pre)
  2528. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
  2529. if (width > 2) { display.cachedCharWidth = width }
  2530. return width || 10
  2531. }
  2532. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2533. // view, so that we don't interleave reading and writing to the DOM.
  2534. function getDimensions(cm) {
  2535. var d = cm.display, left = {}, width = {}
  2536. var gutterLeft = d.gutters.clientLeft
  2537. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2538. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
  2539. width[cm.options.gutters[i]] = n.clientWidth
  2540. }
  2541. return {fixedPos: compensateForHScroll(d),
  2542. gutterTotalWidth: d.gutters.offsetWidth,
  2543. gutterLeft: left,
  2544. gutterWidth: width,
  2545. wrapperWidth: d.wrapper.clientWidth}
  2546. }
  2547. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2548. // but using getBoundingClientRect to get a sub-pixel-accurate
  2549. // result.
  2550. function compensateForHScroll(display) {
  2551. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2552. }
  2553. // Returns a function that estimates the height of a line, to use as
  2554. // first approximation until the line becomes visible (and is thus
  2555. // properly measurable).
  2556. function estimateHeight(cm) {
  2557. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
  2558. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  2559. return function (line) {
  2560. if (lineIsHidden(cm.doc, line)) { return 0 }
  2561. var widgetsHeight = 0
  2562. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2563. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
  2564. } }
  2565. if (wrapping)
  2566. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2567. else
  2568. { return widgetsHeight + th }
  2569. }
  2570. }
  2571. function estimateLineHeights(cm) {
  2572. var doc = cm.doc, est = estimateHeight(cm)
  2573. doc.iter(function (line) {
  2574. var estHeight = est(line)
  2575. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  2576. })
  2577. }
  2578. // Given a mouse event, find the corresponding position. If liberal
  2579. // is false, it checks whether a gutter or scrollbar was clicked,
  2580. // and returns null if it was. forRect is used by rectangular
  2581. // selections, and tries to estimate a character position even for
  2582. // coordinates beyond the right of the text.
  2583. function posFromMouse(cm, e, liberal, forRect) {
  2584. var display = cm.display
  2585. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2586. var x, y, space = display.lineSpace.getBoundingClientRect()
  2587. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2588. try { x = e.clientX - space.left; y = e.clientY - space.top }
  2589. catch (e) { return null }
  2590. var coords = coordsChar(cm, x, y), line
  2591. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2592. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  2593. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  2594. }
  2595. return coords
  2596. }
  2597. // Find the view element corresponding to a given line. Return null
  2598. // when the line isn't visible.
  2599. function findViewIndex(cm, n) {
  2600. if (n >= cm.display.viewTo) { return null }
  2601. n -= cm.display.viewFrom
  2602. if (n < 0) { return null }
  2603. var view = cm.display.view
  2604. for (var i = 0; i < view.length; i++) {
  2605. n -= view[i].size
  2606. if (n < 0) { return i }
  2607. }
  2608. }
  2609. function updateSelection(cm) {
  2610. cm.display.input.showSelection(cm.display.input.prepareSelection())
  2611. }
  2612. function prepareSelection(cm, primary) {
  2613. var doc = cm.doc, result = {}
  2614. var curFragment = result.cursors = document.createDocumentFragment()
  2615. var selFragment = result.selection = document.createDocumentFragment()
  2616. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2617. if (primary === false && i == doc.sel.primIndex) { continue }
  2618. var range$$1 = doc.sel.ranges[i]
  2619. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  2620. var collapsed = range$$1.empty()
  2621. if (collapsed || cm.options.showCursorWhenSelecting)
  2622. { drawSelectionCursor(cm, range$$1.head, curFragment) }
  2623. if (!collapsed)
  2624. { drawSelectionRange(cm, range$$1, selFragment) }
  2625. }
  2626. return result
  2627. }
  2628. // Draws a cursor for the given range
  2629. function drawSelectionCursor(cm, head, output) {
  2630. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
  2631. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
  2632. cursor.style.left = pos.left + "px"
  2633. cursor.style.top = pos.top + "px"
  2634. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
  2635. if (pos.other) {
  2636. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2637. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
  2638. otherCursor.style.display = ""
  2639. otherCursor.style.left = pos.other.left + "px"
  2640. otherCursor.style.top = pos.other.top + "px"
  2641. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
  2642. }
  2643. }
  2644. // Draws the given range as a highlighted selection
  2645. function drawSelectionRange(cm, range$$1, output) {
  2646. var display = cm.display, doc = cm.doc
  2647. var fragment = document.createDocumentFragment()
  2648. var padding = paddingH(cm.display), leftSide = padding.left
  2649. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  2650. function add(left, top, width, bottom) {
  2651. if (top < 0) { top = 0 }
  2652. top = Math.round(top)
  2653. bottom = Math.round(bottom)
  2654. 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")))
  2655. }
  2656. function drawForLine(line, fromArg, toArg) {
  2657. var lineObj = getLine(doc, line)
  2658. var lineLen = lineObj.text.length
  2659. var start, end
  2660. function coords(ch, bias) {
  2661. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2662. }
  2663. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
  2664. var leftPos = coords(from, "left"), rightPos, left, right
  2665. if (from == to) {
  2666. rightPos = leftPos
  2667. left = right = leftPos.left
  2668. } else {
  2669. rightPos = coords(to - 1, "right")
  2670. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp }
  2671. left = leftPos.left
  2672. right = rightPos.right
  2673. }
  2674. if (fromArg == null && from == 0) { left = leftSide }
  2675. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2676. add(left, leftPos.top, null, leftPos.bottom)
  2677. left = leftSide
  2678. if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) }
  2679. }
  2680. if (toArg == null && to == lineLen) { right = rightSide }
  2681. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2682. { start = leftPos }
  2683. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2684. { end = rightPos }
  2685. if (left < leftSide + 1) { left = leftSide }
  2686. add(left, rightPos.top, right - left, rightPos.bottom)
  2687. })
  2688. return {start: start, end: end}
  2689. }
  2690. var sFrom = range$$1.from(), sTo = range$$1.to()
  2691. if (sFrom.line == sTo.line) {
  2692. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  2693. } else {
  2694. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
  2695. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  2696. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  2697. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  2698. if (singleVLine) {
  2699. if (leftEnd.top < rightStart.top - 2) {
  2700. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  2701. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  2702. } else {
  2703. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  2704. }
  2705. }
  2706. if (leftEnd.bottom < rightStart.top)
  2707. { add(leftSide, leftEnd.bottom, null, rightStart.top) }
  2708. }
  2709. output.appendChild(fragment)
  2710. }
  2711. // Cursor-blinking
  2712. function restartBlink(cm) {
  2713. if (!cm.state.focused) { return }
  2714. var display = cm.display
  2715. clearInterval(display.blinker)
  2716. var on = true
  2717. display.cursorDiv.style.visibility = ""
  2718. if (cm.options.cursorBlinkRate > 0)
  2719. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2720. cm.options.cursorBlinkRate) }
  2721. else if (cm.options.cursorBlinkRate < 0)
  2722. { display.cursorDiv.style.visibility = "hidden" }
  2723. }
  2724. function ensureFocus(cm) {
  2725. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
  2726. }
  2727. function delayBlurEvent(cm) {
  2728. cm.state.delayingBlurEvent = true
  2729. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2730. cm.state.delayingBlurEvent = false
  2731. onBlur(cm)
  2732. } }, 100)
  2733. }
  2734. function onFocus(cm, e) {
  2735. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
  2736. if (cm.options.readOnly == "nocursor") { return }
  2737. if (!cm.state.focused) {
  2738. signal(cm, "focus", cm, e)
  2739. cm.state.focused = true
  2740. addClass(cm.display.wrapper, "CodeMirror-focused")
  2741. // This test prevents this from firing when a context
  2742. // menu is closed (since the input reset would kill the
  2743. // select-all detection hack)
  2744. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2745. cm.display.input.reset()
  2746. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
  2747. }
  2748. cm.display.input.receivedFocus()
  2749. }
  2750. restartBlink(cm)
  2751. }
  2752. function onBlur(cm, e) {
  2753. if (cm.state.delayingBlurEvent) { return }
  2754. if (cm.state.focused) {
  2755. signal(cm, "blur", cm, e)
  2756. cm.state.focused = false
  2757. rmClass(cm.display.wrapper, "CodeMirror-focused")
  2758. }
  2759. clearInterval(cm.display.blinker)
  2760. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
  2761. }
  2762. // Re-align line numbers and gutter marks to compensate for
  2763. // horizontal scrolling.
  2764. function alignHorizontally(cm) {
  2765. var display = cm.display, view = display.view
  2766. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  2767. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  2768. var gutterW = display.gutters.offsetWidth, left = comp + "px"
  2769. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  2770. if (cm.options.fixedGutter) {
  2771. if (view[i].gutter)
  2772. { view[i].gutter.style.left = left }
  2773. if (view[i].gutterBackground)
  2774. { view[i].gutterBackground.style.left = left }
  2775. }
  2776. var align = view[i].alignable
  2777. if (align) { for (var j = 0; j < align.length; j++)
  2778. { align[j].style.left = left } }
  2779. } }
  2780. if (cm.options.fixedGutter)
  2781. { display.gutters.style.left = (comp + gutterW) + "px" }
  2782. }
  2783. // Used to ensure that the line number gutter is still the right
  2784. // size for the current document size. Returns true when an update
  2785. // is needed.
  2786. function maybeUpdateLineNumberWidth(cm) {
  2787. if (!cm.options.lineNumbers) { return false }
  2788. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
  2789. if (last.length != display.lineNumChars) {
  2790. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  2791. "CodeMirror-linenumber CodeMirror-gutter-elt"))
  2792. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
  2793. display.lineGutter.style.width = ""
  2794. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  2795. display.lineNumWidth = display.lineNumInnerWidth + padding
  2796. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  2797. display.lineGutter.style.width = display.lineNumWidth + "px"
  2798. updateGutterSpace(cm)
  2799. return true
  2800. }
  2801. return false
  2802. }
  2803. // Read the actual heights of the rendered lines, and update their
  2804. // stored heights to match.
  2805. function updateHeightsInViewport(cm) {
  2806. var display = cm.display
  2807. var prevBottom = display.lineDiv.offsetTop
  2808. for (var i = 0; i < display.view.length; i++) {
  2809. var cur = display.view[i], height = void 0
  2810. if (cur.hidden) { continue }
  2811. if (ie && ie_version < 8) {
  2812. var bot = cur.node.offsetTop + cur.node.offsetHeight
  2813. height = bot - prevBottom
  2814. prevBottom = bot
  2815. } else {
  2816. var box = cur.node.getBoundingClientRect()
  2817. height = box.bottom - box.top
  2818. }
  2819. var diff = cur.line.height - height
  2820. if (height < 2) { height = textHeight(display) }
  2821. if (diff > .001 || diff < -.001) {
  2822. updateLineHeight(cur.line, height)
  2823. updateWidgetHeight(cur.line)
  2824. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2825. { updateWidgetHeight(cur.rest[j]) } }
  2826. }
  2827. }
  2828. }
  2829. // Read and store the height of line widgets associated with the
  2830. // given line.
  2831. function updateWidgetHeight(line) {
  2832. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
  2833. { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } }
  2834. }
  2835. // Compute the lines that are visible in a given viewport (defaults
  2836. // the the current scroll position). viewport may contain top,
  2837. // height, and ensure (see op.scrollToPos) properties.
  2838. function visibleLines(display, doc, viewport) {
  2839. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  2840. top = Math.floor(top - paddingTop(display))
  2841. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  2842. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
  2843. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2844. // forces those lines into the viewport (if possible).
  2845. if (viewport && viewport.ensure) {
  2846. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
  2847. if (ensureFrom < from) {
  2848. from = ensureFrom
  2849. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  2850. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2851. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  2852. to = ensureTo
  2853. }
  2854. }
  2855. return {from: from, to: Math.max(to, from + 1)}
  2856. }
  2857. // Sync the scrollable area and scrollbars, ensure the viewport
  2858. // covers the visible area.
  2859. function setScrollTop(cm, val) {
  2860. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  2861. cm.doc.scrollTop = val
  2862. if (!gecko) { updateDisplaySimple(cm, {top: val}) }
  2863. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
  2864. cm.display.scrollbars.setScrollTop(val)
  2865. if (gecko) { updateDisplaySimple(cm) }
  2866. startWorker(cm, 100)
  2867. }
  2868. // Sync scroller and scrollbar, ensure the gutter elements are
  2869. // aligned.
  2870. function setScrollLeft(cm, val, isScroller) {
  2871. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return }
  2872. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
  2873. cm.doc.scrollLeft = val
  2874. alignHorizontally(cm)
  2875. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
  2876. cm.display.scrollbars.setScrollLeft(val)
  2877. }
  2878. // Since the delta values reported on mouse wheel events are
  2879. // unstandardized between browsers and even browser versions, and
  2880. // generally horribly unpredictable, this code starts by measuring
  2881. // the scroll effect that the first few mouse wheel events have,
  2882. // and, from that, detects the way it can convert deltas to pixel
  2883. // offsets afterwards.
  2884. //
  2885. // The reason we want to know the amount a wheel event will scroll
  2886. // is that it gives us a chance to update the display before the
  2887. // actual scrolling happens, reducing flickering.
  2888. var wheelSamples = 0;
  2889. var wheelPixelsPerUnit = null
  2890. // Fill in a browser-detected starting value on browsers where we
  2891. // know one. These don't have to be accurate -- the result of them
  2892. // being wrong would just be a slight flicker on the first wheel
  2893. // scroll (if it is large enough).
  2894. if (ie) { wheelPixelsPerUnit = -.53 }
  2895. else if (gecko) { wheelPixelsPerUnit = 15 }
  2896. else if (chrome) { wheelPixelsPerUnit = -.7 }
  2897. else if (safari) { wheelPixelsPerUnit = -1/3 }
  2898. function wheelEventDelta(e) {
  2899. var dx = e.wheelDeltaX, dy = e.wheelDeltaY
  2900. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
  2901. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
  2902. else if (dy == null) { dy = e.wheelDelta }
  2903. return {x: dx, y: dy}
  2904. }
  2905. function wheelEventPixels(e) {
  2906. var delta = wheelEventDelta(e)
  2907. delta.x *= wheelPixelsPerUnit
  2908. delta.y *= wheelPixelsPerUnit
  2909. return delta
  2910. }
  2911. function onScrollWheel(cm, e) {
  2912. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
  2913. var display = cm.display, scroll = display.scroller
  2914. // Quit if there's nothing to scroll here
  2915. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  2916. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  2917. if (!(dx && canScrollX || dy && canScrollY)) { return }
  2918. // Webkit browsers on OS X abort momentum scrolls when the target
  2919. // of the scroll event is removed from the scrollable element.
  2920. // This hack (see related code in patchDisplay) makes sure the
  2921. // element is kept around.
  2922. if (dy && mac && webkit) {
  2923. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  2924. for (var i = 0; i < view.length; i++) {
  2925. if (view[i].node == cur) {
  2926. cm.display.currentWheelTarget = cur
  2927. break outer
  2928. }
  2929. }
  2930. }
  2931. }
  2932. // On some browsers, horizontal scrolling will cause redraws to
  2933. // happen before the gutter has been realigned, causing it to
  2934. // wriggle around in a most unseemly way. When we have an
  2935. // estimated pixels/delta value, we just handle horizontal
  2936. // scrolling entirely here. It'll be slightly off from native, but
  2937. // better than glitching out.
  2938. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  2939. if (dy && canScrollY)
  2940. { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) }
  2941. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)))
  2942. // Only prevent default scrolling if vertical scrolling is
  2943. // actually possible. Otherwise, it causes vertical scroll
  2944. // jitter on OSX trackpads when deltaX is small and deltaY
  2945. // is large (issue #3579)
  2946. if (!dy || (dy && canScrollY))
  2947. { e_preventDefault(e) }
  2948. display.wheelStartX = null // Abort measurement, if in progress
  2949. return
  2950. }
  2951. // 'Project' the visible viewport to cover the area that is being
  2952. // scrolled into view (if we know enough to estimate it).
  2953. if (dy && wheelPixelsPerUnit != null) {
  2954. var pixels = dy * wheelPixelsPerUnit
  2955. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
  2956. if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
  2957. else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
  2958. updateDisplaySimple(cm, {top: top, bottom: bot})
  2959. }
  2960. if (wheelSamples < 20) {
  2961. if (display.wheelStartX == null) {
  2962. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
  2963. display.wheelDX = dx; display.wheelDY = dy
  2964. setTimeout(function () {
  2965. if (display.wheelStartX == null) { return }
  2966. var movedX = scroll.scrollLeft - display.wheelStartX
  2967. var movedY = scroll.scrollTop - display.wheelStartY
  2968. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  2969. (movedX && display.wheelDX && movedX / display.wheelDX)
  2970. display.wheelStartX = display.wheelStartY = null
  2971. if (!sample) { return }
  2972. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  2973. ++wheelSamples
  2974. }, 200)
  2975. } else {
  2976. display.wheelDX += dx; display.wheelDY += dy
  2977. }
  2978. }
  2979. }
  2980. // SCROLLBARS
  2981. // Prepare DOM reads needed to update the scrollbars. Done in one
  2982. // shot to minimize update/measure roundtrips.
  2983. function measureForScrollbars(cm) {
  2984. var d = cm.display, gutterW = d.gutters.offsetWidth
  2985. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  2986. return {
  2987. clientHeight: d.scroller.clientHeight,
  2988. viewHeight: d.wrapper.clientHeight,
  2989. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  2990. viewWidth: d.wrapper.clientWidth,
  2991. barLeft: cm.options.fixedGutter ? gutterW : 0,
  2992. docHeight: docH,
  2993. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  2994. nativeBarWidth: d.nativeBarWidth,
  2995. gutterWidth: gutterW
  2996. }
  2997. }
  2998. function NativeScrollbars(place, scroll, cm) {
  2999. this.cm = cm
  3000. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
  3001. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
  3002. place(vert); place(horiz)
  3003. on(vert, "scroll", function () {
  3004. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
  3005. })
  3006. on(horiz, "scroll", function () {
  3007. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
  3008. })
  3009. this.checkedZeroWidth = false
  3010. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3011. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
  3012. }
  3013. NativeScrollbars.prototype = copyObj({
  3014. update: function(measure) {
  3015. var needsH = measure.scrollWidth > measure.clientWidth + 1
  3016. var needsV = measure.scrollHeight > measure.clientHeight + 1
  3017. var sWidth = measure.nativeBarWidth
  3018. if (needsV) {
  3019. this.vert.style.display = "block"
  3020. this.vert.style.bottom = needsH ? sWidth + "px" : "0"
  3021. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  3022. // A bug in IE8 can cause this value to be negative, so guard it.
  3023. this.vert.firstChild.style.height =
  3024. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
  3025. } else {
  3026. this.vert.style.display = ""
  3027. this.vert.firstChild.style.height = "0"
  3028. }
  3029. if (needsH) {
  3030. this.horiz.style.display = "block"
  3031. this.horiz.style.right = needsV ? sWidth + "px" : "0"
  3032. this.horiz.style.left = measure.barLeft + "px"
  3033. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  3034. this.horiz.firstChild.style.width =
  3035. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
  3036. } else {
  3037. this.horiz.style.display = ""
  3038. this.horiz.firstChild.style.width = "0"
  3039. }
  3040. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3041. if (sWidth == 0) { this.zeroWidthHack() }
  3042. this.checkedZeroWidth = true
  3043. }
  3044. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3045. },
  3046. setScrollLeft: function(pos) {
  3047. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
  3048. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz) }
  3049. },
  3050. setScrollTop: function(pos) {
  3051. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
  3052. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert) }
  3053. },
  3054. zeroWidthHack: function() {
  3055. var w = mac && !mac_geMountainLion ? "12px" : "18px"
  3056. this.horiz.style.height = this.vert.style.width = w
  3057. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
  3058. this.disableHoriz = new Delayed
  3059. this.disableVert = new Delayed
  3060. },
  3061. enableZeroWidthBar: function(bar, delay) {
  3062. bar.style.pointerEvents = "auto"
  3063. function maybeDisable() {
  3064. // To find out whether the scrollbar is still visible, we
  3065. // check whether the element under the pixel in the bottom
  3066. // left corner of the scrollbar box is the scrollbar box
  3067. // itself (when the bar is still visible) or its filler child
  3068. // (when the bar is hidden). If it is still visible, we keep
  3069. // it enabled, if it's hidden, we disable pointer events.
  3070. var box = bar.getBoundingClientRect()
  3071. var elt$$1 = document.elementFromPoint(box.left + 1, box.bottom - 1)
  3072. if (elt$$1 != bar) { bar.style.pointerEvents = "none" }
  3073. else { delay.set(1000, maybeDisable) }
  3074. }
  3075. delay.set(1000, maybeDisable)
  3076. },
  3077. clear: function() {
  3078. var parent = this.horiz.parentNode
  3079. parent.removeChild(this.horiz)
  3080. parent.removeChild(this.vert)
  3081. }
  3082. }, NativeScrollbars.prototype)
  3083. function NullScrollbars() {}
  3084. NullScrollbars.prototype = copyObj({
  3085. update: function() { return {bottom: 0, right: 0} },
  3086. setScrollLeft: function() {},
  3087. setScrollTop: function() {},
  3088. clear: function() {}
  3089. }, NullScrollbars.prototype)
  3090. function updateScrollbars(cm, measure) {
  3091. if (!measure) { measure = measureForScrollbars(cm) }
  3092. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
  3093. updateScrollbarsInner(cm, measure)
  3094. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3095. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3096. { updateHeightsInViewport(cm) }
  3097. updateScrollbarsInner(cm, measureForScrollbars(cm))
  3098. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
  3099. }
  3100. }
  3101. // Re-synchronize the fake scrollbars with the actual size of the
  3102. // content.
  3103. function updateScrollbarsInner(cm, measure) {
  3104. var d = cm.display
  3105. var sizes = d.scrollbars.update(measure)
  3106. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
  3107. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
  3108. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  3109. if (sizes.right && sizes.bottom) {
  3110. d.scrollbarFiller.style.display = "block"
  3111. d.scrollbarFiller.style.height = sizes.bottom + "px"
  3112. d.scrollbarFiller.style.width = sizes.right + "px"
  3113. } else { d.scrollbarFiller.style.display = "" }
  3114. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3115. d.gutterFiller.style.display = "block"
  3116. d.gutterFiller.style.height = sizes.bottom + "px"
  3117. d.gutterFiller.style.width = measure.gutterWidth + "px"
  3118. } else { d.gutterFiller.style.display = "" }
  3119. }
  3120. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
  3121. function initScrollbars(cm) {
  3122. if (cm.display.scrollbars) {
  3123. cm.display.scrollbars.clear()
  3124. if (cm.display.scrollbars.addClass)
  3125. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3126. }
  3127. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3128. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  3129. // Prevent clicks in the scrollbars from killing focus
  3130. on(node, "mousedown", function () {
  3131. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
  3132. })
  3133. node.setAttribute("cm-not-content", "true")
  3134. }, function (pos, axis) {
  3135. if (axis == "horizontal") { setScrollLeft(cm, pos) }
  3136. else { setScrollTop(cm, pos) }
  3137. }, cm)
  3138. if (cm.display.scrollbars.addClass)
  3139. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3140. }
  3141. // SCROLLING THINGS INTO VIEW
  3142. // If an editor sits on the top or bottom of the window, partially
  3143. // scrolled out of view, this ensures that the cursor is visible.
  3144. function maybeScrollWindow(cm, coords) {
  3145. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3146. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
  3147. if (coords.top + box.top < 0) { doScroll = true }
  3148. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
  3149. if (doScroll != null && !phantom) {
  3150. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (coords.left) + "px; width: 2px;"))
  3151. cm.display.lineSpace.appendChild(scrollNode)
  3152. scrollNode.scrollIntoView(doScroll)
  3153. cm.display.lineSpace.removeChild(scrollNode)
  3154. }
  3155. }
  3156. // Scroll a given position into view (immediately), verifying that
  3157. // it actually became visible (as line heights are accurately
  3158. // measured, the position of something may 'drift' during drawing).
  3159. function scrollPosIntoView(cm, pos, end, margin) {
  3160. if (margin == null) { margin = 0 }
  3161. var coords
  3162. for (var limit = 0; limit < 5; limit++) {
  3163. var changed = false
  3164. coords = cursorCoords(cm, pos)
  3165. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  3166. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  3167. Math.min(coords.top, endCoords.top) - margin,
  3168. Math.max(coords.left, endCoords.left),
  3169. Math.max(coords.bottom, endCoords.bottom) + margin)
  3170. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
  3171. if (scrollPos.scrollTop != null) {
  3172. setScrollTop(cm, scrollPos.scrollTop)
  3173. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
  3174. }
  3175. if (scrollPos.scrollLeft != null) {
  3176. setScrollLeft(cm, scrollPos.scrollLeft)
  3177. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
  3178. }
  3179. if (!changed) { break }
  3180. }
  3181. return coords
  3182. }
  3183. // Scroll a given set of coordinates into view (immediately).
  3184. function scrollIntoView(cm, x1, y1, x2, y2) {
  3185. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2)
  3186. if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop) }
  3187. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
  3188. }
  3189. // Calculate a new scroll position needed to scroll the given
  3190. // rectangle into view. Returns an object with scrollTop and
  3191. // scrollLeft properties. When these are undefined, the
  3192. // vertical/horizontal position does not need to be adjusted.
  3193. function calculateScrollPos(cm, x1, y1, x2, y2) {
  3194. var display = cm.display, snapMargin = textHeight(cm.display)
  3195. if (y1 < 0) { y1 = 0 }
  3196. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  3197. var screen = displayHeight(cm), result = {}
  3198. if (y2 - y1 > screen) { y2 = y1 + screen }
  3199. var docBottom = cm.doc.height + paddingVert(display)
  3200. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin
  3201. if (y1 < screentop) {
  3202. result.scrollTop = atTop ? 0 : y1
  3203. } else if (y2 > screentop + screen) {
  3204. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen)
  3205. if (newTop != screentop) { result.scrollTop = newTop }
  3206. }
  3207. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
  3208. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
  3209. var tooWide = x2 - x1 > screenw
  3210. if (tooWide) { x2 = x1 + screenw }
  3211. if (x1 < 10)
  3212. { result.scrollLeft = 0 }
  3213. else if (x1 < screenleft)
  3214. { result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)) }
  3215. else if (x2 > screenw + screenleft - 3)
  3216. { result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw }
  3217. return result
  3218. }
  3219. // Store a relative adjustment to the scroll position in the current
  3220. // operation (to be applied when the operation finishes).
  3221. function addToScrollPos(cm, left, top) {
  3222. if (left != null || top != null) { resolveScrollToPos(cm) }
  3223. if (left != null)
  3224. { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left }
  3225. if (top != null)
  3226. { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top }
  3227. }
  3228. // Make sure that at the end of the operation the current cursor is
  3229. // shown.
  3230. function ensureCursorVisible(cm) {
  3231. resolveScrollToPos(cm)
  3232. var cur = cm.getCursor(), from = cur, to = cur
  3233. if (!cm.options.lineWrapping) {
  3234. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur
  3235. to = Pos(cur.line, cur.ch + 1)
  3236. }
  3237. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}
  3238. }
  3239. // When an operation has its scrollToPos property set, and another
  3240. // scroll action is applied before the end of the operation, this
  3241. // 'simulates' scrolling that position into view in a cheap way, so
  3242. // that the effect of intermediate scroll commands is not ignored.
  3243. function resolveScrollToPos(cm) {
  3244. var range$$1 = cm.curOp.scrollToPos
  3245. if (range$$1) {
  3246. cm.curOp.scrollToPos = null
  3247. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to)
  3248. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  3249. Math.min(from.top, to.top) - range$$1.margin,
  3250. Math.max(from.right, to.right),
  3251. Math.max(from.bottom, to.bottom) + range$$1.margin)
  3252. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop)
  3253. }
  3254. }
  3255. // Operations are used to wrap a series of changes to the editor
  3256. // state in such a way that each change won't have to update the
  3257. // cursor and display (which would be awkward, slow, and
  3258. // error-prone). Instead, display updates are batched and then all
  3259. // combined and executed at once.
  3260. var nextOpId = 0
  3261. // Start a new operation.
  3262. function startOperation(cm) {
  3263. cm.curOp = {
  3264. cm: cm,
  3265. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3266. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3267. forceUpdate: false, // Used to force a redraw
  3268. updateInput: null, // Whether to reset the input textarea
  3269. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3270. changeObjs: null, // Accumulated changes, for firing change events
  3271. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3272. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3273. selectionChanged: false, // Whether the selection needs to be redrawn
  3274. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3275. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3276. scrollToPos: null, // Used to scroll to a specific position
  3277. focus: false,
  3278. id: ++nextOpId // Unique ID
  3279. }
  3280. pushOperation(cm.curOp)
  3281. }
  3282. // Finish an operation, updating the display and signalling delayed events
  3283. function endOperation(cm) {
  3284. var op = cm.curOp
  3285. finishOperation(op, function (group) {
  3286. for (var i = 0; i < group.ops.length; i++)
  3287. { group.ops[i].cm.curOp = null }
  3288. endOperations(group)
  3289. })
  3290. }
  3291. // The DOM updates done when an operation finishes are batched so
  3292. // that the minimum number of relayouts are required.
  3293. function endOperations(group) {
  3294. var ops = group.ops
  3295. for (var i = 0; i < ops.length; i++) // Read DOM
  3296. { endOperation_R1(ops[i]) }
  3297. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3298. { endOperation_W1(ops[i$1]) }
  3299. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3300. { endOperation_R2(ops[i$2]) }
  3301. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3302. { endOperation_W2(ops[i$3]) }
  3303. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3304. { endOperation_finish(ops[i$4]) }
  3305. }
  3306. function endOperation_R1(op) {
  3307. var cm = op.cm, display = cm.display
  3308. maybeClipScrollbars(cm)
  3309. if (op.updateMaxLine) { findMaxLine(cm) }
  3310. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3311. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3312. op.scrollToPos.to.line >= display.viewTo) ||
  3313. display.maxLineChanged && cm.options.lineWrapping
  3314. op.update = op.mustUpdate &&
  3315. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
  3316. }
  3317. function endOperation_W1(op) {
  3318. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  3319. }
  3320. function endOperation_R2(op) {
  3321. var cm = op.cm, display = cm.display
  3322. if (op.updatedDisplay) { updateHeightsInViewport(cm) }
  3323. op.barMeasure = measureForScrollbars(cm)
  3324. // If the max line changed since it was last measured, measure it,
  3325. // and ensure the document's width matches it.
  3326. // updateDisplay_W2 will use these properties to do the actual resizing
  3327. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3328. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  3329. cm.display.sizerWidth = op.adjustWidthTo
  3330. op.barMeasure.scrollWidth =
  3331. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  3332. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  3333. }
  3334. if (op.updatedDisplay || op.selectionChanged)
  3335. { op.preparedSelection = display.input.prepareSelection(op.focus) }
  3336. }
  3337. function endOperation_W2(op) {
  3338. var cm = op.cm
  3339. if (op.adjustWidthTo != null) {
  3340. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
  3341. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3342. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
  3343. cm.display.maxLineChanged = false
  3344. }
  3345. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  3346. if (op.preparedSelection)
  3347. { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
  3348. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3349. { updateScrollbars(cm, op.barMeasure) }
  3350. if (op.updatedDisplay)
  3351. { setDocumentHeight(cm, op.barMeasure) }
  3352. if (op.selectionChanged) { restartBlink(cm) }
  3353. if (cm.state.focused && op.updateInput)
  3354. { cm.display.input.reset(op.typing) }
  3355. if (takeFocus) { ensureFocus(op.cm) }
  3356. }
  3357. function endOperation_finish(op) {
  3358. var cm = op.cm, display = cm.display, doc = cm.doc
  3359. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
  3360. // Abort mouse wheel delta measurement, when scrolling explicitly
  3361. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3362. { display.wheelStartX = display.wheelStartY = null }
  3363. // Propagate the scroll position to the actual DOM scroller
  3364. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  3365. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop))
  3366. display.scrollbars.setScrollTop(doc.scrollTop)
  3367. display.scroller.scrollTop = doc.scrollTop
  3368. }
  3369. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  3370. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft))
  3371. display.scrollbars.setScrollLeft(doc.scrollLeft)
  3372. display.scroller.scrollLeft = doc.scrollLeft
  3373. alignHorizontally(cm)
  3374. }
  3375. // If we need to scroll a specific position into view, do so.
  3376. if (op.scrollToPos) {
  3377. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3378. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  3379. if (op.scrollToPos.isCursor && cm.state.focused) { maybeScrollWindow(cm, coords) }
  3380. }
  3381. // Fire events for markers that are hidden/unidden by editing or
  3382. // undoing
  3383. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  3384. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3385. { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
  3386. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3387. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
  3388. if (display.wrapper.offsetHeight)
  3389. { doc.scrollTop = cm.display.scroller.scrollTop }
  3390. // Fire change events, and delayed event handlers
  3391. if (op.changeObjs)
  3392. { signal(cm, "changes", cm, op.changeObjs) }
  3393. if (op.update)
  3394. { op.update.finish() }
  3395. }
  3396. // Run the given function in an operation
  3397. function runInOp(cm, f) {
  3398. if (cm.curOp) { return f() }
  3399. startOperation(cm)
  3400. try { return f() }
  3401. finally { endOperation(cm) }
  3402. }
  3403. // Wraps a function in an operation. Returns the wrapped function.
  3404. function operation(cm, f) {
  3405. return function() {
  3406. if (cm.curOp) { return f.apply(cm, arguments) }
  3407. startOperation(cm)
  3408. try { return f.apply(cm, arguments) }
  3409. finally { endOperation(cm) }
  3410. }
  3411. }
  3412. // Used to add methods to editor and doc instances, wrapping them in
  3413. // operations.
  3414. function methodOp(f) {
  3415. return function() {
  3416. if (this.curOp) { return f.apply(this, arguments) }
  3417. startOperation(this)
  3418. try { return f.apply(this, arguments) }
  3419. finally { endOperation(this) }
  3420. }
  3421. }
  3422. function docMethodOp(f) {
  3423. return function() {
  3424. var cm = this.cm
  3425. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3426. startOperation(cm)
  3427. try { return f.apply(this, arguments) }
  3428. finally { endOperation(cm) }
  3429. }
  3430. }
  3431. // Updates the display.view data structure for a given change to the
  3432. // document. From and to are in pre-change coordinates. Lendiff is
  3433. // the amount of lines added or subtracted by the change. This is
  3434. // used for changes that span multiple lines, or change the way
  3435. // lines are divided into visual lines. regLineChange (below)
  3436. // registers single-line changes.
  3437. function regChange(cm, from, to, lendiff) {
  3438. if (from == null) { from = cm.doc.first }
  3439. if (to == null) { to = cm.doc.first + cm.doc.size }
  3440. if (!lendiff) { lendiff = 0 }
  3441. var display = cm.display
  3442. if (lendiff && to < display.viewTo &&
  3443. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3444. { display.updateLineNumbers = from }
  3445. cm.curOp.viewChanged = true
  3446. if (from >= display.viewTo) { // Change after
  3447. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3448. { resetView(cm) }
  3449. } else if (to <= display.viewFrom) { // Change before
  3450. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3451. resetView(cm)
  3452. } else {
  3453. display.viewFrom += lendiff
  3454. display.viewTo += lendiff
  3455. }
  3456. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3457. resetView(cm)
  3458. } else if (from <= display.viewFrom) { // Top overlap
  3459. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3460. if (cut) {
  3461. display.view = display.view.slice(cut.index)
  3462. display.viewFrom = cut.lineN
  3463. display.viewTo += lendiff
  3464. } else {
  3465. resetView(cm)
  3466. }
  3467. } else if (to >= display.viewTo) { // Bottom overlap
  3468. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3469. if (cut$1) {
  3470. display.view = display.view.slice(0, cut$1.index)
  3471. display.viewTo = cut$1.lineN
  3472. } else {
  3473. resetView(cm)
  3474. }
  3475. } else { // Gap in the middle
  3476. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3477. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3478. if (cutTop && cutBot) {
  3479. display.view = display.view.slice(0, cutTop.index)
  3480. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3481. .concat(display.view.slice(cutBot.index))
  3482. display.viewTo += lendiff
  3483. } else {
  3484. resetView(cm)
  3485. }
  3486. }
  3487. var ext = display.externalMeasured
  3488. if (ext) {
  3489. if (to < ext.lineN)
  3490. { ext.lineN += lendiff }
  3491. else if (from < ext.lineN + ext.size)
  3492. { display.externalMeasured = null }
  3493. }
  3494. }
  3495. // Register a change to a single line. Type must be one of "text",
  3496. // "gutter", "class", "widget"
  3497. function regLineChange(cm, line, type) {
  3498. cm.curOp.viewChanged = true
  3499. var display = cm.display, ext = cm.display.externalMeasured
  3500. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3501. { display.externalMeasured = null }
  3502. if (line < display.viewFrom || line >= display.viewTo) { return }
  3503. var lineView = display.view[findViewIndex(cm, line)]
  3504. if (lineView.node == null) { return }
  3505. var arr = lineView.changes || (lineView.changes = [])
  3506. if (indexOf(arr, type) == -1) { arr.push(type) }
  3507. }
  3508. // Clear the view.
  3509. function resetView(cm) {
  3510. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3511. cm.display.view = []
  3512. cm.display.viewOffset = 0
  3513. }
  3514. function viewCuttingPoint(cm, oldN, newN, dir) {
  3515. var index = findViewIndex(cm, oldN), diff, view = cm.display.view
  3516. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3517. { return {index: index, lineN: newN} }
  3518. var n = cm.display.viewFrom
  3519. for (var i = 0; i < index; i++)
  3520. { n += view[i].size }
  3521. if (n != oldN) {
  3522. if (dir > 0) {
  3523. if (index == view.length - 1) { return null }
  3524. diff = (n + view[index].size) - oldN
  3525. index++
  3526. } else {
  3527. diff = n - oldN
  3528. }
  3529. oldN += diff; newN += diff
  3530. }
  3531. while (visualLineNo(cm.doc, newN) != newN) {
  3532. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3533. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3534. index += dir
  3535. }
  3536. return {index: index, lineN: newN}
  3537. }
  3538. // Force the view to cover a given range, adding empty view element
  3539. // or clipping off existing ones as needed.
  3540. function adjustView(cm, from, to) {
  3541. var display = cm.display, view = display.view
  3542. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3543. display.view = buildViewArray(cm, from, to)
  3544. display.viewFrom = from
  3545. } else {
  3546. if (display.viewFrom > from)
  3547. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
  3548. else if (display.viewFrom < from)
  3549. { display.view = display.view.slice(findViewIndex(cm, from)) }
  3550. display.viewFrom = from
  3551. if (display.viewTo < to)
  3552. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
  3553. else if (display.viewTo > to)
  3554. { display.view = display.view.slice(0, findViewIndex(cm, to)) }
  3555. }
  3556. display.viewTo = to
  3557. }
  3558. // Count the number of lines in the view whose DOM representation is
  3559. // out of date (or nonexistent).
  3560. function countDirtyView(cm) {
  3561. var view = cm.display.view, dirty = 0
  3562. for (var i = 0; i < view.length; i++) {
  3563. var lineView = view[i]
  3564. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
  3565. }
  3566. return dirty
  3567. }
  3568. // HIGHLIGHT WORKER
  3569. function startWorker(cm, time) {
  3570. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  3571. { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
  3572. }
  3573. function highlightWorker(cm) {
  3574. var doc = cm.doc
  3575. if (doc.frontier < doc.first) { doc.frontier = doc.first }
  3576. if (doc.frontier >= cm.display.viewTo) { return }
  3577. var end = +new Date + cm.options.workTime
  3578. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier))
  3579. var changedLines = []
  3580. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3581. if (doc.frontier >= cm.display.viewFrom) { // Visible
  3582. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength
  3583. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true)
  3584. line.styles = highlighted.styles
  3585. var oldCls = line.styleClasses, newCls = highlighted.classes
  3586. if (newCls) { line.styleClasses = newCls }
  3587. else if (oldCls) { line.styleClasses = null }
  3588. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3589. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
  3590. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
  3591. if (ischange) { changedLines.push(doc.frontier) }
  3592. line.stateAfter = tooLong ? state : copyState(doc.mode, state)
  3593. } else {
  3594. if (line.text.length <= cm.options.maxHighlightLength)
  3595. { processLine(cm, line.text, state) }
  3596. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null
  3597. }
  3598. ++doc.frontier
  3599. if (+new Date > end) {
  3600. startWorker(cm, cm.options.workDelay)
  3601. return true
  3602. }
  3603. })
  3604. if (changedLines.length) { runInOp(cm, function () {
  3605. for (var i = 0; i < changedLines.length; i++)
  3606. { regLineChange(cm, changedLines[i], "text") }
  3607. }) }
  3608. }
  3609. // DISPLAY DRAWING
  3610. function DisplayUpdate(cm, viewport, force) {
  3611. var display = cm.display
  3612. this.viewport = viewport
  3613. // Store some values that we'll need later (but don't want to force a relayout for)
  3614. this.visible = visibleLines(display, cm.doc, viewport)
  3615. this.editorIsHidden = !display.wrapper.offsetWidth
  3616. this.wrapperHeight = display.wrapper.clientHeight
  3617. this.wrapperWidth = display.wrapper.clientWidth
  3618. this.oldDisplayWidth = displayWidth(cm)
  3619. this.force = force
  3620. this.dims = getDimensions(cm)
  3621. this.events = []
  3622. }
  3623. DisplayUpdate.prototype.signal = function(emitter, type) {
  3624. if (hasHandler(emitter, type))
  3625. { this.events.push(arguments) }
  3626. }
  3627. DisplayUpdate.prototype.finish = function() {
  3628. var this$1 = this;
  3629. for (var i = 0; i < this.events.length; i++)
  3630. { signal.apply(null, this$1.events[i]) }
  3631. }
  3632. function maybeClipScrollbars(cm) {
  3633. var display = cm.display
  3634. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3635. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  3636. display.heightForcer.style.height = scrollGap(cm) + "px"
  3637. display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
  3638. display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
  3639. display.scrollbarsClipped = true
  3640. }
  3641. }
  3642. // Does the actual updating of the line display. Bails out
  3643. // (returning false) when there is nothing to be done and forced is
  3644. // false.
  3645. function updateDisplayIfNeeded(cm, update) {
  3646. var display = cm.display, doc = cm.doc
  3647. if (update.editorIsHidden) {
  3648. resetView(cm)
  3649. return false
  3650. }
  3651. // Bail out if the visible area is already rendered and nothing changed.
  3652. if (!update.force &&
  3653. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3654. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3655. display.renderedView == display.view && countDirtyView(cm) == 0)
  3656. { return false }
  3657. if (maybeUpdateLineNumberWidth(cm)) {
  3658. resetView(cm)
  3659. update.dims = getDimensions(cm)
  3660. }
  3661. // Compute a suitable new viewport (from & to)
  3662. var end = doc.first + doc.size
  3663. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  3664. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  3665. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) }
  3666. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) }
  3667. if (sawCollapsedSpans) {
  3668. from = visualLineNo(cm.doc, from)
  3669. to = visualLineEndNo(cm.doc, to)
  3670. }
  3671. var different = from != display.viewFrom || to != display.viewTo ||
  3672. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  3673. adjustView(cm, from, to)
  3674. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  3675. // Position the mover div to align with the current scroll position
  3676. cm.display.mover.style.top = display.viewOffset + "px"
  3677. var toUpdate = countDirtyView(cm)
  3678. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3679. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3680. { return false }
  3681. // For big changes, we hide the enclosing element during the
  3682. // update, since that speeds up the operations on most browsers.
  3683. var focused = activeElt()
  3684. if (toUpdate > 4) { display.lineDiv.style.display = "none" }
  3685. patchDisplay(cm, display.updateLineNumbers, update.dims)
  3686. if (toUpdate > 4) { display.lineDiv.style.display = "" }
  3687. display.renderedView = display.view
  3688. // There might have been a widget with a focused element that got
  3689. // hidden or updated, if so re-focus it.
  3690. if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus() }
  3691. // Prevent selection and cursors from interfering with the scroll
  3692. // width and height.
  3693. removeChildren(display.cursorDiv)
  3694. removeChildren(display.selectionDiv)
  3695. display.gutters.style.height = display.sizer.style.minHeight = 0
  3696. if (different) {
  3697. display.lastWrapHeight = update.wrapperHeight
  3698. display.lastWrapWidth = update.wrapperWidth
  3699. startWorker(cm, 400)
  3700. }
  3701. display.updateLineNumbers = null
  3702. return true
  3703. }
  3704. function postUpdateDisplay(cm, update) {
  3705. var viewport = update.viewport
  3706. for (var first = true;; first = false) {
  3707. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3708. // Clip forced viewport to actual scrollable area.
  3709. if (viewport && viewport.top != null)
  3710. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
  3711. // Updated line heights might result in the drawn area not
  3712. // actually covering the viewport. Keep looping until it does.
  3713. update.visible = visibleLines(cm.display, cm.doc, viewport)
  3714. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3715. { break }
  3716. }
  3717. if (!updateDisplayIfNeeded(cm, update)) { break }
  3718. updateHeightsInViewport(cm)
  3719. var barMeasure = measureForScrollbars(cm)
  3720. updateSelection(cm)
  3721. updateScrollbars(cm, barMeasure)
  3722. setDocumentHeight(cm, barMeasure)
  3723. }
  3724. update.signal(cm, "update", cm)
  3725. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3726. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
  3727. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
  3728. }
  3729. }
  3730. function updateDisplaySimple(cm, viewport) {
  3731. var update = new DisplayUpdate(cm, viewport)
  3732. if (updateDisplayIfNeeded(cm, update)) {
  3733. updateHeightsInViewport(cm)
  3734. postUpdateDisplay(cm, update)
  3735. var barMeasure = measureForScrollbars(cm)
  3736. updateSelection(cm)
  3737. updateScrollbars(cm, barMeasure)
  3738. setDocumentHeight(cm, barMeasure)
  3739. update.finish()
  3740. }
  3741. }
  3742. // Sync the actual display DOM structure with display.view, removing
  3743. // nodes for lines that are no longer in view, and creating the ones
  3744. // that are not there yet, and updating the ones that are out of
  3745. // date.
  3746. function patchDisplay(cm, updateNumbersFrom, dims) {
  3747. var display = cm.display, lineNumbers = cm.options.lineNumbers
  3748. var container = display.lineDiv, cur = container.firstChild
  3749. function rm(node) {
  3750. var next = node.nextSibling
  3751. // Works around a throw-scroll bug in OS X Webkit
  3752. if (webkit && mac && cm.display.currentWheelTarget == node)
  3753. { node.style.display = "none" }
  3754. else
  3755. { node.parentNode.removeChild(node) }
  3756. return next
  3757. }
  3758. var view = display.view, lineN = display.viewFrom
  3759. // Loop over the elements in the view, syncing cur (the DOM nodes
  3760. // in display.lineDiv) with the view as we go.
  3761. for (var i = 0; i < view.length; i++) {
  3762. var lineView = view[i]
  3763. if (lineView.hidden) {
  3764. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3765. var node = buildLineElement(cm, lineView, lineN, dims)
  3766. container.insertBefore(node, cur)
  3767. } else { // Already drawn
  3768. while (cur != lineView.node) { cur = rm(cur) }
  3769. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3770. updateNumbersFrom <= lineN && lineView.lineNumber
  3771. if (lineView.changes) {
  3772. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
  3773. updateLineForChanges(cm, lineView, lineN, dims)
  3774. }
  3775. if (updateNumber) {
  3776. removeChildren(lineView.lineNumber)
  3777. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  3778. }
  3779. cur = lineView.node.nextSibling
  3780. }
  3781. lineN += lineView.size
  3782. }
  3783. while (cur) { cur = rm(cur) }
  3784. }
  3785. function updateGutterSpace(cm) {
  3786. var width = cm.display.gutters.offsetWidth
  3787. cm.display.sizer.style.marginLeft = width + "px"
  3788. }
  3789. function setDocumentHeight(cm, measure) {
  3790. cm.display.sizer.style.minHeight = measure.docHeight + "px"
  3791. cm.display.heightForcer.style.top = measure.docHeight + "px"
  3792. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
  3793. }
  3794. // Rebuild the gutter elements, ensure the margin to the left of the
  3795. // code matches their width.
  3796. function updateGutters(cm) {
  3797. var gutters = cm.display.gutters, specs = cm.options.gutters
  3798. removeChildren(gutters)
  3799. var i = 0
  3800. for (; i < specs.length; ++i) {
  3801. var gutterClass = specs[i]
  3802. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
  3803. if (gutterClass == "CodeMirror-linenumbers") {
  3804. cm.display.lineGutter = gElt
  3805. gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
  3806. }
  3807. }
  3808. gutters.style.display = i ? "" : "none"
  3809. updateGutterSpace(cm)
  3810. }
  3811. // Make sure the gutters options contains the element
  3812. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3813. function setGuttersForLineNumbers(options) {
  3814. var found = indexOf(options.gutters, "CodeMirror-linenumbers")
  3815. if (found == -1 && options.lineNumbers) {
  3816. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
  3817. } else if (found > -1 && !options.lineNumbers) {
  3818. options.gutters = options.gutters.slice(0)
  3819. options.gutters.splice(found, 1)
  3820. }
  3821. }
  3822. // Selection objects are immutable. A new one is created every time
  3823. // the selection changes. A selection is one or more non-overlapping
  3824. // (and non-touching) ranges, sorted, and an integer that indicates
  3825. // which one is the primary selection (the one that's scrolled into
  3826. // view, that getCursor returns, etc).
  3827. function Selection(ranges, primIndex) {
  3828. this.ranges = ranges
  3829. this.primIndex = primIndex
  3830. }
  3831. Selection.prototype = {
  3832. primary: function() { return this.ranges[this.primIndex] },
  3833. equals: function(other) {
  3834. var this$1 = this;
  3835. if (other == this) { return true }
  3836. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  3837. for (var i = 0; i < this.ranges.length; i++) {
  3838. var here = this$1.ranges[i], there = other.ranges[i]
  3839. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) { return false }
  3840. }
  3841. return true
  3842. },
  3843. deepCopy: function() {
  3844. var this$1 = this;
  3845. var out = []
  3846. for (var i = 0; i < this.ranges.length; i++)
  3847. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
  3848. return new Selection(out, this.primIndex)
  3849. },
  3850. somethingSelected: function() {
  3851. var this$1 = this;
  3852. for (var i = 0; i < this.ranges.length; i++)
  3853. { if (!this$1.ranges[i].empty()) { return true } }
  3854. return false
  3855. },
  3856. contains: function(pos, end) {
  3857. var this$1 = this;
  3858. if (!end) { end = pos }
  3859. for (var i = 0; i < this.ranges.length; i++) {
  3860. var range = this$1.ranges[i]
  3861. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  3862. { return i }
  3863. }
  3864. return -1
  3865. }
  3866. }
  3867. function Range(anchor, head) {
  3868. this.anchor = anchor; this.head = head
  3869. }
  3870. Range.prototype = {
  3871. from: function() { return minPos(this.anchor, this.head) },
  3872. to: function() { return maxPos(this.anchor, this.head) },
  3873. empty: function() {
  3874. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch
  3875. }
  3876. }
  3877. // Take an unsorted, potentially overlapping set of ranges, and
  3878. // build a selection out of it. 'Consumes' ranges array (modifying
  3879. // it).
  3880. function normalizeSelection(ranges, primIndex) {
  3881. var prim = ranges[primIndex]
  3882. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
  3883. primIndex = indexOf(ranges, prim)
  3884. for (var i = 1; i < ranges.length; i++) {
  3885. var cur = ranges[i], prev = ranges[i - 1]
  3886. if (cmp(prev.to(), cur.from()) >= 0) {
  3887. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
  3888. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  3889. if (i <= primIndex) { --primIndex }
  3890. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  3891. }
  3892. }
  3893. return new Selection(ranges, primIndex)
  3894. }
  3895. function simpleSelection(anchor, head) {
  3896. return new Selection([new Range(anchor, head || anchor)], 0)
  3897. }
  3898. // Compute the position of the end of a change (its 'to' property
  3899. // refers to the pre-change end).
  3900. function changeEnd(change) {
  3901. if (!change.text) { return change.to }
  3902. return Pos(change.from.line + change.text.length - 1,
  3903. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  3904. }
  3905. // Adjust a position to refer to the post-change position of the
  3906. // same text, or the end of the change if the change covers it.
  3907. function adjustForChange(pos, change) {
  3908. if (cmp(pos, change.from) < 0) { return pos }
  3909. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  3910. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
  3911. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
  3912. return Pos(line, ch)
  3913. }
  3914. function computeSelAfterChange(doc, change) {
  3915. var out = []
  3916. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3917. var range = doc.sel.ranges[i]
  3918. out.push(new Range(adjustForChange(range.anchor, change),
  3919. adjustForChange(range.head, change)))
  3920. }
  3921. return normalizeSelection(out, doc.sel.primIndex)
  3922. }
  3923. function offsetPos(pos, old, nw) {
  3924. if (pos.line == old.line)
  3925. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  3926. else
  3927. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  3928. }
  3929. // Used by replaceSelections to allow moving the selection to the
  3930. // start or around the replaced test. Hint may be "start" or "around".
  3931. function computeReplacedSel(doc, changes, hint) {
  3932. var out = []
  3933. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
  3934. for (var i = 0; i < changes.length; i++) {
  3935. var change = changes[i]
  3936. var from = offsetPos(change.from, oldPrev, newPrev)
  3937. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  3938. oldPrev = change.to
  3939. newPrev = to
  3940. if (hint == "around") {
  3941. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
  3942. out[i] = new Range(inv ? to : from, inv ? from : to)
  3943. } else {
  3944. out[i] = new Range(from, from)
  3945. }
  3946. }
  3947. return new Selection(out, doc.sel.primIndex)
  3948. }
  3949. // Used to get the editor into a consistent state again when options change.
  3950. function loadMode(cm) {
  3951. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  3952. resetModeState(cm)
  3953. }
  3954. function resetModeState(cm) {
  3955. cm.doc.iter(function (line) {
  3956. if (line.stateAfter) { line.stateAfter = null }
  3957. if (line.styles) { line.styles = null }
  3958. })
  3959. cm.doc.frontier = cm.doc.first
  3960. startWorker(cm, 100)
  3961. cm.state.modeGen++
  3962. if (cm.curOp) { regChange(cm) }
  3963. }
  3964. // DOCUMENT DATA STRUCTURE
  3965. // By default, updates that start and end at the beginning of a line
  3966. // are treated specially, in order to make the association of line
  3967. // widgets and marker elements with the text behave more intuitive.
  3968. function isWholeLineUpdate(doc, change) {
  3969. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  3970. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  3971. }
  3972. // Perform a change on the document data structure.
  3973. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  3974. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  3975. function update(line, text, spans) {
  3976. updateLine(line, text, spans, estimateHeight$$1)
  3977. signalLater(line, "change", line, change)
  3978. }
  3979. function linesFor(start, end) {
  3980. var result = []
  3981. for (var i = start; i < end; ++i)
  3982. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)) }
  3983. return result
  3984. }
  3985. var from = change.from, to = change.to, text = change.text
  3986. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  3987. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
  3988. // Adjust the line structure
  3989. if (change.full) {
  3990. doc.insert(0, linesFor(0, text.length))
  3991. doc.remove(text.length, doc.size - text.length)
  3992. } else if (isWholeLineUpdate(doc, change)) {
  3993. // This is a whole-line replace. Treated specially to make
  3994. // sure line objects move the way they are supposed to.
  3995. var added = linesFor(0, text.length - 1)
  3996. update(lastLine, lastLine.text, lastSpans)
  3997. if (nlines) { doc.remove(from.line, nlines) }
  3998. if (added.length) { doc.insert(from.line, added) }
  3999. } else if (firstLine == lastLine) {
  4000. if (text.length == 1) {
  4001. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  4002. } else {
  4003. var added$1 = linesFor(1, text.length - 1)
  4004. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1))
  4005. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4006. doc.insert(from.line + 1, added$1)
  4007. }
  4008. } else if (text.length == 1) {
  4009. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  4010. doc.remove(from.line + 1, nlines)
  4011. } else {
  4012. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4013. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  4014. var added$2 = linesFor(1, text.length - 1)
  4015. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) }
  4016. doc.insert(from.line + 1, added$2)
  4017. }
  4018. signalLater(doc, "change", doc, change)
  4019. }
  4020. // Call f for all linked documents.
  4021. function linkedDocs(doc, f, sharedHistOnly) {
  4022. function propagate(doc, skip, sharedHist) {
  4023. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4024. var rel = doc.linked[i]
  4025. if (rel.doc == skip) { continue }
  4026. var shared = sharedHist && rel.sharedHist
  4027. if (sharedHistOnly && !shared) { continue }
  4028. f(rel.doc, shared)
  4029. propagate(rel.doc, doc, shared)
  4030. } }
  4031. }
  4032. propagate(doc, null, true)
  4033. }
  4034. // Attach a document to an editor.
  4035. function attachDoc(cm, doc) {
  4036. if (doc.cm) { throw new Error("This document is already in use.") }
  4037. cm.doc = doc
  4038. doc.cm = cm
  4039. estimateLineHeights(cm)
  4040. loadMode(cm)
  4041. if (!cm.options.lineWrapping) { findMaxLine(cm) }
  4042. cm.options.mode = doc.modeOption
  4043. regChange(cm)
  4044. }
  4045. function History(startGen) {
  4046. // Arrays of change events and selections. Doing something adds an
  4047. // event to done and clears undo. Undoing moves events from done
  4048. // to undone, redoing moves them in the other direction.
  4049. this.done = []; this.undone = []
  4050. this.undoDepth = Infinity
  4051. // Used to track when changes can be merged into a single undo
  4052. // event
  4053. this.lastModTime = this.lastSelTime = 0
  4054. this.lastOp = this.lastSelOp = null
  4055. this.lastOrigin = this.lastSelOrigin = null
  4056. // Used by the isClean() method
  4057. this.generation = this.maxGeneration = startGen || 1
  4058. }
  4059. // Create a history change event from an updateDoc-style change
  4060. // object.
  4061. function historyChangeFromChange(doc, change) {
  4062. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
  4063. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  4064. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
  4065. return histChange
  4066. }
  4067. // Pop all selection events off the end of a history array. Stop at
  4068. // a change event.
  4069. function clearSelectionEvents(array) {
  4070. while (array.length) {
  4071. var last = lst(array)
  4072. if (last.ranges) { array.pop() }
  4073. else { break }
  4074. }
  4075. }
  4076. // Find the top change event in the history. Pop off selection
  4077. // events that are in the way.
  4078. function lastChangeEvent(hist, force) {
  4079. if (force) {
  4080. clearSelectionEvents(hist.done)
  4081. return lst(hist.done)
  4082. } else if (hist.done.length && !lst(hist.done).ranges) {
  4083. return lst(hist.done)
  4084. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4085. hist.done.pop()
  4086. return lst(hist.done)
  4087. }
  4088. }
  4089. // Register a change in the history. Merges changes that are within
  4090. // a single operation, or are close together with an origin that
  4091. // allows merging (starting with "+") into a single event.
  4092. function addChangeToHistory(doc, change, selAfter, opId) {
  4093. var hist = doc.history
  4094. hist.undone.length = 0
  4095. var time = +new Date, cur
  4096. var last
  4097. if ((hist.lastOp == opId ||
  4098. hist.lastOrigin == change.origin && change.origin &&
  4099. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  4100. change.origin.charAt(0) == "*")) &&
  4101. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4102. // Merge this change into the last event
  4103. last = lst(cur.changes)
  4104. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4105. // Optimized case for simple insertion -- don't want to add
  4106. // new changesets for every character typed
  4107. last.to = changeEnd(change)
  4108. } else {
  4109. // Add new sub-event
  4110. cur.changes.push(historyChangeFromChange(doc, change))
  4111. }
  4112. } else {
  4113. // Can not be merged, start a new event.
  4114. var before = lst(hist.done)
  4115. if (!before || !before.ranges)
  4116. { pushSelectionToHistory(doc.sel, hist.done) }
  4117. cur = {changes: [historyChangeFromChange(doc, change)],
  4118. generation: hist.generation}
  4119. hist.done.push(cur)
  4120. while (hist.done.length > hist.undoDepth) {
  4121. hist.done.shift()
  4122. if (!hist.done[0].ranges) { hist.done.shift() }
  4123. }
  4124. }
  4125. hist.done.push(selAfter)
  4126. hist.generation = ++hist.maxGeneration
  4127. hist.lastModTime = hist.lastSelTime = time
  4128. hist.lastOp = hist.lastSelOp = opId
  4129. hist.lastOrigin = hist.lastSelOrigin = change.origin
  4130. if (!last) { signal(doc, "historyAdded") }
  4131. }
  4132. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4133. var ch = origin.charAt(0)
  4134. return ch == "*" ||
  4135. ch == "+" &&
  4136. prev.ranges.length == sel.ranges.length &&
  4137. prev.somethingSelected() == sel.somethingSelected() &&
  4138. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4139. }
  4140. // Called whenever the selection changes, sets the new selection as
  4141. // the pending selection in the history, and pushes the old pending
  4142. // selection into the 'done' array when it was significantly
  4143. // different (in number of selected ranges, emptiness, or time).
  4144. function addSelectionToHistory(doc, sel, opId, options) {
  4145. var hist = doc.history, origin = options && options.origin
  4146. // A new event is started when the previous origin does not match
  4147. // the current, or the origins don't allow matching. Origins
  4148. // starting with * are always merged, those starting with + are
  4149. // merged when similar and close together in time.
  4150. if (opId == hist.lastSelOp ||
  4151. (origin && hist.lastSelOrigin == origin &&
  4152. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4153. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4154. { hist.done[hist.done.length - 1] = sel }
  4155. else
  4156. { pushSelectionToHistory(sel, hist.done) }
  4157. hist.lastSelTime = +new Date
  4158. hist.lastSelOrigin = origin
  4159. hist.lastSelOp = opId
  4160. if (options && options.clearRedo !== false)
  4161. { clearSelectionEvents(hist.undone) }
  4162. }
  4163. function pushSelectionToHistory(sel, dest) {
  4164. var top = lst(dest)
  4165. if (!(top && top.ranges && top.equals(sel)))
  4166. { dest.push(sel) }
  4167. }
  4168. // Used to store marked span information in the history.
  4169. function attachLocalSpans(doc, change, from, to) {
  4170. var existing = change["spans_" + doc.id], n = 0
  4171. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4172. if (line.markedSpans)
  4173. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans }
  4174. ++n
  4175. })
  4176. }
  4177. // When un/re-doing restores text containing marked spans, those
  4178. // that have been explicitly cleared should not be restored.
  4179. function removeClearedSpans(spans) {
  4180. if (!spans) { return null }
  4181. var out
  4182. for (var i = 0; i < spans.length; ++i) {
  4183. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
  4184. else if (out) { out.push(spans[i]) }
  4185. }
  4186. return !out ? spans : out.length ? out : null
  4187. }
  4188. // Retrieve and filter the old marked spans stored in a change event.
  4189. function getOldSpans(doc, change) {
  4190. var found = change["spans_" + doc.id]
  4191. if (!found) { return null }
  4192. var nw = []
  4193. for (var i = 0; i < change.text.length; ++i)
  4194. { nw.push(removeClearedSpans(found[i])) }
  4195. return nw
  4196. }
  4197. // Used for un/re-doing changes from the history. Combines the
  4198. // result of computing the existing spans with the set of spans that
  4199. // existed in the history (so that deleting around a span and then
  4200. // undoing brings back the span).
  4201. function mergeOldSpans(doc, change) {
  4202. var old = getOldSpans(doc, change)
  4203. var stretched = stretchSpansOverChange(doc, change)
  4204. if (!old) { return stretched }
  4205. if (!stretched) { return old }
  4206. for (var i = 0; i < old.length; ++i) {
  4207. var oldCur = old[i], stretchCur = stretched[i]
  4208. if (oldCur && stretchCur) {
  4209. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4210. var span = stretchCur[j]
  4211. for (var k = 0; k < oldCur.length; ++k)
  4212. { if (oldCur[k].marker == span.marker) { continue spans } }
  4213. oldCur.push(span)
  4214. }
  4215. } else if (stretchCur) {
  4216. old[i] = stretchCur
  4217. }
  4218. }
  4219. return old
  4220. }
  4221. // Used both to provide a JSON-safe object in .getHistory, and, when
  4222. // detaching a document, to split the history in two
  4223. function copyHistoryArray(events, newGroup, instantiateSel) {
  4224. var copy = []
  4225. for (var i = 0; i < events.length; ++i) {
  4226. var event = events[i]
  4227. if (event.ranges) {
  4228. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  4229. continue
  4230. }
  4231. var changes = event.changes, newChanges = []
  4232. copy.push({changes: newChanges})
  4233. for (var j = 0; j < changes.length; ++j) {
  4234. var change = changes[j], m = void 0
  4235. newChanges.push({from: change.from, to: change.to, text: change.text})
  4236. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4237. if (indexOf(newGroup, Number(m[1])) > -1) {
  4238. lst(newChanges)[prop] = change[prop]
  4239. delete change[prop]
  4240. }
  4241. } } }
  4242. }
  4243. }
  4244. return copy
  4245. }
  4246. // The 'scroll' parameter given to many of these indicated whether
  4247. // the new cursor position should be scrolled into view after
  4248. // modifying the selection.
  4249. // If shift is held or the extend flag is set, extends a range to
  4250. // include a given position (and optionally a second position).
  4251. // Otherwise, simply returns the range between the given positions.
  4252. // Used for cursor motion and such.
  4253. function extendRange(doc, range, head, other) {
  4254. if (doc.cm && doc.cm.display.shift || doc.extend) {
  4255. var anchor = range.anchor
  4256. if (other) {
  4257. var posBefore = cmp(head, anchor) < 0
  4258. if (posBefore != (cmp(other, anchor) < 0)) {
  4259. anchor = head
  4260. head = other
  4261. } else if (posBefore != (cmp(head, other) < 0)) {
  4262. head = other
  4263. }
  4264. }
  4265. return new Range(anchor, head)
  4266. } else {
  4267. return new Range(other || head, head)
  4268. }
  4269. }
  4270. // Extend the primary selection range, discard the rest.
  4271. function extendSelection(doc, head, other, options) {
  4272. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options)
  4273. }
  4274. // Extend all selections (pos is an array of selections with length
  4275. // equal the number of selections)
  4276. function extendSelections(doc, heads, options) {
  4277. var out = []
  4278. for (var i = 0; i < doc.sel.ranges.length; i++)
  4279. { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null) }
  4280. var newSel = normalizeSelection(out, doc.sel.primIndex)
  4281. setSelection(doc, newSel, options)
  4282. }
  4283. // Updates a single range in the selection.
  4284. function replaceOneSelection(doc, i, range, options) {
  4285. var ranges = doc.sel.ranges.slice(0)
  4286. ranges[i] = range
  4287. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
  4288. }
  4289. // Reset the selection to a single range.
  4290. function setSimpleSelection(doc, anchor, head, options) {
  4291. setSelection(doc, simpleSelection(anchor, head), options)
  4292. }
  4293. // Give beforeSelectionChange handlers a change to influence a
  4294. // selection update.
  4295. function filterSelectionChange(doc, sel, options) {
  4296. var obj = {
  4297. ranges: sel.ranges,
  4298. update: function(ranges) {
  4299. var this$1 = this;
  4300. this.ranges = []
  4301. for (var i = 0; i < ranges.length; i++)
  4302. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4303. clipPos(doc, ranges[i].head)) }
  4304. },
  4305. origin: options && options.origin
  4306. }
  4307. signal(doc, "beforeSelectionChange", doc, obj)
  4308. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
  4309. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4310. else { return sel }
  4311. }
  4312. function setSelectionReplaceHistory(doc, sel, options) {
  4313. var done = doc.history.done, last = lst(done)
  4314. if (last && last.ranges) {
  4315. done[done.length - 1] = sel
  4316. setSelectionNoUndo(doc, sel, options)
  4317. } else {
  4318. setSelection(doc, sel, options)
  4319. }
  4320. }
  4321. // Set a new selection.
  4322. function setSelection(doc, sel, options) {
  4323. setSelectionNoUndo(doc, sel, options)
  4324. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  4325. }
  4326. function setSelectionNoUndo(doc, sel, options) {
  4327. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4328. { sel = filterSelectionChange(doc, sel, options) }
  4329. var bias = options && options.bias ||
  4330. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  4331. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  4332. if (!(options && options.scroll === false) && doc.cm)
  4333. { ensureCursorVisible(doc.cm) }
  4334. }
  4335. function setSelectionInner(doc, sel) {
  4336. if (sel.equals(doc.sel)) { return }
  4337. doc.sel = sel
  4338. if (doc.cm) {
  4339. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
  4340. signalCursorActivity(doc.cm)
  4341. }
  4342. signalLater(doc, "cursorActivity", doc)
  4343. }
  4344. // Verify that the selection does not partially select any atomic
  4345. // marked ranges.
  4346. function reCheckSelection(doc) {
  4347. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll)
  4348. }
  4349. // Return a selection that does not partially select any atomic
  4350. // ranges.
  4351. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4352. var out
  4353. for (var i = 0; i < sel.ranges.length; i++) {
  4354. var range = sel.ranges[i]
  4355. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  4356. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  4357. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  4358. if (out || newAnchor != range.anchor || newHead != range.head) {
  4359. if (!out) { out = sel.ranges.slice(0, i) }
  4360. out[i] = new Range(newAnchor, newHead)
  4361. }
  4362. }
  4363. return out ? normalizeSelection(out, sel.primIndex) : sel
  4364. }
  4365. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4366. var line = getLine(doc, pos.line)
  4367. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4368. var sp = line.markedSpans[i], m = sp.marker
  4369. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4370. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4371. if (mayClear) {
  4372. signal(m, "beforeCursorEnter")
  4373. if (m.explicitlyCleared) {
  4374. if (!line.markedSpans) { break }
  4375. else {--i; continue}
  4376. }
  4377. }
  4378. if (!m.atomic) { continue }
  4379. if (oldPos) {
  4380. var near = m.find(dir < 0 ? 1 : -1), diff = void 0
  4381. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4382. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
  4383. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4384. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4385. }
  4386. var far = m.find(dir < 0 ? -1 : 1)
  4387. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4388. { far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
  4389. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4390. }
  4391. } }
  4392. return pos
  4393. }
  4394. // Ensure a given position is not inside an atomic range.
  4395. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4396. var dir = bias || 1
  4397. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4398. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4399. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4400. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  4401. if (!found) {
  4402. doc.cantEdit = true
  4403. return Pos(doc.first, 0)
  4404. }
  4405. return found
  4406. }
  4407. function movePos(doc, pos, dir, line) {
  4408. if (dir < 0 && pos.ch == 0) {
  4409. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4410. else { return null }
  4411. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4412. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4413. else { return null }
  4414. } else {
  4415. return new Pos(pos.line, pos.ch + dir)
  4416. }
  4417. }
  4418. function selectAll(cm) {
  4419. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  4420. }
  4421. // UPDATING
  4422. // Allow "beforeChange" event handlers to influence a change
  4423. function filterChange(doc, change, update) {
  4424. var obj = {
  4425. canceled: false,
  4426. from: change.from,
  4427. to: change.to,
  4428. text: change.text,
  4429. origin: change.origin,
  4430. cancel: function () { return obj.canceled = true; }
  4431. }
  4432. if (update) { obj.update = function (from, to, text, origin) {
  4433. if (from) { obj.from = clipPos(doc, from) }
  4434. if (to) { obj.to = clipPos(doc, to) }
  4435. if (text) { obj.text = text }
  4436. if (origin !== undefined) { obj.origin = origin }
  4437. } }
  4438. signal(doc, "beforeChange", doc, obj)
  4439. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
  4440. if (obj.canceled) { return null }
  4441. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4442. }
  4443. // Apply a change to a document, and add it to the document's
  4444. // history, and propagating it to all linked documents.
  4445. function makeChange(doc, change, ignoreReadOnly) {
  4446. if (doc.cm) {
  4447. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4448. if (doc.cm.state.suppressEdits) { return }
  4449. }
  4450. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4451. change = filterChange(doc, change, true)
  4452. if (!change) { return }
  4453. }
  4454. // Possibly split or suppress the update based on the presence
  4455. // of read-only spans in its range.
  4456. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  4457. if (split) {
  4458. for (var i = split.length - 1; i >= 0; --i)
  4459. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}) }
  4460. } else {
  4461. makeChangeInner(doc, change)
  4462. }
  4463. }
  4464. function makeChangeInner(doc, change) {
  4465. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4466. var selAfter = computeSelAfterChange(doc, change)
  4467. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  4468. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  4469. var rebased = []
  4470. linkedDocs(doc, function (doc, sharedHist) {
  4471. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4472. rebaseHist(doc.history, change)
  4473. rebased.push(doc.history)
  4474. }
  4475. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  4476. })
  4477. }
  4478. // Revert a change stored in a document's history.
  4479. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4480. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  4481. var hist = doc.history, event, selAfter = doc.sel
  4482. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
  4483. // Verify that there is a useable event (so that ctrl-z won't
  4484. // needlessly clear selection events)
  4485. var i = 0
  4486. for (; i < source.length; i++) {
  4487. event = source[i]
  4488. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4489. { break }
  4490. }
  4491. if (i == source.length) { return }
  4492. hist.lastOrigin = hist.lastSelOrigin = null
  4493. for (;;) {
  4494. event = source.pop()
  4495. if (event.ranges) {
  4496. pushSelectionToHistory(event, dest)
  4497. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4498. setSelection(doc, event, {clearRedo: false})
  4499. return
  4500. }
  4501. selAfter = event
  4502. }
  4503. else { break }
  4504. }
  4505. // Build up a reverse change object to add to the opposite history
  4506. // stack (redo when undoing, and vice versa).
  4507. var antiChanges = []
  4508. pushSelectionToHistory(selAfter, dest)
  4509. dest.push({changes: antiChanges, generation: hist.generation})
  4510. hist.generation = event.generation || ++hist.maxGeneration
  4511. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
  4512. var loop = function ( i ) {
  4513. var change = event.changes[i]
  4514. change.origin = type
  4515. if (filter && !filterChange(doc, change, false)) {
  4516. source.length = 0
  4517. return {}
  4518. }
  4519. antiChanges.push(historyChangeFromChange(doc, change))
  4520. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  4521. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  4522. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
  4523. var rebased = []
  4524. // Propagate to the linked documents
  4525. linkedDocs(doc, function (doc, sharedHist) {
  4526. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4527. rebaseHist(doc.history, change)
  4528. rebased.push(doc.history)
  4529. }
  4530. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  4531. })
  4532. };
  4533. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4534. var returned = loop( i$1 );
  4535. if ( returned ) return returned.v;
  4536. }
  4537. }
  4538. // Sub-views need their line numbers shifted when text is added
  4539. // above or below them in the parent document.
  4540. function shiftDoc(doc, distance) {
  4541. if (distance == 0) { return }
  4542. doc.first += distance
  4543. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4544. Pos(range.anchor.line + distance, range.anchor.ch),
  4545. Pos(range.head.line + distance, range.head.ch)
  4546. ); }), doc.sel.primIndex)
  4547. if (doc.cm) {
  4548. regChange(doc.cm, doc.first, doc.first - distance, distance)
  4549. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4550. { regLineChange(doc.cm, l, "gutter") }
  4551. }
  4552. }
  4553. // More lower-level change function, handling only a single document
  4554. // (not linked ones).
  4555. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4556. if (doc.cm && !doc.cm.curOp)
  4557. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4558. if (change.to.line < doc.first) {
  4559. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  4560. return
  4561. }
  4562. if (change.from.line > doc.lastLine()) { return }
  4563. // Clip the change to the size of this doc
  4564. if (change.from.line < doc.first) {
  4565. var shift = change.text.length - 1 - (doc.first - change.from.line)
  4566. shiftDoc(doc, shift)
  4567. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4568. text: [lst(change.text)], origin: change.origin}
  4569. }
  4570. var last = doc.lastLine()
  4571. if (change.to.line > last) {
  4572. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4573. text: [change.text[0]], origin: change.origin}
  4574. }
  4575. change.removed = getBetween(doc, change.from, change.to)
  4576. if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
  4577. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
  4578. else { updateDoc(doc, change, spans) }
  4579. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  4580. }
  4581. // Handle the interaction of a change to a document with the editor
  4582. // that this document is part of.
  4583. function makeChangeSingleDocInEditor(cm, change, spans) {
  4584. var doc = cm.doc, display = cm.display, from = change.from, to = change.to
  4585. var recomputeMaxLength = false, checkWidthStart = from.line
  4586. if (!cm.options.lineWrapping) {
  4587. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  4588. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4589. if (line == display.maxLine) {
  4590. recomputeMaxLength = true
  4591. return true
  4592. }
  4593. })
  4594. }
  4595. if (doc.sel.contains(change.from, change.to) > -1)
  4596. { signalCursorActivity(cm) }
  4597. updateDoc(doc, change, spans, estimateHeight(cm))
  4598. if (!cm.options.lineWrapping) {
  4599. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4600. var len = lineLength(line)
  4601. if (len > display.maxLineLength) {
  4602. display.maxLine = line
  4603. display.maxLineLength = len
  4604. display.maxLineChanged = true
  4605. recomputeMaxLength = false
  4606. }
  4607. })
  4608. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
  4609. }
  4610. // Adjust frontier, schedule worker
  4611. doc.frontier = Math.min(doc.frontier, from.line)
  4612. startWorker(cm, 400)
  4613. var lendiff = change.text.length - (to.line - from.line) - 1
  4614. // Remember that these lines changed, for updating the display
  4615. if (change.full)
  4616. { regChange(cm) }
  4617. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4618. { regLineChange(cm, from.line, "text") }
  4619. else
  4620. { regChange(cm, from.line, to.line + 1, lendiff) }
  4621. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
  4622. if (changeHandler || changesHandler) {
  4623. var obj = {
  4624. from: from, to: to,
  4625. text: change.text,
  4626. removed: change.removed,
  4627. origin: change.origin
  4628. }
  4629. if (changeHandler) { signalLater(cm, "change", cm, obj) }
  4630. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
  4631. }
  4632. cm.display.selForContextMenu = null
  4633. }
  4634. function replaceRange(doc, code, from, to, origin) {
  4635. if (!to) { to = from }
  4636. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp }
  4637. if (typeof code == "string") { code = doc.splitLines(code) }
  4638. makeChange(doc, {from: from, to: to, text: code, origin: origin})
  4639. }
  4640. // Rebasing/resetting history to deal with externally-sourced changes
  4641. function rebaseHistSelSingle(pos, from, to, diff) {
  4642. if (to < pos.line) {
  4643. pos.line += diff
  4644. } else if (from < pos.line) {
  4645. pos.line = from
  4646. pos.ch = 0
  4647. }
  4648. }
  4649. // Tries to rebase an array of history events given a change in the
  4650. // document. If the change touches the same lines as the event, the
  4651. // event, and everything 'behind' it, is discarded. If the change is
  4652. // before the event, the event's positions are updated. Uses a
  4653. // copy-on-write scheme for the positions, to avoid having to
  4654. // reallocate them all on every rebase, but also avoid problems with
  4655. // shared position objects being unsafely updated.
  4656. function rebaseHistArray(array, from, to, diff) {
  4657. for (var i = 0; i < array.length; ++i) {
  4658. var sub = array[i], ok = true
  4659. if (sub.ranges) {
  4660. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
  4661. for (var j = 0; j < sub.ranges.length; j++) {
  4662. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  4663. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  4664. }
  4665. continue
  4666. }
  4667. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4668. var cur = sub.changes[j$1]
  4669. if (to < cur.from.line) {
  4670. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  4671. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  4672. } else if (from <= cur.to.line) {
  4673. ok = false
  4674. break
  4675. }
  4676. }
  4677. if (!ok) {
  4678. array.splice(0, i + 1)
  4679. i = 0
  4680. }
  4681. }
  4682. }
  4683. function rebaseHist(hist, change) {
  4684. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
  4685. rebaseHistArray(hist.done, from, to, diff)
  4686. rebaseHistArray(hist.undone, from, to, diff)
  4687. }
  4688. // Utility for applying a change to a line by handle or number,
  4689. // returning the number and optionally registering the line as
  4690. // changed.
  4691. function changeLine(doc, handle, changeType, op) {
  4692. var no = handle, line = handle
  4693. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
  4694. else { no = lineNo(handle) }
  4695. if (no == null) { return null }
  4696. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
  4697. return line
  4698. }
  4699. // The document is represented as a BTree consisting of leaves, with
  4700. // chunk of lines in them, and branches, with up to ten leaves or
  4701. // other branch nodes below them. The top node is always a branch
  4702. // node, and is the document object itself (meaning it has
  4703. // additional methods and properties).
  4704. //
  4705. // All nodes have parent links. The tree is used both to go from
  4706. // line numbers to line objects, and to go from objects to numbers.
  4707. // It also indexes by height, and is used to convert between height
  4708. // and line object, and to find the total height of the document.
  4709. //
  4710. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4711. function LeafChunk(lines) {
  4712. var this$1 = this;
  4713. this.lines = lines
  4714. this.parent = null
  4715. var height = 0
  4716. for (var i = 0; i < lines.length; ++i) {
  4717. lines[i].parent = this$1
  4718. height += lines[i].height
  4719. }
  4720. this.height = height
  4721. }
  4722. LeafChunk.prototype = {
  4723. chunkSize: function() { return this.lines.length },
  4724. // Remove the n lines at offset 'at'.
  4725. removeInner: function(at, n) {
  4726. var this$1 = this;
  4727. for (var i = at, e = at + n; i < e; ++i) {
  4728. var line = this$1.lines[i]
  4729. this$1.height -= line.height
  4730. cleanUpLine(line)
  4731. signalLater(line, "delete")
  4732. }
  4733. this.lines.splice(at, n)
  4734. },
  4735. // Helper used to collapse a small branch into a single leaf.
  4736. collapse: function(lines) {
  4737. lines.push.apply(lines, this.lines)
  4738. },
  4739. // Insert the given array of lines at offset 'at', count them as
  4740. // having the given height.
  4741. insertInner: function(at, lines, height) {
  4742. var this$1 = this;
  4743. this.height += height
  4744. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  4745. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
  4746. },
  4747. // Used to iterate over a part of the tree.
  4748. iterN: function(at, n, op) {
  4749. var this$1 = this;
  4750. for (var e = at + n; at < e; ++at)
  4751. { if (op(this$1.lines[at])) { return true } }
  4752. }
  4753. }
  4754. function BranchChunk(children) {
  4755. var this$1 = this;
  4756. this.children = children
  4757. var size = 0, height = 0
  4758. for (var i = 0; i < children.length; ++i) {
  4759. var ch = children[i]
  4760. size += ch.chunkSize(); height += ch.height
  4761. ch.parent = this$1
  4762. }
  4763. this.size = size
  4764. this.height = height
  4765. this.parent = null
  4766. }
  4767. BranchChunk.prototype = {
  4768. chunkSize: function() { return this.size },
  4769. removeInner: function(at, n) {
  4770. var this$1 = this;
  4771. this.size -= n
  4772. for (var i = 0; i < this.children.length; ++i) {
  4773. var child = this$1.children[i], sz = child.chunkSize()
  4774. if (at < sz) {
  4775. var rm = Math.min(n, sz - at), oldHeight = child.height
  4776. child.removeInner(at, rm)
  4777. this$1.height -= oldHeight - child.height
  4778. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
  4779. if ((n -= rm) == 0) { break }
  4780. at = 0
  4781. } else { at -= sz }
  4782. }
  4783. // If the result is smaller than 25 lines, ensure that it is a
  4784. // single leaf node.
  4785. if (this.size - n < 25 &&
  4786. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  4787. var lines = []
  4788. this.collapse(lines)
  4789. this.children = [new LeafChunk(lines)]
  4790. this.children[0].parent = this
  4791. }
  4792. },
  4793. collapse: function(lines) {
  4794. var this$1 = this;
  4795. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
  4796. },
  4797. insertInner: function(at, lines, height) {
  4798. var this$1 = this;
  4799. this.size += lines.length
  4800. this.height += height
  4801. for (var i = 0; i < this.children.length; ++i) {
  4802. var child = this$1.children[i], sz = child.chunkSize()
  4803. if (at <= sz) {
  4804. child.insertInner(at, lines, height)
  4805. if (child.lines && child.lines.length > 50) {
  4806. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  4807. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  4808. var remaining = child.lines.length % 25 + 25
  4809. for (var pos = remaining; pos < child.lines.length;) {
  4810. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
  4811. child.height -= leaf.height
  4812. this$1.children.splice(++i, 0, leaf)
  4813. leaf.parent = this$1
  4814. }
  4815. child.lines = child.lines.slice(0, remaining)
  4816. this$1.maybeSpill()
  4817. }
  4818. break
  4819. }
  4820. at -= sz
  4821. }
  4822. },
  4823. // When a node has grown, check whether it should be split.
  4824. maybeSpill: function() {
  4825. if (this.children.length <= 10) { return }
  4826. var me = this
  4827. do {
  4828. var spilled = me.children.splice(me.children.length - 5, 5)
  4829. var sibling = new BranchChunk(spilled)
  4830. if (!me.parent) { // Become the parent node
  4831. var copy = new BranchChunk(me.children)
  4832. copy.parent = me
  4833. me.children = [copy, sibling]
  4834. me = copy
  4835. } else {
  4836. me.size -= sibling.size
  4837. me.height -= sibling.height
  4838. var myIndex = indexOf(me.parent.children, me)
  4839. me.parent.children.splice(myIndex + 1, 0, sibling)
  4840. }
  4841. sibling.parent = me.parent
  4842. } while (me.children.length > 10)
  4843. me.parent.maybeSpill()
  4844. },
  4845. iterN: function(at, n, op) {
  4846. var this$1 = this;
  4847. for (var i = 0; i < this.children.length; ++i) {
  4848. var child = this$1.children[i], sz = child.chunkSize()
  4849. if (at < sz) {
  4850. var used = Math.min(n, sz - at)
  4851. if (child.iterN(at, used, op)) { return true }
  4852. if ((n -= used) == 0) { break }
  4853. at = 0
  4854. } else { at -= sz }
  4855. }
  4856. }
  4857. }
  4858. // Line widgets are block elements displayed above or below a line.
  4859. function LineWidget(doc, node, options) {
  4860. var this$1 = this;
  4861. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  4862. { this$1[opt] = options[opt] } } }
  4863. this.doc = doc
  4864. this.node = node
  4865. }
  4866. eventMixin(LineWidget)
  4867. function adjustScrollWhenAboveVisible(cm, line, diff) {
  4868. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  4869. { addToScrollPos(cm, null, diff) }
  4870. }
  4871. LineWidget.prototype.clear = function() {
  4872. var this$1 = this;
  4873. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  4874. if (no == null || !ws) { return }
  4875. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
  4876. if (!ws.length) { line.widgets = null }
  4877. var height = widgetHeight(this)
  4878. updateLineHeight(line, Math.max(0, line.height - height))
  4879. if (cm) { runInOp(cm, function () {
  4880. adjustScrollWhenAboveVisible(cm, line, -height)
  4881. regLineChange(cm, no, "widget")
  4882. }) }
  4883. }
  4884. LineWidget.prototype.changed = function() {
  4885. var oldH = this.height, cm = this.doc.cm, line = this.line
  4886. this.height = null
  4887. var diff = widgetHeight(this) - oldH
  4888. if (!diff) { return }
  4889. updateLineHeight(line, line.height + diff)
  4890. if (cm) { runInOp(cm, function () {
  4891. cm.curOp.forceUpdate = true
  4892. adjustScrollWhenAboveVisible(cm, line, diff)
  4893. }) }
  4894. }
  4895. function addLineWidget(doc, handle, node, options) {
  4896. var widget = new LineWidget(doc, node, options)
  4897. var cm = doc.cm
  4898. if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
  4899. changeLine(doc, handle, "widget", function (line) {
  4900. var widgets = line.widgets || (line.widgets = [])
  4901. if (widget.insertAt == null) { widgets.push(widget) }
  4902. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
  4903. widget.line = line
  4904. if (cm && !lineIsHidden(doc, line)) {
  4905. var aboveVisible = heightAtLine(line) < doc.scrollTop
  4906. updateLineHeight(line, line.height + widgetHeight(widget))
  4907. if (aboveVisible) { addToScrollPos(cm, null, widget.height) }
  4908. cm.curOp.forceUpdate = true
  4909. }
  4910. return true
  4911. })
  4912. return widget
  4913. }
  4914. // TEXTMARKERS
  4915. // Created with markText and setBookmark methods. A TextMarker is a
  4916. // handle that can be used to clear or find a marked position in the
  4917. // document. Line objects hold arrays (markedSpans) containing
  4918. // {from, to, marker} object pointing to such marker objects, and
  4919. // indicating that such a marker is present on that line. Multiple
  4920. // lines may point to the same marker when it spans across lines.
  4921. // The spans will have null for their from/to properties when the
  4922. // marker continues beyond the start/end of the line. Markers have
  4923. // links back to the lines they currently touch.
  4924. // Collapsed markers have unique ids, in order to be able to order
  4925. // them, which is needed for uniquely determining an outer marker
  4926. // when they overlap (they may nest, but not partially overlap).
  4927. var nextMarkerId = 0
  4928. function TextMarker(doc, type) {
  4929. this.lines = []
  4930. this.type = type
  4931. this.doc = doc
  4932. this.id = ++nextMarkerId
  4933. }
  4934. eventMixin(TextMarker)
  4935. // Clear the marker.
  4936. TextMarker.prototype.clear = function() {
  4937. var this$1 = this;
  4938. if (this.explicitlyCleared) { return }
  4939. var cm = this.doc.cm, withOp = cm && !cm.curOp
  4940. if (withOp) { startOperation(cm) }
  4941. if (hasHandler(this, "clear")) {
  4942. var found = this.find()
  4943. if (found) { signalLater(this, "clear", found.from, found.to) }
  4944. }
  4945. var min = null, max = null
  4946. for (var i = 0; i < this.lines.length; ++i) {
  4947. var line = this$1.lines[i]
  4948. var span = getMarkedSpanFor(line.markedSpans, this$1)
  4949. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
  4950. else if (cm) {
  4951. if (span.to != null) { max = lineNo(line) }
  4952. if (span.from != null) { min = lineNo(line) }
  4953. }
  4954. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  4955. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  4956. { updateLineHeight(line, textHeight(cm.display)) }
  4957. }
  4958. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  4959. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
  4960. if (len > cm.display.maxLineLength) {
  4961. cm.display.maxLine = visual
  4962. cm.display.maxLineLength = len
  4963. cm.display.maxLineChanged = true
  4964. }
  4965. } }
  4966. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
  4967. this.lines.length = 0
  4968. this.explicitlyCleared = true
  4969. if (this.atomic && this.doc.cantEdit) {
  4970. this.doc.cantEdit = false
  4971. if (cm) { reCheckSelection(cm.doc) }
  4972. }
  4973. if (cm) { signalLater(cm, "markerCleared", cm, this) }
  4974. if (withOp) { endOperation(cm) }
  4975. if (this.parent) { this.parent.clear() }
  4976. }
  4977. // Find the position of the marker in the document. Returns a {from,
  4978. // to} object by default. Side can be passed to get a specific side
  4979. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  4980. // Pos objects returned contain a line object, rather than a line
  4981. // number (used to prevent looking up the same line twice).
  4982. TextMarker.prototype.find = function(side, lineObj) {
  4983. var this$1 = this;
  4984. if (side == null && this.type == "bookmark") { side = 1 }
  4985. var from, to
  4986. for (var i = 0; i < this.lines.length; ++i) {
  4987. var line = this$1.lines[i]
  4988. var span = getMarkedSpanFor(line.markedSpans, this$1)
  4989. if (span.from != null) {
  4990. from = Pos(lineObj ? line : lineNo(line), span.from)
  4991. if (side == -1) { return from }
  4992. }
  4993. if (span.to != null) {
  4994. to = Pos(lineObj ? line : lineNo(line), span.to)
  4995. if (side == 1) { return to }
  4996. }
  4997. }
  4998. return from && {from: from, to: to}
  4999. }
  5000. // Signals that the marker's widget changed, and surrounding layout
  5001. // should be recomputed.
  5002. TextMarker.prototype.changed = function() {
  5003. var pos = this.find(-1, true), widget = this, cm = this.doc.cm
  5004. if (!pos || !cm) { return }
  5005. runInOp(cm, function () {
  5006. var line = pos.line, lineN = lineNo(pos.line)
  5007. var view = findViewForLine(cm, lineN)
  5008. if (view) {
  5009. clearLineMeasurementCacheFor(view)
  5010. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  5011. }
  5012. cm.curOp.updateMaxLine = true
  5013. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5014. var oldHeight = widget.height
  5015. widget.height = null
  5016. var dHeight = widgetHeight(widget) - oldHeight
  5017. if (dHeight)
  5018. { updateLineHeight(line, line.height + dHeight) }
  5019. }
  5020. })
  5021. }
  5022. TextMarker.prototype.attachLine = function(line) {
  5023. if (!this.lines.length && this.doc.cm) {
  5024. var op = this.doc.cm.curOp
  5025. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5026. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
  5027. }
  5028. this.lines.push(line)
  5029. }
  5030. TextMarker.prototype.detachLine = function(line) {
  5031. this.lines.splice(indexOf(this.lines, line), 1)
  5032. if (!this.lines.length && this.doc.cm) {
  5033. var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  5034. }
  5035. }
  5036. // Create a marker, wire it up to the right lines, and
  5037. function markText(doc, from, to, options, type) {
  5038. // Shared markers (across linked documents) are handled separately
  5039. // (markTextShared will call out to this again, once per
  5040. // document).
  5041. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5042. // Ensure we are in an operation.
  5043. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5044. var marker = new TextMarker(doc, type), diff = cmp(from, to)
  5045. if (options) { copyObj(options, marker, false) }
  5046. // Don't connect empty markers unless clearWhenEmpty is false
  5047. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5048. { return marker }
  5049. if (marker.replacedWith) {
  5050. // Showing up as a widget implies collapsed (widget replaces text)
  5051. marker.collapsed = true
  5052. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget")
  5053. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
  5054. if (options.insertLeft) { marker.widgetNode.insertLeft = true }
  5055. }
  5056. if (marker.collapsed) {
  5057. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5058. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5059. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5060. seeCollapsedSpans()
  5061. }
  5062. if (marker.addToHistory)
  5063. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
  5064. var curLine = from.line, cm = doc.cm, updateMaxLine
  5065. doc.iter(curLine, to.line + 1, function (line) {
  5066. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5067. { updateMaxLine = true }
  5068. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
  5069. addMarkedSpan(line, new MarkedSpan(marker,
  5070. curLine == from.line ? from.ch : null,
  5071. curLine == to.line ? to.ch : null))
  5072. ++curLine
  5073. })
  5074. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5075. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5076. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
  5077. }) }
  5078. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
  5079. if (marker.readOnly) {
  5080. seeReadOnlySpans()
  5081. if (doc.history.done.length || doc.history.undone.length)
  5082. { doc.clearHistory() }
  5083. }
  5084. if (marker.collapsed) {
  5085. marker.id = ++nextMarkerId
  5086. marker.atomic = true
  5087. }
  5088. if (cm) {
  5089. // Sync editor state
  5090. if (updateMaxLine) { cm.curOp.updateMaxLine = true }
  5091. if (marker.collapsed)
  5092. { regChange(cm, from.line, to.line + 1) }
  5093. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5094. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
  5095. if (marker.atomic) { reCheckSelection(cm.doc) }
  5096. signalLater(cm, "markerAdded", cm, marker)
  5097. }
  5098. return marker
  5099. }
  5100. // SHARED TEXTMARKERS
  5101. // A shared marker spans multiple linked documents. It is
  5102. // implemented as a meta-marker-object controlling multiple normal
  5103. // markers.
  5104. function SharedTextMarker(markers, primary) {
  5105. var this$1 = this;
  5106. this.markers = markers
  5107. this.primary = primary
  5108. for (var i = 0; i < markers.length; ++i)
  5109. { markers[i].parent = this$1 }
  5110. }
  5111. eventMixin(SharedTextMarker)
  5112. SharedTextMarker.prototype.clear = function() {
  5113. var this$1 = this;
  5114. if (this.explicitlyCleared) { return }
  5115. this.explicitlyCleared = true
  5116. for (var i = 0; i < this.markers.length; ++i)
  5117. { this$1.markers[i].clear() }
  5118. signalLater(this, "clear")
  5119. }
  5120. SharedTextMarker.prototype.find = function(side, lineObj) {
  5121. return this.primary.find(side, lineObj)
  5122. }
  5123. function markTextShared(doc, from, to, options, type) {
  5124. options = copyObj(options)
  5125. options.shared = false
  5126. var markers = [markText(doc, from, to, options, type)], primary = markers[0]
  5127. var widget = options.widgetNode
  5128. linkedDocs(doc, function (doc) {
  5129. if (widget) { options.widgetNode = widget.cloneNode(true) }
  5130. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  5131. for (var i = 0; i < doc.linked.length; ++i)
  5132. { if (doc.linked[i].isParent) { return } }
  5133. primary = lst(markers)
  5134. })
  5135. return new SharedTextMarker(markers, primary)
  5136. }
  5137. function findSharedMarkers(doc) {
  5138. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5139. }
  5140. function copySharedMarkers(doc, markers) {
  5141. for (var i = 0; i < markers.length; i++) {
  5142. var marker = markers[i], pos = marker.find()
  5143. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
  5144. if (cmp(mFrom, mTo)) {
  5145. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  5146. marker.markers.push(subMark)
  5147. subMark.parent = marker
  5148. }
  5149. }
  5150. }
  5151. function detachSharedMarkers(markers) {
  5152. var loop = function ( i ) {
  5153. var marker = markers[i], linked = [marker.primary.doc]
  5154. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
  5155. for (var j = 0; j < marker.markers.length; j++) {
  5156. var subMarker = marker.markers[j]
  5157. if (indexOf(linked, subMarker.doc) == -1) {
  5158. subMarker.parent = null
  5159. marker.markers.splice(j--, 1)
  5160. }
  5161. }
  5162. };
  5163. for (var i = 0; i < markers.length; i++) loop( i );
  5164. }
  5165. var nextDocId = 0
  5166. var Doc = function(text, mode, firstLine, lineSep) {
  5167. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep) }
  5168. if (firstLine == null) { firstLine = 0 }
  5169. BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  5170. this.first = firstLine
  5171. this.scrollTop = this.scrollLeft = 0
  5172. this.cantEdit = false
  5173. this.cleanGeneration = 1
  5174. this.frontier = firstLine
  5175. var start = Pos(firstLine, 0)
  5176. this.sel = simpleSelection(start)
  5177. this.history = new History(null)
  5178. this.id = ++nextDocId
  5179. this.modeOption = mode
  5180. this.lineSep = lineSep
  5181. this.extend = false
  5182. if (typeof text == "string") { text = this.splitLines(text) }
  5183. updateDoc(this, {from: start, to: start, text: text})
  5184. setSelection(this, simpleSelection(start), sel_dontScroll)
  5185. }
  5186. Doc.prototype = createObj(BranchChunk.prototype, {
  5187. constructor: Doc,
  5188. // Iterate over the document. Supports two forms -- with only one
  5189. // argument, it calls that for each line in the document. With
  5190. // three, it iterates over the range given by the first two (with
  5191. // the second being non-inclusive).
  5192. iter: function(from, to, op) {
  5193. if (op) { this.iterN(from - this.first, to - from, op) }
  5194. else { this.iterN(this.first, this.first + this.size, from) }
  5195. },
  5196. // Non-public interface for adding and removing lines.
  5197. insert: function(at, lines) {
  5198. var height = 0
  5199. for (var i = 0; i < lines.length; ++i) { height += lines[i].height }
  5200. this.insertInner(at - this.first, lines, height)
  5201. },
  5202. remove: function(at, n) { this.removeInner(at - this.first, n) },
  5203. // From here, the methods are part of the public interface. Most
  5204. // are also available from CodeMirror (editor) instances.
  5205. getValue: function(lineSep) {
  5206. var lines = getLines(this, this.first, this.first + this.size)
  5207. if (lineSep === false) { return lines }
  5208. return lines.join(lineSep || this.lineSeparator())
  5209. },
  5210. setValue: docMethodOp(function(code) {
  5211. var top = Pos(this.first, 0), last = this.first + this.size - 1
  5212. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5213. text: this.splitLines(code), origin: "setValue", full: true}, true)
  5214. setSelection(this, simpleSelection(top))
  5215. }),
  5216. replaceRange: function(code, from, to, origin) {
  5217. from = clipPos(this, from)
  5218. to = to ? clipPos(this, to) : from
  5219. replaceRange(this, code, from, to, origin)
  5220. },
  5221. getRange: function(from, to, lineSep) {
  5222. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  5223. if (lineSep === false) { return lines }
  5224. return lines.join(lineSep || this.lineSeparator())
  5225. },
  5226. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5227. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5228. getLineNumber: function(line) {return lineNo(line)},
  5229. getLineHandleVisualStart: function(line) {
  5230. if (typeof line == "number") { line = getLine(this, line) }
  5231. return visualLine(line)
  5232. },
  5233. lineCount: function() {return this.size},
  5234. firstLine: function() {return this.first},
  5235. lastLine: function() {return this.first + this.size - 1},
  5236. clipPos: function(pos) {return clipPos(this, pos)},
  5237. getCursor: function(start) {
  5238. var range$$1 = this.sel.primary(), pos
  5239. if (start == null || start == "head") { pos = range$$1.head }
  5240. else if (start == "anchor") { pos = range$$1.anchor }
  5241. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to() }
  5242. else { pos = range$$1.from() }
  5243. return pos
  5244. },
  5245. listSelections: function() { return this.sel.ranges },
  5246. somethingSelected: function() {return this.sel.somethingSelected()},
  5247. setCursor: docMethodOp(function(line, ch, options) {
  5248. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options)
  5249. }),
  5250. setSelection: docMethodOp(function(anchor, head, options) {
  5251. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  5252. }),
  5253. extendSelection: docMethodOp(function(head, other, options) {
  5254. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  5255. }),
  5256. extendSelections: docMethodOp(function(heads, options) {
  5257. extendSelections(this, clipPosArray(this, heads), options)
  5258. }),
  5259. extendSelectionsBy: docMethodOp(function(f, options) {
  5260. var heads = map(this.sel.ranges, f)
  5261. extendSelections(this, clipPosArray(this, heads), options)
  5262. }),
  5263. setSelections: docMethodOp(function(ranges, primary, options) {
  5264. var this$1 = this;
  5265. if (!ranges.length) { return }
  5266. var out = []
  5267. for (var i = 0; i < ranges.length; i++)
  5268. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5269. clipPos(this$1, ranges[i].head)) }
  5270. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
  5271. setSelection(this, normalizeSelection(out, primary), options)
  5272. }),
  5273. addSelection: docMethodOp(function(anchor, head, options) {
  5274. var ranges = this.sel.ranges.slice(0)
  5275. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  5276. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
  5277. }),
  5278. getSelection: function(lineSep) {
  5279. var this$1 = this;
  5280. var ranges = this.sel.ranges, lines
  5281. for (var i = 0; i < ranges.length; i++) {
  5282. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5283. lines = lines ? lines.concat(sel) : sel
  5284. }
  5285. if (lineSep === false) { return lines }
  5286. else { return lines.join(lineSep || this.lineSeparator()) }
  5287. },
  5288. getSelections: function(lineSep) {
  5289. var this$1 = this;
  5290. var parts = [], ranges = this.sel.ranges
  5291. for (var i = 0; i < ranges.length; i++) {
  5292. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5293. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
  5294. parts[i] = sel
  5295. }
  5296. return parts
  5297. },
  5298. replaceSelection: function(code, collapse, origin) {
  5299. var dup = []
  5300. for (var i = 0; i < this.sel.ranges.length; i++)
  5301. { dup[i] = code }
  5302. this.replaceSelections(dup, collapse, origin || "+input")
  5303. },
  5304. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5305. var this$1 = this;
  5306. var changes = [], sel = this.sel
  5307. for (var i = 0; i < sel.ranges.length; i++) {
  5308. var range$$1 = sel.ranges[i]
  5309. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}
  5310. }
  5311. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
  5312. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5313. { makeChange(this$1, changes[i$1]) }
  5314. if (newSel) { setSelectionReplaceHistory(this, newSel) }
  5315. else if (this.cm) { ensureCursorVisible(this.cm) }
  5316. }),
  5317. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
  5318. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
  5319. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
  5320. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
  5321. setExtending: function(val) {this.extend = val},
  5322. getExtending: function() {return this.extend},
  5323. historySize: function() {
  5324. var hist = this.history, done = 0, undone = 0
  5325. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
  5326. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
  5327. return {undo: done, redo: undone}
  5328. },
  5329. clearHistory: function() {this.history = new History(this.history.maxGeneration)},
  5330. markClean: function() {
  5331. this.cleanGeneration = this.changeGeneration(true)
  5332. },
  5333. changeGeneration: function(forceSplit) {
  5334. if (forceSplit)
  5335. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
  5336. return this.history.generation
  5337. },
  5338. isClean: function (gen) {
  5339. return this.history.generation == (gen || this.cleanGeneration)
  5340. },
  5341. getHistory: function() {
  5342. return {done: copyHistoryArray(this.history.done),
  5343. undone: copyHistoryArray(this.history.undone)}
  5344. },
  5345. setHistory: function(histData) {
  5346. var hist = this.history = new History(this.history.maxGeneration)
  5347. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  5348. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  5349. },
  5350. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5351. return changeLine(this, line, "gutter", function (line) {
  5352. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  5353. markers[gutterID] = value
  5354. if (!value && isEmpty(markers)) { line.gutterMarkers = null }
  5355. return true
  5356. })
  5357. }),
  5358. clearGutter: docMethodOp(function(gutterID) {
  5359. var this$1 = this;
  5360. var i = this.first
  5361. this.iter(function (line) {
  5362. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5363. changeLine(this$1, line, "gutter", function () {
  5364. line.gutterMarkers[gutterID] = null
  5365. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
  5366. return true
  5367. })
  5368. }
  5369. ++i
  5370. })
  5371. }),
  5372. lineInfo: function(line) {
  5373. var n
  5374. if (typeof line == "number") {
  5375. if (!isLine(this, line)) { return null }
  5376. n = line
  5377. line = getLine(this, line)
  5378. if (!line) { return null }
  5379. } else {
  5380. n = lineNo(line)
  5381. if (n == null) { return null }
  5382. }
  5383. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5384. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5385. widgets: line.widgets}
  5386. },
  5387. addLineClass: docMethodOp(function(handle, where, cls) {
  5388. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5389. var prop = where == "text" ? "textClass"
  5390. : where == "background" ? "bgClass"
  5391. : where == "gutter" ? "gutterClass" : "wrapClass"
  5392. if (!line[prop]) { line[prop] = cls }
  5393. else if (classTest(cls).test(line[prop])) { return false }
  5394. else { line[prop] += " " + cls }
  5395. return true
  5396. })
  5397. }),
  5398. removeLineClass: docMethodOp(function(handle, where, cls) {
  5399. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5400. var prop = where == "text" ? "textClass"
  5401. : where == "background" ? "bgClass"
  5402. : where == "gutter" ? "gutterClass" : "wrapClass"
  5403. var cur = line[prop]
  5404. if (!cur) { return false }
  5405. else if (cls == null) { line[prop] = null }
  5406. else {
  5407. var found = cur.match(classTest(cls))
  5408. if (!found) { return false }
  5409. var end = found.index + found[0].length
  5410. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
  5411. }
  5412. return true
  5413. })
  5414. }),
  5415. addLineWidget: docMethodOp(function(handle, node, options) {
  5416. return addLineWidget(this, handle, node, options)
  5417. }),
  5418. removeLineWidget: function(widget) { widget.clear() },
  5419. markText: function(from, to, options) {
  5420. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5421. },
  5422. setBookmark: function(pos, options) {
  5423. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5424. insertLeft: options && options.insertLeft,
  5425. clearWhenEmpty: false, shared: options && options.shared,
  5426. handleMouseEvents: options && options.handleMouseEvents}
  5427. pos = clipPos(this, pos)
  5428. return markText(this, pos, pos, realOpts, "bookmark")
  5429. },
  5430. findMarksAt: function(pos) {
  5431. pos = clipPos(this, pos)
  5432. var markers = [], spans = getLine(this, pos.line).markedSpans
  5433. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5434. var span = spans[i]
  5435. if ((span.from == null || span.from <= pos.ch) &&
  5436. (span.to == null || span.to >= pos.ch))
  5437. { markers.push(span.marker.parent || span.marker) }
  5438. } }
  5439. return markers
  5440. },
  5441. findMarks: function(from, to, filter) {
  5442. from = clipPos(this, from); to = clipPos(this, to)
  5443. var found = [], lineNo$$1 = from.line
  5444. this.iter(from.line, to.line + 1, function (line) {
  5445. var spans = line.markedSpans
  5446. if (spans) { for (var i = 0; i < spans.length; i++) {
  5447. var span = spans[i]
  5448. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  5449. span.from == null && lineNo$$1 != from.line ||
  5450. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  5451. (!filter || filter(span.marker)))
  5452. { found.push(span.marker.parent || span.marker) }
  5453. } }
  5454. ++lineNo$$1
  5455. })
  5456. return found
  5457. },
  5458. getAllMarks: function() {
  5459. var markers = []
  5460. this.iter(function (line) {
  5461. var sps = line.markedSpans
  5462. if (sps) { for (var i = 0; i < sps.length; ++i)
  5463. { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
  5464. })
  5465. return markers
  5466. },
  5467. posFromIndex: function(off) {
  5468. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length
  5469. this.iter(function (line) {
  5470. var sz = line.text.length + sepSize
  5471. if (sz > off) { ch = off; return true }
  5472. off -= sz
  5473. ++lineNo$$1
  5474. })
  5475. return clipPos(this, Pos(lineNo$$1, ch))
  5476. },
  5477. indexFromPos: function (coords) {
  5478. coords = clipPos(this, coords)
  5479. var index = coords.ch
  5480. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5481. var sepSize = this.lineSeparator().length
  5482. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5483. index += line.text.length + sepSize
  5484. })
  5485. return index
  5486. },
  5487. copy: function(copyHistory) {
  5488. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5489. this.modeOption, this.first, this.lineSep)
  5490. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
  5491. doc.sel = this.sel
  5492. doc.extend = false
  5493. if (copyHistory) {
  5494. doc.history.undoDepth = this.history.undoDepth
  5495. doc.setHistory(this.getHistory())
  5496. }
  5497. return doc
  5498. },
  5499. linkedDoc: function(options) {
  5500. if (!options) { options = {} }
  5501. var from = this.first, to = this.first + this.size
  5502. if (options.from != null && options.from > from) { from = options.from }
  5503. if (options.to != null && options.to < to) { to = options.to }
  5504. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep)
  5505. if (options.sharedHist) { copy.history = this.history
  5506. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
  5507. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
  5508. copySharedMarkers(copy, findSharedMarkers(this))
  5509. return copy
  5510. },
  5511. unlinkDoc: function(other) {
  5512. var this$1 = this;
  5513. if (other instanceof CodeMirror$1) { other = other.doc }
  5514. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5515. var link = this$1.linked[i]
  5516. if (link.doc != other) { continue }
  5517. this$1.linked.splice(i, 1)
  5518. other.unlinkDoc(this$1)
  5519. detachSharedMarkers(findSharedMarkers(this$1))
  5520. break
  5521. } }
  5522. // If the histories were shared, split them again
  5523. if (other.history == this.history) {
  5524. var splitIds = [other.id]
  5525. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
  5526. other.history = new History(null)
  5527. other.history.done = copyHistoryArray(this.history.done, splitIds)
  5528. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  5529. }
  5530. },
  5531. iterLinkedDocs: function(f) {linkedDocs(this, f)},
  5532. getMode: function() {return this.mode},
  5533. getEditor: function() {return this.cm},
  5534. splitLines: function(str) {
  5535. if (this.lineSep) { return str.split(this.lineSep) }
  5536. return splitLinesAuto(str)
  5537. },
  5538. lineSeparator: function() { return this.lineSep || "\n" }
  5539. })
  5540. // Public alias.
  5541. Doc.prototype.eachLine = Doc.prototype.iter
  5542. // Kludge to work around strange IE behavior where it'll sometimes
  5543. // re-fire a series of drag-related events right after the drop (#1551)
  5544. var lastDrop = 0
  5545. function onDrop(e) {
  5546. var cm = this
  5547. clearDragCursor(cm)
  5548. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5549. { return }
  5550. e_preventDefault(e)
  5551. if (ie) { lastDrop = +new Date }
  5552. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
  5553. if (!pos || cm.isReadOnly()) { return }
  5554. // Might be a file drop, in which case we simply extract the text
  5555. // and insert it.
  5556. if (files && files.length && window.FileReader && window.File) {
  5557. var n = files.length, text = Array(n), read = 0
  5558. var loadFile = function (file, i) {
  5559. if (cm.options.allowDropFileTypes &&
  5560. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5561. { return }
  5562. var reader = new FileReader
  5563. reader.onload = operation(cm, function () {
  5564. var content = reader.result
  5565. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
  5566. text[i] = content
  5567. if (++read == n) {
  5568. pos = clipPos(cm.doc, pos)
  5569. var change = {from: pos, to: pos,
  5570. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5571. origin: "paste"}
  5572. makeChange(cm.doc, change)
  5573. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
  5574. }
  5575. })
  5576. reader.readAsText(file)
  5577. }
  5578. for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
  5579. } else { // Normal drop
  5580. // Don't do a replace if the drop happened inside of the selected text.
  5581. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5582. cm.state.draggingText(e)
  5583. // Ensure the editor is re-focused
  5584. setTimeout(function () { return cm.display.input.focus(); }, 20)
  5585. return
  5586. }
  5587. try {
  5588. var text$1 = e.dataTransfer.getData("Text")
  5589. if (text$1) {
  5590. var selected
  5591. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5592. { selected = cm.listSelections() }
  5593. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  5594. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5595. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
  5596. cm.replaceSelection(text$1, "around", "paste")
  5597. cm.display.input.focus()
  5598. }
  5599. }
  5600. catch(e){}
  5601. }
  5602. }
  5603. function onDragStart(cm, e) {
  5604. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5605. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5606. e.dataTransfer.setData("Text", cm.getSelection())
  5607. e.dataTransfer.effectAllowed = "copyMove"
  5608. // Use dummy image instead of default browsers image.
  5609. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5610. if (e.dataTransfer.setDragImage && !safari) {
  5611. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
  5612. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  5613. if (presto) {
  5614. img.width = img.height = 1
  5615. cm.display.wrapper.appendChild(img)
  5616. // Force a relayout, or Opera won't use our image for some obscure reason
  5617. img._top = img.offsetTop
  5618. }
  5619. e.dataTransfer.setDragImage(img, 0, 0)
  5620. if (presto) { img.parentNode.removeChild(img) }
  5621. }
  5622. }
  5623. function onDragOver(cm, e) {
  5624. var pos = posFromMouse(cm, e)
  5625. if (!pos) { return }
  5626. var frag = document.createDocumentFragment()
  5627. drawSelectionCursor(cm, pos, frag)
  5628. if (!cm.display.dragCursor) {
  5629. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
  5630. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  5631. }
  5632. removeChildrenAndAdd(cm.display.dragCursor, frag)
  5633. }
  5634. function clearDragCursor(cm) {
  5635. if (cm.display.dragCursor) {
  5636. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  5637. cm.display.dragCursor = null
  5638. }
  5639. }
  5640. // These must be handled carefully, because naively registering a
  5641. // handler for each editor will cause the editors to never be
  5642. // garbage collected.
  5643. function forEachCodeMirror(f) {
  5644. if (!document.body.getElementsByClassName) { return }
  5645. var byClass = document.body.getElementsByClassName("CodeMirror")
  5646. for (var i = 0; i < byClass.length; i++) {
  5647. var cm = byClass[i].CodeMirror
  5648. if (cm) { f(cm) }
  5649. }
  5650. }
  5651. var globalsRegistered = false
  5652. function ensureGlobalHandlers() {
  5653. if (globalsRegistered) { return }
  5654. registerGlobalHandlers()
  5655. globalsRegistered = true
  5656. }
  5657. function registerGlobalHandlers() {
  5658. // When the window resizes, we need to refresh active editors.
  5659. var resizeTimer
  5660. on(window, "resize", function () {
  5661. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5662. resizeTimer = null
  5663. forEachCodeMirror(onResize)
  5664. }, 100) }
  5665. })
  5666. // When the window loses focus, we want to show the editor as blurred
  5667. on(window, "blur", function () { return forEachCodeMirror(onBlur); })
  5668. }
  5669. // Called when the window resizes
  5670. function onResize(cm) {
  5671. var d = cm.display
  5672. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5673. { return }
  5674. // Might be a text scaling operation, clear size caches.
  5675. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5676. d.scrollbarsClipped = false
  5677. cm.setSize()
  5678. }
  5679. var keyNames = {
  5680. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5681. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5682. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5683. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5684. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  5685. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5686. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5687. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5688. }
  5689. // Number keys
  5690. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
  5691. // Alphabetic keys
  5692. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
  5693. // Function keys
  5694. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
  5695. var keyMap = {}
  5696. keyMap.basic = {
  5697. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5698. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5699. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5700. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5701. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5702. "Esc": "singleSelection"
  5703. }
  5704. // Note that the save and find-related commands aren't defined by
  5705. // default. User code or addons can define them. Unknown commands
  5706. // are simply ignored.
  5707. keyMap.pcDefault = {
  5708. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5709. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5710. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5711. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5712. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5713. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5714. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5715. fallthrough: "basic"
  5716. }
  5717. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5718. keyMap.emacsy = {
  5719. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5720. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5721. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5722. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5723. "Ctrl-O": "openLine"
  5724. }
  5725. keyMap.macDefault = {
  5726. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5727. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5728. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5729. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5730. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5731. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5732. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5733. fallthrough: ["basic", "emacsy"]
  5734. }
  5735. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
  5736. // KEYMAP DISPATCH
  5737. function normalizeKeyName(name) {
  5738. var parts = name.split(/-(?!$)/)
  5739. name = parts[parts.length - 1]
  5740. var alt, ctrl, shift, cmd
  5741. for (var i = 0; i < parts.length - 1; i++) {
  5742. var mod = parts[i]
  5743. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
  5744. else if (/^a(lt)?$/i.test(mod)) { alt = true }
  5745. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
  5746. else if (/^s(hift)?$/i.test(mod)) { shift = true }
  5747. else { throw new Error("Unrecognized modifier name: " + mod) }
  5748. }
  5749. if (alt) { name = "Alt-" + name }
  5750. if (ctrl) { name = "Ctrl-" + name }
  5751. if (cmd) { name = "Cmd-" + name }
  5752. if (shift) { name = "Shift-" + name }
  5753. return name
  5754. }
  5755. // This is a kludge to keep keymaps mostly working as raw objects
  5756. // (backwards compatibility) while at the same time support features
  5757. // like normalization and multi-stroke key bindings. It compiles a
  5758. // new normalized keymap, and then updates the old object to reflect
  5759. // this.
  5760. function normalizeKeyMap(keymap) {
  5761. var copy = {}
  5762. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  5763. var value = keymap[keyname]
  5764. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  5765. if (value == "...") { delete keymap[keyname]; continue }
  5766. var keys = map(keyname.split(" "), normalizeKeyName)
  5767. for (var i = 0; i < keys.length; i++) {
  5768. var val = void 0, name = void 0
  5769. if (i == keys.length - 1) {
  5770. name = keys.join(" ")
  5771. val = value
  5772. } else {
  5773. name = keys.slice(0, i + 1).join(" ")
  5774. val = "..."
  5775. }
  5776. var prev = copy[name]
  5777. if (!prev) { copy[name] = val }
  5778. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  5779. }
  5780. delete keymap[keyname]
  5781. } }
  5782. for (var prop in copy) { keymap[prop] = copy[prop] }
  5783. return keymap
  5784. }
  5785. function lookupKey(key, map$$1, handle, context) {
  5786. map$$1 = getKeyMap(map$$1)
  5787. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]
  5788. if (found === false) { return "nothing" }
  5789. if (found === "...") { return "multi" }
  5790. if (found != null && handle(found)) { return "handled" }
  5791. if (map$$1.fallthrough) {
  5792. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  5793. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  5794. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  5795. var result = lookupKey(key, map$$1.fallthrough[i], handle, context)
  5796. if (result) { return result }
  5797. }
  5798. }
  5799. }
  5800. // Modifier key presses don't count as 'real' key presses for the
  5801. // purpose of keymap fallthrough.
  5802. function isModifierKey(value) {
  5803. var name = typeof value == "string" ? value : keyNames[value.keyCode]
  5804. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  5805. }
  5806. // Look up the name of a key as indicated by an event object.
  5807. function keyName(event, noShift) {
  5808. if (presto && event.keyCode == 34 && event["char"]) { return false }
  5809. var base = keyNames[event.keyCode], name = base
  5810. if (name == null || event.altGraphKey) { return false }
  5811. if (event.altKey && base != "Alt") { name = "Alt-" + name }
  5812. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
  5813. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
  5814. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
  5815. return name
  5816. }
  5817. function getKeyMap(val) {
  5818. return typeof val == "string" ? keyMap[val] : val
  5819. }
  5820. // Helper for deleting text near the selection(s), used to implement
  5821. // backspace, delete, and similar functionality.
  5822. function deleteNearSelection(cm, compute) {
  5823. var ranges = cm.doc.sel.ranges, kill = []
  5824. // Build up a set of ranges to kill first, merging overlapping
  5825. // ranges.
  5826. for (var i = 0; i < ranges.length; i++) {
  5827. var toKill = compute(ranges[i])
  5828. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  5829. var replaced = kill.pop()
  5830. if (cmp(replaced.from, toKill.from) < 0) {
  5831. toKill.from = replaced.from
  5832. break
  5833. }
  5834. }
  5835. kill.push(toKill)
  5836. }
  5837. // Next, remove those actual ranges.
  5838. runInOp(cm, function () {
  5839. for (var i = kill.length - 1; i >= 0; i--)
  5840. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") }
  5841. ensureCursorVisible(cm)
  5842. })
  5843. }
  5844. // Commands are parameter-less actions that can be performed on an
  5845. // editor, mostly used for keybindings.
  5846. var commands = {
  5847. selectAll: selectAll,
  5848. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  5849. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  5850. if (range.empty()) {
  5851. var len = getLine(cm.doc, range.head.line).text.length
  5852. if (range.head.ch == len && range.head.line < cm.lastLine())
  5853. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  5854. else
  5855. { return {from: range.head, to: Pos(range.head.line, len)} }
  5856. } else {
  5857. return {from: range.from(), to: range.to()}
  5858. }
  5859. }); },
  5860. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5861. from: Pos(range.from().line, 0),
  5862. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  5863. }); }); },
  5864. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5865. from: Pos(range.from().line, 0), to: range.from()
  5866. }); }); },
  5867. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  5868. var top = cm.charCoords(range.head, "div").top + 5
  5869. var leftPos = cm.coordsChar({left: 0, top: top}, "div")
  5870. return {from: leftPos, to: range.from()}
  5871. }); },
  5872. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  5873. var top = cm.charCoords(range.head, "div").top + 5
  5874. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  5875. return {from: range.from(), to: rightPos }
  5876. }); },
  5877. undo: function (cm) { return cm.undo(); },
  5878. redo: function (cm) { return cm.redo(); },
  5879. undoSelection: function (cm) { return cm.undoSelection(); },
  5880. redoSelection: function (cm) { return cm.redoSelection(); },
  5881. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  5882. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  5883. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  5884. {origin: "+move", bias: 1}
  5885. ); },
  5886. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  5887. {origin: "+move", bias: 1}
  5888. ); },
  5889. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  5890. {origin: "+move", bias: -1}
  5891. ); },
  5892. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  5893. var top = cm.charCoords(range.head, "div").top + 5
  5894. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  5895. }, sel_move); },
  5896. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  5897. var top = cm.charCoords(range.head, "div").top + 5
  5898. return cm.coordsChar({left: 0, top: top}, "div")
  5899. }, sel_move); },
  5900. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  5901. var top = cm.charCoords(range.head, "div").top + 5
  5902. var pos = cm.coordsChar({left: 0, top: top}, "div")
  5903. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  5904. return pos
  5905. }, sel_move); },
  5906. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  5907. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  5908. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  5909. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  5910. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  5911. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  5912. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  5913. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  5914. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  5915. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  5916. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  5917. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  5918. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  5919. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  5920. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  5921. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  5922. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  5923. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  5924. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  5925. indentMore: function (cm) { return cm.indentSelection("add"); },
  5926. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  5927. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  5928. insertSoftTab: function (cm) {
  5929. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
  5930. for (var i = 0; i < ranges.length; i++) {
  5931. var pos = ranges[i].from()
  5932. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  5933. spaces.push(spaceStr(tabSize - col % tabSize))
  5934. }
  5935. cm.replaceSelections(spaces)
  5936. },
  5937. defaultTab: function (cm) {
  5938. if (cm.somethingSelected()) { cm.indentSelection("add") }
  5939. else { cm.execCommand("insertTab") }
  5940. },
  5941. // Swap the two chars left and right of each selection's head.
  5942. // Move cursor behind the two swapped characters afterwards.
  5943. //
  5944. // Doesn't consider line feeds a character.
  5945. // Doesn't scan more than one line above to find a character.
  5946. // Doesn't do anything on an empty line.
  5947. // Doesn't do anything with non-empty selections.
  5948. transposeChars: function (cm) { return runInOp(cm, function () {
  5949. var ranges = cm.listSelections(), newSel = []
  5950. for (var i = 0; i < ranges.length; i++) {
  5951. if (!ranges[i].empty()) { continue }
  5952. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
  5953. if (line) {
  5954. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
  5955. if (cur.ch > 0) {
  5956. cur = new Pos(cur.line, cur.ch + 1)
  5957. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5958. Pos(cur.line, cur.ch - 2), cur, "+transpose")
  5959. } else if (cur.line > cm.doc.first) {
  5960. var prev = getLine(cm.doc, cur.line - 1).text
  5961. if (prev) {
  5962. cur = new Pos(cur.line, 1)
  5963. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  5964. prev.charAt(prev.length - 1),
  5965. Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
  5966. }
  5967. }
  5968. }
  5969. newSel.push(new Range(cur, cur))
  5970. }
  5971. cm.setSelections(newSel)
  5972. }); },
  5973. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  5974. var sels = cm.listSelections()
  5975. for (var i = sels.length - 1; i >= 0; i--)
  5976. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") }
  5977. sels = cm.listSelections()
  5978. for (var i$1 = 0; i$1 < sels.length; i$1++)
  5979. { cm.indentLine(sels[i$1].from().line, null, true) }
  5980. ensureCursorVisible(cm)
  5981. }); },
  5982. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  5983. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  5984. }
  5985. function lineStart(cm, lineN) {
  5986. var line = getLine(cm.doc, lineN)
  5987. var visual = visualLine(line)
  5988. if (visual != line) { lineN = lineNo(visual) }
  5989. var order = getOrder(visual)
  5990. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual)
  5991. return Pos(lineN, ch)
  5992. }
  5993. function lineEnd(cm, lineN) {
  5994. var merged, line = getLine(cm.doc, lineN)
  5995. while (merged = collapsedSpanAtEnd(line)) {
  5996. line = merged.find(1, true).line
  5997. lineN = null
  5998. }
  5999. var order = getOrder(line)
  6000. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line)
  6001. return Pos(lineN == null ? lineNo(line) : lineN, ch)
  6002. }
  6003. function lineStartSmart(cm, pos) {
  6004. var start = lineStart(cm, pos.line)
  6005. var line = getLine(cm.doc, start.line)
  6006. var order = getOrder(line)
  6007. if (!order || order[0].level == 0) {
  6008. var firstNonWS = Math.max(0, line.text.search(/\S/))
  6009. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  6010. return Pos(start.line, inWS ? 0 : firstNonWS)
  6011. }
  6012. return start
  6013. }
  6014. // Run a handler that was bound to a key.
  6015. function doHandleBinding(cm, bound, dropShift) {
  6016. if (typeof bound == "string") {
  6017. bound = commands[bound]
  6018. if (!bound) { return false }
  6019. }
  6020. // Ensure previous input has been read, so that the handler sees a
  6021. // consistent view of the document
  6022. cm.display.input.ensurePolled()
  6023. var prevShift = cm.display.shift, done = false
  6024. try {
  6025. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6026. if (dropShift) { cm.display.shift = false }
  6027. done = bound(cm) != Pass
  6028. } finally {
  6029. cm.display.shift = prevShift
  6030. cm.state.suppressEdits = false
  6031. }
  6032. return done
  6033. }
  6034. function lookupKeyForEditor(cm, name, handle) {
  6035. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6036. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  6037. if (result) { return result }
  6038. }
  6039. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6040. || lookupKey(name, cm.options.keyMap, handle, cm)
  6041. }
  6042. var stopSeq = new Delayed
  6043. function dispatchKey(cm, name, e, handle) {
  6044. var seq = cm.state.keySeq
  6045. if (seq) {
  6046. if (isModifierKey(name)) { return "handled" }
  6047. stopSeq.set(50, function () {
  6048. if (cm.state.keySeq == seq) {
  6049. cm.state.keySeq = null
  6050. cm.display.input.reset()
  6051. }
  6052. })
  6053. name = seq + " " + name
  6054. }
  6055. var result = lookupKeyForEditor(cm, name, handle)
  6056. if (result == "multi")
  6057. { cm.state.keySeq = name }
  6058. if (result == "handled")
  6059. { signalLater(cm, "keyHandled", cm, name, e) }
  6060. if (result == "handled" || result == "multi") {
  6061. e_preventDefault(e)
  6062. restartBlink(cm)
  6063. }
  6064. if (seq && !result && /\'$/.test(name)) {
  6065. e_preventDefault(e)
  6066. return true
  6067. }
  6068. return !!result
  6069. }
  6070. // Handle a key from the keydown event.
  6071. function handleKeyBinding(cm, e) {
  6072. var name = keyName(e, true)
  6073. if (!name) { return false }
  6074. if (e.shiftKey && !cm.state.keySeq) {
  6075. // First try to resolve full name (including 'Shift-'). Failing
  6076. // that, see if there is a cursor-motion command (starting with
  6077. // 'go') bound to the keyname without 'Shift-'.
  6078. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6079. || dispatchKey(cm, name, e, function (b) {
  6080. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6081. { return doHandleBinding(cm, b) }
  6082. })
  6083. } else {
  6084. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6085. }
  6086. }
  6087. // Handle a key from the keypress event
  6088. function handleCharBinding(cm, e, ch) {
  6089. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6090. }
  6091. var lastStoppedKey = null
  6092. function onKeyDown(e) {
  6093. var cm = this
  6094. cm.curOp.focus = activeElt()
  6095. if (signalDOMEvent(cm, e)) { return }
  6096. // IE does strange things with escape.
  6097. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
  6098. var code = e.keyCode
  6099. cm.display.shift = code == 16 || e.shiftKey
  6100. var handled = handleKeyBinding(cm, e)
  6101. if (presto) {
  6102. lastStoppedKey = handled ? code : null
  6103. // Opera has no cut event... we try to at least catch the key combo
  6104. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6105. { cm.replaceSelection("", null, "cut") }
  6106. }
  6107. // Turn mouse into crosshair when Alt is held on Mac.
  6108. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6109. { showCrossHair(cm) }
  6110. }
  6111. function showCrossHair(cm) {
  6112. var lineDiv = cm.display.lineDiv
  6113. addClass(lineDiv, "CodeMirror-crosshair")
  6114. function up(e) {
  6115. if (e.keyCode == 18 || !e.altKey) {
  6116. rmClass(lineDiv, "CodeMirror-crosshair")
  6117. off(document, "keyup", up)
  6118. off(document, "mouseover", up)
  6119. }
  6120. }
  6121. on(document, "keyup", up)
  6122. on(document, "mouseover", up)
  6123. }
  6124. function onKeyUp(e) {
  6125. if (e.keyCode == 16) { this.doc.sel.shift = false }
  6126. signalDOMEvent(this, e)
  6127. }
  6128. function onKeyPress(e) {
  6129. var cm = this
  6130. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6131. var keyCode = e.keyCode, charCode = e.charCode
  6132. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6133. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6134. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  6135. // Some browsers fire keypress events for backspace
  6136. if (ch == "\x08") { return }
  6137. if (handleCharBinding(cm, e, ch)) { return }
  6138. cm.display.input.onKeyPress(e)
  6139. }
  6140. // A mouse down can be a single click, double click, triple click,
  6141. // start of selection drag, start of text drag, new cursor
  6142. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6143. // middle-click-paste. Or it might be a click on something we should
  6144. // not interfere with, such as a scrollbar or widget.
  6145. function onMouseDown(e) {
  6146. var cm = this, display = cm.display
  6147. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6148. display.input.ensurePolled()
  6149. display.shift = e.shiftKey
  6150. if (eventInWidget(display, e)) {
  6151. if (!webkit) {
  6152. // Briefly turn off draggability, to allow widgets to do
  6153. // normal dragging things.
  6154. display.scroller.draggable = false
  6155. setTimeout(function () { return display.scroller.draggable = true; }, 100)
  6156. }
  6157. return
  6158. }
  6159. if (clickInGutter(cm, e)) { return }
  6160. var start = posFromMouse(cm, e)
  6161. window.focus()
  6162. switch (e_button(e)) {
  6163. case 1:
  6164. // #3261: make sure, that we're not starting a second selection
  6165. if (cm.state.selectingText)
  6166. { cm.state.selectingText(e) }
  6167. else if (start)
  6168. { leftButtonDown(cm, e, start) }
  6169. else if (e_target(e) == display.scroller)
  6170. { e_preventDefault(e) }
  6171. break
  6172. case 2:
  6173. if (webkit) { cm.state.lastMiddleDown = +new Date }
  6174. if (start) { extendSelection(cm.doc, start) }
  6175. setTimeout(function () { return display.input.focus(); }, 20)
  6176. e_preventDefault(e)
  6177. break
  6178. case 3:
  6179. if (captureRightClick) { onContextMenu(cm, e) }
  6180. else { delayBlurEvent(cm) }
  6181. break
  6182. }
  6183. }
  6184. var lastClick;
  6185. var lastDoubleClick
  6186. function leftButtonDown(cm, e, start) {
  6187. if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
  6188. else { cm.curOp.focus = activeElt() }
  6189. var now = +new Date, type
  6190. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  6191. type = "triple"
  6192. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  6193. type = "double"
  6194. lastDoubleClick = {time: now, pos: start}
  6195. } else {
  6196. type = "single"
  6197. lastClick = {time: now, pos: start}
  6198. }
  6199. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained
  6200. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6201. type == "single" && (contained = sel.contains(start)) > -1 &&
  6202. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  6203. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  6204. { leftButtonStartDrag(cm, e, start, modifier) }
  6205. else
  6206. { leftButtonSelect(cm, e, start, type, modifier) }
  6207. }
  6208. // Start a text drag. When it ends, see if any dragging actually
  6209. // happen, and treat as a click if it didn't.
  6210. function leftButtonStartDrag(cm, e, start, modifier) {
  6211. var display = cm.display, startTime = +new Date
  6212. var dragEnd = operation(cm, function (e2) {
  6213. if (webkit) { display.scroller.draggable = false }
  6214. cm.state.draggingText = false
  6215. off(document, "mouseup", dragEnd)
  6216. off(display.scroller, "drop", dragEnd)
  6217. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  6218. e_preventDefault(e2)
  6219. if (!modifier && +new Date - 200 < startTime)
  6220. { extendSelection(cm.doc, start) }
  6221. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6222. if (webkit || ie && ie_version == 9)
  6223. { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) }
  6224. else
  6225. { display.input.focus() }
  6226. }
  6227. })
  6228. // Let the drag handler handle this.
  6229. if (webkit) { display.scroller.draggable = true }
  6230. cm.state.draggingText = dragEnd
  6231. dragEnd.copy = mac ? e.altKey : e.ctrlKey
  6232. // IE's approach to draggable
  6233. if (display.scroller.dragDrop) { display.scroller.dragDrop() }
  6234. on(document, "mouseup", dragEnd)
  6235. on(display.scroller, "drop", dragEnd)
  6236. }
  6237. // Normal selection, as opposed to text dragging.
  6238. function leftButtonSelect(cm, e, start, type, addNew) {
  6239. var display = cm.display, doc = cm.doc
  6240. e_preventDefault(e)
  6241. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  6242. if (addNew && !e.shiftKey) {
  6243. ourIndex = doc.sel.contains(start)
  6244. if (ourIndex > -1)
  6245. { ourRange = ranges[ourIndex] }
  6246. else
  6247. { ourRange = new Range(start, start) }
  6248. } else {
  6249. ourRange = doc.sel.primary()
  6250. ourIndex = doc.sel.primIndex
  6251. }
  6252. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  6253. type = "rect"
  6254. if (!addNew) { ourRange = new Range(start, start) }
  6255. start = posFromMouse(cm, e, true, true)
  6256. ourIndex = -1
  6257. } else if (type == "double") {
  6258. var word = cm.findWordAt(start)
  6259. if (cm.display.shift || doc.extend)
  6260. { ourRange = extendRange(doc, ourRange, word.anchor, word.head) }
  6261. else
  6262. { ourRange = word }
  6263. } else if (type == "triple") {
  6264. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)))
  6265. if (cm.display.shift || doc.extend)
  6266. { ourRange = extendRange(doc, ourRange, line.anchor, line.head) }
  6267. else
  6268. { ourRange = line }
  6269. } else {
  6270. ourRange = extendRange(doc, ourRange, start)
  6271. }
  6272. if (!addNew) {
  6273. ourIndex = 0
  6274. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  6275. startSel = doc.sel
  6276. } else if (ourIndex == -1) {
  6277. ourIndex = ranges.length
  6278. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6279. {scroll: false, origin: "*mouse"})
  6280. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  6281. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6282. {scroll: false, origin: "*mouse"})
  6283. startSel = doc.sel
  6284. } else {
  6285. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  6286. }
  6287. var lastPos = start
  6288. function extendTo(pos) {
  6289. if (cmp(lastPos, pos) == 0) { return }
  6290. lastPos = pos
  6291. if (type == "rect") {
  6292. var ranges = [], tabSize = cm.options.tabSize
  6293. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  6294. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  6295. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  6296. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6297. line <= end; line++) {
  6298. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  6299. if (left == right)
  6300. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
  6301. else if (text.length > leftPos)
  6302. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
  6303. }
  6304. if (!ranges.length) { ranges.push(new Range(start, start)) }
  6305. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6306. {origin: "*mouse", scroll: false})
  6307. cm.scrollIntoView(pos)
  6308. } else {
  6309. var oldRange = ourRange
  6310. var anchor = oldRange.anchor, head = pos
  6311. if (type != "single") {
  6312. var range$$1
  6313. if (type == "double")
  6314. { range$$1 = cm.findWordAt(pos) }
  6315. else
  6316. { range$$1 = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) }
  6317. if (cmp(range$$1.anchor, anchor) > 0) {
  6318. head = range$$1.head
  6319. anchor = minPos(oldRange.from(), range$$1.anchor)
  6320. } else {
  6321. head = range$$1.anchor
  6322. anchor = maxPos(oldRange.to(), range$$1.head)
  6323. }
  6324. }
  6325. var ranges$1 = startSel.ranges.slice(0)
  6326. ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head)
  6327. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
  6328. }
  6329. }
  6330. var editorSize = display.wrapper.getBoundingClientRect()
  6331. // Used to ensure timeout re-tries don't fire when another extend
  6332. // happened in the meantime (clearTimeout isn't reliable -- at
  6333. // least on Chrome, the timeouts still happen even when cleared,
  6334. // if the clear happens after their scheduled firing time).
  6335. var counter = 0
  6336. function extend(e) {
  6337. var curCount = ++counter
  6338. var cur = posFromMouse(cm, e, true, type == "rect")
  6339. if (!cur) { return }
  6340. if (cmp(cur, lastPos) != 0) {
  6341. cm.curOp.focus = activeElt()
  6342. extendTo(cur)
  6343. var visible = visibleLines(display, doc)
  6344. if (cur.line >= visible.to || cur.line < visible.from)
  6345. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
  6346. } else {
  6347. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  6348. if (outside) { setTimeout(operation(cm, function () {
  6349. if (counter != curCount) { return }
  6350. display.scroller.scrollTop += outside
  6351. extend(e)
  6352. }), 50) }
  6353. }
  6354. }
  6355. function done(e) {
  6356. cm.state.selectingText = false
  6357. counter = Infinity
  6358. e_preventDefault(e)
  6359. display.input.focus()
  6360. off(document, "mousemove", move)
  6361. off(document, "mouseup", up)
  6362. doc.history.lastSelOrigin = null
  6363. }
  6364. var move = operation(cm, function (e) {
  6365. if (!e_button(e)) { done(e) }
  6366. else { extend(e) }
  6367. })
  6368. var up = operation(cm, done)
  6369. cm.state.selectingText = up
  6370. on(document, "mousemove", move)
  6371. on(document, "mouseup", up)
  6372. }
  6373. // Determines whether an event happened in the gutter, and fires the
  6374. // handlers for the corresponding event.
  6375. function gutterEvent(cm, e, type, prevent) {
  6376. var mX, mY
  6377. try { mX = e.clientX; mY = e.clientY }
  6378. catch(e) { return false }
  6379. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6380. if (prevent) { e_preventDefault(e) }
  6381. var display = cm.display
  6382. var lineBox = display.lineDiv.getBoundingClientRect()
  6383. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6384. mY -= lineBox.top - display.viewOffset
  6385. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6386. var g = display.gutters.childNodes[i]
  6387. if (g && g.getBoundingClientRect().right >= mX) {
  6388. var line = lineAtHeight(cm.doc, mY)
  6389. var gutter = cm.options.gutters[i]
  6390. signal(cm, type, cm, line, gutter, e)
  6391. return e_defaultPrevented(e)
  6392. }
  6393. }
  6394. }
  6395. function clickInGutter(cm, e) {
  6396. return gutterEvent(cm, e, "gutterClick", true)
  6397. }
  6398. // CONTEXT MENU HANDLING
  6399. // To make the context menu work, we need to briefly unhide the
  6400. // textarea (making it as unobtrusive as possible) to let the
  6401. // right-click take effect on it.
  6402. function onContextMenu(cm, e) {
  6403. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6404. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6405. cm.display.input.onContextMenu(e)
  6406. }
  6407. function contextMenuInGutter(cm, e) {
  6408. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6409. return gutterEvent(cm, e, "gutterContextMenu", false)
  6410. }
  6411. function themeChanged(cm) {
  6412. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6413. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
  6414. clearCaches(cm)
  6415. }
  6416. var Init = {toString: function(){return "CodeMirror.Init"}}
  6417. var defaults = {}
  6418. var optionHandlers = {}
  6419. function defineOptions(CodeMirror) {
  6420. var optionHandlers = CodeMirror.optionHandlers
  6421. function option(name, deflt, handle, notOnInit) {
  6422. CodeMirror.defaults[name] = deflt
  6423. if (handle) { optionHandlers[name] =
  6424. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
  6425. }
  6426. CodeMirror.defineOption = option
  6427. // Passed to option handlers when there is no old value.
  6428. CodeMirror.Init = Init
  6429. // These two are, on init, called from the constructor because they
  6430. // have to be initialized before the editor can start at all.
  6431. option("value", "", function (cm, val) { return cm.setValue(val); }, true)
  6432. option("mode", null, function (cm, val) {
  6433. cm.doc.modeOption = val
  6434. loadMode(cm)
  6435. }, true)
  6436. option("indentUnit", 2, loadMode, true)
  6437. option("indentWithTabs", false)
  6438. option("smartIndent", true)
  6439. option("tabSize", 4, function (cm) {
  6440. resetModeState(cm)
  6441. clearCaches(cm)
  6442. regChange(cm)
  6443. }, true)
  6444. option("lineSeparator", null, function (cm, val) {
  6445. cm.doc.lineSep = val
  6446. if (!val) { return }
  6447. var newBreaks = [], lineNo = cm.doc.first
  6448. cm.doc.iter(function (line) {
  6449. for (var pos = 0;;) {
  6450. var found = line.text.indexOf(val, pos)
  6451. if (found == -1) { break }
  6452. pos = found + val.length
  6453. newBreaks.push(Pos(lineNo, found))
  6454. }
  6455. lineNo++
  6456. })
  6457. for (var i = newBreaks.length - 1; i >= 0; i--)
  6458. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
  6459. })
  6460. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6461. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
  6462. if (old != Init) { cm.refresh() }
  6463. })
  6464. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
  6465. option("electricChars", true)
  6466. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6467. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6468. }, true)
  6469. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
  6470. option("rtlMoveVisually", !windows)
  6471. option("wholeLineUpdateBefore", true)
  6472. option("theme", "default", function (cm) {
  6473. themeChanged(cm)
  6474. guttersChanged(cm)
  6475. }, true)
  6476. option("keyMap", "default", function (cm, val, old) {
  6477. var next = getKeyMap(val)
  6478. var prev = old != Init && getKeyMap(old)
  6479. if (prev && prev.detach) { prev.detach(cm, next) }
  6480. if (next.attach) { next.attach(cm, prev || null) }
  6481. })
  6482. option("extraKeys", null)
  6483. option("lineWrapping", false, wrappingChanged, true)
  6484. option("gutters", [], function (cm) {
  6485. setGuttersForLineNumbers(cm.options)
  6486. guttersChanged(cm)
  6487. }, true)
  6488. option("fixedGutter", true, function (cm, val) {
  6489. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
  6490. cm.refresh()
  6491. }, true)
  6492. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
  6493. option("scrollbarStyle", "native", function (cm) {
  6494. initScrollbars(cm)
  6495. updateScrollbars(cm)
  6496. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  6497. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  6498. }, true)
  6499. option("lineNumbers", false, function (cm) {
  6500. setGuttersForLineNumbers(cm.options)
  6501. guttersChanged(cm)
  6502. }, true)
  6503. option("firstLineNumber", 1, guttersChanged, true)
  6504. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
  6505. option("showCursorWhenSelecting", false, updateSelection, true)
  6506. option("resetSelectionOnContextMenu", true)
  6507. option("lineWiseCopyCut", true)
  6508. option("readOnly", false, function (cm, val) {
  6509. if (val == "nocursor") {
  6510. onBlur(cm)
  6511. cm.display.input.blur()
  6512. cm.display.disabled = true
  6513. } else {
  6514. cm.display.disabled = false
  6515. }
  6516. cm.display.input.readOnlyChanged(val)
  6517. })
  6518. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
  6519. option("dragDrop", true, dragDropChanged)
  6520. option("allowDropFileTypes", null)
  6521. option("cursorBlinkRate", 530)
  6522. option("cursorScrollMargin", 0)
  6523. option("cursorHeight", 1, updateSelection, true)
  6524. option("singleCursorHeightPerLine", true, updateSelection, true)
  6525. option("workTime", 100)
  6526. option("workDelay", 100)
  6527. option("flattenSpans", true, resetModeState, true)
  6528. option("addModeClass", false, resetModeState, true)
  6529. option("pollInterval", 100)
  6530. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
  6531. option("historyEventDelay", 1250)
  6532. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true)
  6533. option("maxHighlightLength", 10000, resetModeState, true)
  6534. option("moveInputWithCursor", true, function (cm, val) {
  6535. if (!val) { cm.display.input.resetPosition() }
  6536. })
  6537. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; })
  6538. option("autofocus", null)
  6539. }
  6540. function guttersChanged(cm) {
  6541. updateGutters(cm)
  6542. regChange(cm)
  6543. setTimeout(function () { return alignHorizontally(cm); }, 20)
  6544. }
  6545. function dragDropChanged(cm, value, old) {
  6546. var wasOn = old && old != Init
  6547. if (!value != !wasOn) {
  6548. var funcs = cm.display.dragFunctions
  6549. var toggle = value ? on : off
  6550. toggle(cm.display.scroller, "dragstart", funcs.start)
  6551. toggle(cm.display.scroller, "dragenter", funcs.enter)
  6552. toggle(cm.display.scroller, "dragover", funcs.over)
  6553. toggle(cm.display.scroller, "dragleave", funcs.leave)
  6554. toggle(cm.display.scroller, "drop", funcs.drop)
  6555. }
  6556. }
  6557. function wrappingChanged(cm) {
  6558. if (cm.options.lineWrapping) {
  6559. addClass(cm.display.wrapper, "CodeMirror-wrap")
  6560. cm.display.sizer.style.minWidth = ""
  6561. cm.display.sizerWidth = null
  6562. } else {
  6563. rmClass(cm.display.wrapper, "CodeMirror-wrap")
  6564. findMaxLine(cm)
  6565. }
  6566. estimateLineHeights(cm)
  6567. regChange(cm)
  6568. clearCaches(cm)
  6569. setTimeout(function () { return updateScrollbars(cm); }, 100)
  6570. }
  6571. // A CodeMirror instance represents an editor. This is the object
  6572. // that user code is usually dealing with.
  6573. function CodeMirror$1(place, options) {
  6574. var this$1 = this;
  6575. if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
  6576. this.options = options = options ? copyObj(options) : {}
  6577. // Determine effective options based on given values and defaults.
  6578. copyObj(defaults, options, false)
  6579. setGuttersForLineNumbers(options)
  6580. var doc = options.value
  6581. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator) }
  6582. this.doc = doc
  6583. var input = new CodeMirror$1.inputStyles[options.inputStyle](this)
  6584. var display = this.display = new Display(place, doc, input)
  6585. display.wrapper.CodeMirror = this
  6586. updateGutters(this)
  6587. themeChanged(this)
  6588. if (options.lineWrapping)
  6589. { this.display.wrapper.className += " CodeMirror-wrap" }
  6590. if (options.autofocus && !mobile) { display.input.focus() }
  6591. initScrollbars(this)
  6592. this.state = {
  6593. keyMaps: [], // stores maps added by addKeyMap
  6594. overlays: [], // highlighting overlays, as added by addOverlay
  6595. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  6596. overwrite: false,
  6597. delayingBlurEvent: false,
  6598. focused: false,
  6599. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  6600. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  6601. selectingText: false,
  6602. draggingText: false,
  6603. highlight: new Delayed(), // stores highlight worker timeout
  6604. keySeq: null, // Unfinished key sequence
  6605. specialChars: null
  6606. }
  6607. // Override magic textarea content restore that IE sometimes does
  6608. // on our hidden textarea on reload
  6609. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
  6610. registerEventHandlers(this)
  6611. ensureGlobalHandlers()
  6612. startOperation(this)
  6613. this.curOp.forceUpdate = true
  6614. attachDoc(this, doc)
  6615. if ((options.autofocus && !mobile) || this.hasFocus())
  6616. { setTimeout(bind(onFocus, this), 20) }
  6617. else
  6618. { onBlur(this) }
  6619. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  6620. { optionHandlers[opt](this$1, options[opt], Init) } }
  6621. maybeUpdateLineNumberWidth(this)
  6622. if (options.finishInit) { options.finishInit(this) }
  6623. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
  6624. endOperation(this)
  6625. // Suppress optimizelegibility in Webkit, since it breaks text
  6626. // measuring on line wrapping boundaries.
  6627. if (webkit && options.lineWrapping &&
  6628. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  6629. { display.lineDiv.style.textRendering = "auto" }
  6630. }
  6631. // The default configuration options.
  6632. CodeMirror$1.defaults = defaults
  6633. // Functions to run when options are changed.
  6634. CodeMirror$1.optionHandlers = optionHandlers
  6635. // Attach the necessary event handlers when initializing the editor
  6636. function registerEventHandlers(cm) {
  6637. var d = cm.display
  6638. on(d.scroller, "mousedown", operation(cm, onMouseDown))
  6639. // Older IE's will not fire a second mousedown for a double click
  6640. if (ie && ie_version < 11)
  6641. { on(d.scroller, "dblclick", operation(cm, function (e) {
  6642. if (signalDOMEvent(cm, e)) { return }
  6643. var pos = posFromMouse(cm, e)
  6644. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  6645. e_preventDefault(e)
  6646. var word = cm.findWordAt(pos)
  6647. extendSelection(cm.doc, word.anchor, word.head)
  6648. })) }
  6649. else
  6650. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
  6651. // Some browsers fire contextmenu *after* opening the menu, at
  6652. // which point we can't mess with it anymore. Context menu is
  6653. // handled in onMouseDown for these browsers.
  6654. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
  6655. // Used to suppress mouse event handling when a touch happens
  6656. var touchFinished, prevTouch = {end: 0}
  6657. function finishTouch() {
  6658. if (d.activeTouch) {
  6659. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
  6660. prevTouch = d.activeTouch
  6661. prevTouch.end = +new Date
  6662. }
  6663. }
  6664. function isMouseLikeTouchEvent(e) {
  6665. if (e.touches.length != 1) { return false }
  6666. var touch = e.touches[0]
  6667. return touch.radiusX <= 1 && touch.radiusY <= 1
  6668. }
  6669. function farAway(touch, other) {
  6670. if (other.left == null) { return true }
  6671. var dx = other.left - touch.left, dy = other.top - touch.top
  6672. return dx * dx + dy * dy > 20 * 20
  6673. }
  6674. on(d.scroller, "touchstart", function (e) {
  6675. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  6676. d.input.ensurePolled()
  6677. clearTimeout(touchFinished)
  6678. var now = +new Date
  6679. d.activeTouch = {start: now, moved: false,
  6680. prev: now - prevTouch.end <= 300 ? prevTouch : null}
  6681. if (e.touches.length == 1) {
  6682. d.activeTouch.left = e.touches[0].pageX
  6683. d.activeTouch.top = e.touches[0].pageY
  6684. }
  6685. }
  6686. })
  6687. on(d.scroller, "touchmove", function () {
  6688. if (d.activeTouch) { d.activeTouch.moved = true }
  6689. })
  6690. on(d.scroller, "touchend", function (e) {
  6691. var touch = d.activeTouch
  6692. if (touch && !eventInWidget(d, e) && touch.left != null &&
  6693. !touch.moved && new Date - touch.start < 300) {
  6694. var pos = cm.coordsChar(d.activeTouch, "page"), range
  6695. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  6696. { range = new Range(pos, pos) }
  6697. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  6698. { range = cm.findWordAt(pos) }
  6699. else // Triple tap
  6700. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6701. cm.setSelection(range.anchor, range.head)
  6702. cm.focus()
  6703. e_preventDefault(e)
  6704. }
  6705. finishTouch()
  6706. })
  6707. on(d.scroller, "touchcancel", finishTouch)
  6708. // Sync scrolling between fake scrollbars and real scrollable
  6709. // area, ensure viewport is updated when scrolling.
  6710. on(d.scroller, "scroll", function () {
  6711. if (d.scroller.clientHeight) {
  6712. setScrollTop(cm, d.scroller.scrollTop)
  6713. setScrollLeft(cm, d.scroller.scrollLeft, true)
  6714. signal(cm, "scroll", cm)
  6715. }
  6716. })
  6717. // Listen to wheel events in order to try and update the viewport on time.
  6718. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); })
  6719. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); })
  6720. // Prevent wrapper from ever scrolling
  6721. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
  6722. d.dragFunctions = {
  6723. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
  6724. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
  6725. start: function (e) { return onDragStart(cm, e); },
  6726. drop: operation(cm, onDrop),
  6727. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
  6728. }
  6729. var inp = d.input.getField()
  6730. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); })
  6731. on(inp, "keydown", operation(cm, onKeyDown))
  6732. on(inp, "keypress", operation(cm, onKeyPress))
  6733. on(inp, "focus", function (e) { return onFocus(cm, e); })
  6734. on(inp, "blur", function (e) { return onBlur(cm, e); })
  6735. }
  6736. var initHooks = []
  6737. CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); }
  6738. // Indent the given line. The how parameter can be "smart",
  6739. // "add"/null, "subtract", or "prev". When aggressive is false
  6740. // (typically set to true for forced single-line indents), empty
  6741. // lines are not indented, and places where the mode returns Pass
  6742. // are left alone.
  6743. function indentLine(cm, n, how, aggressive) {
  6744. var doc = cm.doc, state
  6745. if (how == null) { how = "add" }
  6746. if (how == "smart") {
  6747. // Fall back to "prev" when the mode doesn't have an indentation
  6748. // method.
  6749. if (!doc.mode.indent) { how = "prev" }
  6750. else { state = getStateBefore(cm, n) }
  6751. }
  6752. var tabSize = cm.options.tabSize
  6753. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
  6754. if (line.stateAfter) { line.stateAfter = null }
  6755. var curSpaceString = line.text.match(/^\s*/)[0], indentation
  6756. if (!aggressive && !/\S/.test(line.text)) {
  6757. indentation = 0
  6758. how = "not"
  6759. } else if (how == "smart") {
  6760. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  6761. if (indentation == Pass || indentation > 150) {
  6762. if (!aggressive) { return }
  6763. how = "prev"
  6764. }
  6765. }
  6766. if (how == "prev") {
  6767. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
  6768. else { indentation = 0 }
  6769. } else if (how == "add") {
  6770. indentation = curSpace + cm.options.indentUnit
  6771. } else if (how == "subtract") {
  6772. indentation = curSpace - cm.options.indentUnit
  6773. } else if (typeof how == "number") {
  6774. indentation = curSpace + how
  6775. }
  6776. indentation = Math.max(0, indentation)
  6777. var indentString = "", pos = 0
  6778. if (cm.options.indentWithTabs)
  6779. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
  6780. if (pos < indentation) { indentString += spaceStr(indentation - pos) }
  6781. if (indentString != curSpaceString) {
  6782. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
  6783. line.stateAfter = null
  6784. return true
  6785. } else {
  6786. // Ensure that, if the cursor was in the whitespace at the start
  6787. // of the line, it is moved to the end of that space.
  6788. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  6789. var range = doc.sel.ranges[i$1]
  6790. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  6791. var pos$1 = Pos(n, curSpaceString.length)
  6792. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  6793. break
  6794. }
  6795. }
  6796. }
  6797. }
  6798. // This will be set to a {lineWise: bool, text: [string]} object, so
  6799. // that, when pasting, we know what kind of selections the copied
  6800. // text was made out of.
  6801. var lastCopied = null
  6802. function setLastCopied(newLastCopied) {
  6803. lastCopied = newLastCopied
  6804. }
  6805. function applyTextInput(cm, inserted, deleted, sel, origin) {
  6806. var doc = cm.doc
  6807. cm.display.shift = false
  6808. if (!sel) { sel = doc.sel }
  6809. var paste = cm.state.pasteIncoming || origin == "paste"
  6810. var textLines = splitLinesAuto(inserted), multiPaste = null
  6811. // When pasing N lines into N selections, insert one line per selection
  6812. if (paste && sel.ranges.length > 1) {
  6813. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  6814. if (sel.ranges.length % lastCopied.text.length == 0) {
  6815. multiPaste = []
  6816. for (var i = 0; i < lastCopied.text.length; i++)
  6817. { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
  6818. }
  6819. } else if (textLines.length == sel.ranges.length) {
  6820. multiPaste = map(textLines, function (l) { return [l]; })
  6821. }
  6822. }
  6823. var updateInput
  6824. // Normal behavior is to insert the new text into every selection
  6825. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  6826. var range$$1 = sel.ranges[i$1]
  6827. var from = range$$1.from(), to = range$$1.to()
  6828. if (range$$1.empty()) {
  6829. if (deleted && deleted > 0) // Handle deletion
  6830. { from = Pos(from.line, from.ch - deleted) }
  6831. else if (cm.state.overwrite && !paste) // Handle overwrite
  6832. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
  6833. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  6834. { from = to = Pos(from.line, 0) }
  6835. }
  6836. updateInput = cm.curOp.updateInput
  6837. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  6838. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
  6839. makeChange(cm.doc, changeEvent)
  6840. signalLater(cm, "inputRead", cm, changeEvent)
  6841. }
  6842. if (inserted && !paste)
  6843. { triggerElectric(cm, inserted) }
  6844. ensureCursorVisible(cm)
  6845. cm.curOp.updateInput = updateInput
  6846. cm.curOp.typing = true
  6847. cm.state.pasteIncoming = cm.state.cutIncoming = false
  6848. }
  6849. function handlePaste(e, cm) {
  6850. var pasted = e.clipboardData && e.clipboardData.getData("Text")
  6851. if (pasted) {
  6852. e.preventDefault()
  6853. if (!cm.isReadOnly() && !cm.options.disableInput)
  6854. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
  6855. return true
  6856. }
  6857. }
  6858. function triggerElectric(cm, inserted) {
  6859. // When an 'electric' character is inserted, immediately trigger a reindent
  6860. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  6861. var sel = cm.doc.sel
  6862. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  6863. var range$$1 = sel.ranges[i]
  6864. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  6865. var mode = cm.getModeAt(range$$1.head)
  6866. var indented = false
  6867. if (mode.electricChars) {
  6868. for (var j = 0; j < mode.electricChars.length; j++)
  6869. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  6870. indented = indentLine(cm, range$$1.head.line, "smart")
  6871. break
  6872. } }
  6873. } else if (mode.electricInput) {
  6874. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  6875. { indented = indentLine(cm, range$$1.head.line, "smart") }
  6876. }
  6877. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line) }
  6878. }
  6879. }
  6880. function copyableRanges(cm) {
  6881. var text = [], ranges = []
  6882. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  6883. var line = cm.doc.sel.ranges[i].head.line
  6884. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}
  6885. ranges.push(lineRange)
  6886. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  6887. }
  6888. return {text: text, ranges: ranges}
  6889. }
  6890. function disableBrowserMagic(field, spellcheck) {
  6891. field.setAttribute("autocorrect", "off")
  6892. field.setAttribute("autocapitalize", "off")
  6893. field.setAttribute("spellcheck", !!spellcheck)
  6894. }
  6895. function hiddenTextarea() {
  6896. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
  6897. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
  6898. // The textarea is kept positioned near the cursor to prevent the
  6899. // fact that it'll be scrolled into view on input from scrolling
  6900. // our fake cursor out of view. On webkit, when wrap=off, paste is
  6901. // very slow. So make the area wide instead.
  6902. if (webkit) { te.style.width = "1000px" }
  6903. else { te.setAttribute("wrap", "off") }
  6904. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  6905. if (ios) { te.style.border = "1px solid black" }
  6906. disableBrowserMagic(te)
  6907. return div
  6908. }
  6909. // The publicly visible API. Note that methodOp(f) means
  6910. // 'wrap f in an operation, performed on its `this` parameter'.
  6911. // This is not the complete set of editor methods. Most of the
  6912. // methods defined on the Doc type are also injected into
  6913. // CodeMirror.prototype, for backwards compatibility and
  6914. // convenience.
  6915. var addEditorMethods = function(CodeMirror) {
  6916. var optionHandlers = CodeMirror.optionHandlers
  6917. var helpers = CodeMirror.helpers = {}
  6918. CodeMirror.prototype = {
  6919. constructor: CodeMirror,
  6920. focus: function(){window.focus(); this.display.input.focus()},
  6921. setOption: function(option, value) {
  6922. var options = this.options, old = options[option]
  6923. if (options[option] == value && option != "mode") { return }
  6924. options[option] = value
  6925. if (optionHandlers.hasOwnProperty(option))
  6926. { operation(this, optionHandlers[option])(this, value, old) }
  6927. },
  6928. getOption: function(option) {return this.options[option]},
  6929. getDoc: function() {return this.doc},
  6930. addKeyMap: function(map$$1, bottom) {
  6931. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1))
  6932. },
  6933. removeKeyMap: function(map$$1) {
  6934. var maps = this.state.keyMaps
  6935. for (var i = 0; i < maps.length; ++i)
  6936. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  6937. maps.splice(i, 1)
  6938. return true
  6939. } }
  6940. },
  6941. addOverlay: methodOp(function(spec, options) {
  6942. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  6943. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  6944. insertSorted(this.state.overlays,
  6945. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  6946. priority: (options && options.priority) || 0},
  6947. function (overlay) { return overlay.priority; })
  6948. this.state.modeGen++
  6949. regChange(this)
  6950. }),
  6951. removeOverlay: methodOp(function(spec) {
  6952. var this$1 = this;
  6953. var overlays = this.state.overlays
  6954. for (var i = 0; i < overlays.length; ++i) {
  6955. var cur = overlays[i].modeSpec
  6956. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  6957. overlays.splice(i, 1)
  6958. this$1.state.modeGen++
  6959. regChange(this$1)
  6960. return
  6961. }
  6962. }
  6963. }),
  6964. indentLine: methodOp(function(n, dir, aggressive) {
  6965. if (typeof dir != "string" && typeof dir != "number") {
  6966. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
  6967. else { dir = dir ? "add" : "subtract" }
  6968. }
  6969. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
  6970. }),
  6971. indentSelection: methodOp(function(how) {
  6972. var this$1 = this;
  6973. var ranges = this.doc.sel.ranges, end = -1
  6974. for (var i = 0; i < ranges.length; i++) {
  6975. var range$$1 = ranges[i]
  6976. if (!range$$1.empty()) {
  6977. var from = range$$1.from(), to = range$$1.to()
  6978. var start = Math.max(end, from.line)
  6979. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  6980. for (var j = start; j < end; ++j)
  6981. { indentLine(this$1, j, how) }
  6982. var newRanges = this$1.doc.sel.ranges
  6983. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  6984. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
  6985. } else if (range$$1.head.line > end) {
  6986. indentLine(this$1, range$$1.head.line, how, true)
  6987. end = range$$1.head.line
  6988. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
  6989. }
  6990. }
  6991. }),
  6992. // Fetch the parser token for a given character. Useful for hacks
  6993. // that want to inspect the mode state (say, for completion).
  6994. getTokenAt: function(pos, precise) {
  6995. return takeToken(this, pos, precise)
  6996. },
  6997. getLineTokens: function(line, precise) {
  6998. return takeToken(this, Pos(line), precise, true)
  6999. },
  7000. getTokenTypeAt: function(pos) {
  7001. pos = clipPos(this.doc, pos)
  7002. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  7003. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
  7004. var type
  7005. if (ch == 0) { type = styles[2] }
  7006. else { for (;;) {
  7007. var mid = (before + after) >> 1
  7008. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
  7009. else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
  7010. else { type = styles[mid * 2 + 2]; break }
  7011. } }
  7012. var cut = type ? type.indexOf("overlay ") : -1
  7013. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7014. },
  7015. getModeAt: function(pos) {
  7016. var mode = this.doc.mode
  7017. if (!mode.innerMode) { return mode }
  7018. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7019. },
  7020. getHelper: function(pos, type) {
  7021. return this.getHelpers(pos, type)[0]
  7022. },
  7023. getHelpers: function(pos, type) {
  7024. var this$1 = this;
  7025. var found = []
  7026. if (!helpers.hasOwnProperty(type)) { return found }
  7027. var help = helpers[type], mode = this.getModeAt(pos)
  7028. if (typeof mode[type] == "string") {
  7029. if (help[mode[type]]) { found.push(help[mode[type]]) }
  7030. } else if (mode[type]) {
  7031. for (var i = 0; i < mode[type].length; i++) {
  7032. var val = help[mode[type][i]]
  7033. if (val) { found.push(val) }
  7034. }
  7035. } else if (mode.helperType && help[mode.helperType]) {
  7036. found.push(help[mode.helperType])
  7037. } else if (help[mode.name]) {
  7038. found.push(help[mode.name])
  7039. }
  7040. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7041. var cur = help._global[i$1]
  7042. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7043. { found.push(cur.val) }
  7044. }
  7045. return found
  7046. },
  7047. getStateAfter: function(line, precise) {
  7048. var doc = this.doc
  7049. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
  7050. return getStateBefore(this, line + 1, precise)
  7051. },
  7052. cursorCoords: function(start, mode) {
  7053. var pos, range$$1 = this.doc.sel.primary()
  7054. if (start == null) { pos = range$$1.head }
  7055. else if (typeof start == "object") { pos = clipPos(this.doc, start) }
  7056. else { pos = start ? range$$1.from() : range$$1.to() }
  7057. return cursorCoords(this, pos, mode || "page")
  7058. },
  7059. charCoords: function(pos, mode) {
  7060. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7061. },
  7062. coordsChar: function(coords, mode) {
  7063. coords = fromCoordSystem(this, coords, mode || "page")
  7064. return coordsChar(this, coords.left, coords.top)
  7065. },
  7066. lineAtHeight: function(height, mode) {
  7067. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
  7068. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7069. },
  7070. heightAtLine: function(line, mode, includeWidgets) {
  7071. var end = false, lineObj
  7072. if (typeof line == "number") {
  7073. var last = this.doc.first + this.doc.size - 1
  7074. if (line < this.doc.first) { line = this.doc.first }
  7075. else if (line > last) { line = last; end = true }
  7076. lineObj = getLine(this.doc, line)
  7077. } else {
  7078. lineObj = line
  7079. }
  7080. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets).top +
  7081. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7082. },
  7083. defaultTextHeight: function() { return textHeight(this.display) },
  7084. defaultCharWidth: function() { return charWidth(this.display) },
  7085. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7086. addWidget: function(pos, node, scroll, vert, horiz) {
  7087. var display = this.display
  7088. pos = cursorCoords(this, clipPos(this.doc, pos))
  7089. var top = pos.bottom, left = pos.left
  7090. node.style.position = "absolute"
  7091. node.setAttribute("cm-ignore-events", "true")
  7092. this.display.input.setUneditable(node)
  7093. display.sizer.appendChild(node)
  7094. if (vert == "over") {
  7095. top = pos.top
  7096. } else if (vert == "above" || vert == "near") {
  7097. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7098. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  7099. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7100. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7101. { top = pos.top - node.offsetHeight }
  7102. else if (pos.bottom + node.offsetHeight <= vspace)
  7103. { top = pos.bottom }
  7104. if (left + node.offsetWidth > hspace)
  7105. { left = hspace - node.offsetWidth }
  7106. }
  7107. node.style.top = top + "px"
  7108. node.style.left = node.style.right = ""
  7109. if (horiz == "right") {
  7110. left = display.sizer.clientWidth - node.offsetWidth
  7111. node.style.right = "0px"
  7112. } else {
  7113. if (horiz == "left") { left = 0 }
  7114. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
  7115. node.style.left = left + "px"
  7116. }
  7117. if (scroll)
  7118. { scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight) }
  7119. },
  7120. triggerOnKeyDown: methodOp(onKeyDown),
  7121. triggerOnKeyPress: methodOp(onKeyPress),
  7122. triggerOnKeyUp: onKeyUp,
  7123. execCommand: function(cmd) {
  7124. if (commands.hasOwnProperty(cmd))
  7125. { return commands[cmd].call(null, this) }
  7126. },
  7127. triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
  7128. findPosH: function(from, amount, unit, visually) {
  7129. var this$1 = this;
  7130. var dir = 1
  7131. if (amount < 0) { dir = -1; amount = -amount }
  7132. var cur = clipPos(this.doc, from)
  7133. for (var i = 0; i < amount; ++i) {
  7134. cur = findPosH(this$1.doc, cur, dir, unit, visually)
  7135. if (cur.hitSide) { break }
  7136. }
  7137. return cur
  7138. },
  7139. moveH: methodOp(function(dir, unit) {
  7140. var this$1 = this;
  7141. this.extendSelectionsBy(function (range$$1) {
  7142. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  7143. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  7144. else
  7145. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7146. }, sel_move)
  7147. }),
  7148. deleteH: methodOp(function(dir, unit) {
  7149. var sel = this.doc.sel, doc = this.doc
  7150. if (sel.somethingSelected())
  7151. { doc.replaceSelection("", null, "+delete") }
  7152. else
  7153. { deleteNearSelection(this, function (range$$1) {
  7154. var other = findPosH(doc, range$$1.head, dir, unit, false)
  7155. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  7156. }) }
  7157. }),
  7158. findPosV: function(from, amount, unit, goalColumn) {
  7159. var this$1 = this;
  7160. var dir = 1, x = goalColumn
  7161. if (amount < 0) { dir = -1; amount = -amount }
  7162. var cur = clipPos(this.doc, from)
  7163. for (var i = 0; i < amount; ++i) {
  7164. var coords = cursorCoords(this$1, cur, "div")
  7165. if (x == null) { x = coords.left }
  7166. else { coords.left = x }
  7167. cur = findPosV(this$1, coords, dir, unit)
  7168. if (cur.hitSide) { break }
  7169. }
  7170. return cur
  7171. },
  7172. moveV: methodOp(function(dir, unit) {
  7173. var this$1 = this;
  7174. var doc = this.doc, goals = []
  7175. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  7176. doc.extendSelectionsBy(function (range$$1) {
  7177. if (collapse)
  7178. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7179. var headPos = cursorCoords(this$1, range$$1.head, "div")
  7180. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn }
  7181. goals.push(headPos.left)
  7182. var pos = findPosV(this$1, headPos, dir, unit)
  7183. if (unit == "page" && range$$1 == doc.sel.primary())
  7184. { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top) }
  7185. return pos
  7186. }, sel_move)
  7187. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7188. { doc.sel.ranges[i].goalColumn = goals[i] } }
  7189. }),
  7190. // Find the word at the given position (as returned by coordsChar).
  7191. findWordAt: function(pos) {
  7192. var doc = this.doc, line = getLine(doc, pos.line).text
  7193. var start = pos.ch, end = pos.ch
  7194. if (line) {
  7195. var helper = this.getHelper(pos, "wordChars")
  7196. if ((pos.xRel < 0 || end == line.length) && start) { --start; } else { ++end }
  7197. var startChar = line.charAt(start)
  7198. var check = isWordChar(startChar, helper)
  7199. ? function (ch) { return isWordChar(ch, helper); }
  7200. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7201. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
  7202. while (start > 0 && check(line.charAt(start - 1))) { --start }
  7203. while (end < line.length && check(line.charAt(end))) { ++end }
  7204. }
  7205. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7206. },
  7207. toggleOverwrite: function(value) {
  7208. if (value != null && value == this.state.overwrite) { return }
  7209. if (this.state.overwrite = !this.state.overwrite)
  7210. { addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7211. else
  7212. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7213. signal(this, "overwriteToggle", this, this.state.overwrite)
  7214. },
  7215. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7216. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7217. scrollTo: methodOp(function(x, y) {
  7218. if (x != null || y != null) { resolveScrollToPos(this) }
  7219. if (x != null) { this.curOp.scrollLeft = x }
  7220. if (y != null) { this.curOp.scrollTop = y }
  7221. }),
  7222. getScrollInfo: function() {
  7223. var scroller = this.display.scroller
  7224. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7225. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7226. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7227. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7228. },
  7229. scrollIntoView: methodOp(function(range$$1, margin) {
  7230. if (range$$1 == null) {
  7231. range$$1 = {from: this.doc.sel.primary().head, to: null}
  7232. if (margin == null) { margin = this.options.cursorScrollMargin }
  7233. } else if (typeof range$$1 == "number") {
  7234. range$$1 = {from: Pos(range$$1, 0), to: null}
  7235. } else if (range$$1.from == null) {
  7236. range$$1 = {from: range$$1, to: null}
  7237. }
  7238. if (!range$$1.to) { range$$1.to = range$$1.from }
  7239. range$$1.margin = margin || 0
  7240. if (range$$1.from.line != null) {
  7241. resolveScrollToPos(this)
  7242. this.curOp.scrollToPos = range$$1
  7243. } else {
  7244. var sPos = calculateScrollPos(this, Math.min(range$$1.from.left, range$$1.to.left),
  7245. Math.min(range$$1.from.top, range$$1.to.top) - range$$1.margin,
  7246. Math.max(range$$1.from.right, range$$1.to.right),
  7247. Math.max(range$$1.from.bottom, range$$1.to.bottom) + range$$1.margin)
  7248. this.scrollTo(sPos.scrollLeft, sPos.scrollTop)
  7249. }
  7250. }),
  7251. setSize: methodOp(function(width, height) {
  7252. var this$1 = this;
  7253. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }
  7254. if (width != null) { this.display.wrapper.style.width = interpret(width) }
  7255. if (height != null) { this.display.wrapper.style.height = interpret(height) }
  7256. if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
  7257. var lineNo$$1 = this.display.viewFrom
  7258. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  7259. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7260. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  7261. ++lineNo$$1
  7262. })
  7263. this.curOp.forceUpdate = true
  7264. signal(this, "refresh", this)
  7265. }),
  7266. operation: function(f){return runInOp(this, f)},
  7267. refresh: methodOp(function() {
  7268. var oldHeight = this.display.cachedTextHeight
  7269. regChange(this)
  7270. this.curOp.forceUpdate = true
  7271. clearCaches(this)
  7272. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop)
  7273. updateGutterSpace(this)
  7274. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7275. { estimateLineHeights(this) }
  7276. signal(this, "refresh", this)
  7277. }),
  7278. swapDoc: methodOp(function(doc) {
  7279. var old = this.doc
  7280. old.cm = null
  7281. attachDoc(this, doc)
  7282. clearCaches(this)
  7283. this.display.input.reset()
  7284. this.scrollTo(doc.scrollLeft, doc.scrollTop)
  7285. this.curOp.forceScroll = true
  7286. signalLater(this, "swapDoc", this, old)
  7287. return old
  7288. }),
  7289. getInputField: function(){return this.display.input.getField()},
  7290. getWrapperElement: function(){return this.display.wrapper},
  7291. getScrollerElement: function(){return this.display.scroller},
  7292. getGutterElement: function(){return this.display.gutters}
  7293. }
  7294. eventMixin(CodeMirror)
  7295. CodeMirror.registerHelper = function(type, name, value) {
  7296. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
  7297. helpers[type][name] = value
  7298. }
  7299. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7300. CodeMirror.registerHelper(type, name, value)
  7301. helpers[type]._global.push({pred: predicate, val: value})
  7302. }
  7303. }
  7304. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7305. // right), unit can be "char", "column" (like char, but doesn't
  7306. // cross line boundaries), "word" (across next word), or "group" (to
  7307. // the start of next group of word or non-word-non-whitespace
  7308. // chars). The visually param controls whether, in right-to-left
  7309. // text, direction 1 means to move towards the next index in the
  7310. // string, or towards the character to the right of the current
  7311. // position. The resulting position will have a hitSide=true
  7312. // property if it reached the end of the document.
  7313. function findPosH(doc, pos, dir, unit, visually) {
  7314. var line = pos.line, ch = pos.ch, origDir = dir
  7315. var lineObj = getLine(doc, line)
  7316. function findNextLine() {
  7317. var l = line + dir
  7318. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7319. line = l
  7320. return lineObj = getLine(doc, l)
  7321. }
  7322. function moveOnce(boundToLine) {
  7323. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true)
  7324. if (next == null) {
  7325. if (!boundToLine && findNextLine()) {
  7326. if (visually) { ch = (dir < 0 ? lineRight : lineLeft)(lineObj) }
  7327. else { ch = dir < 0 ? lineObj.text.length : 0 }
  7328. } else { return false }
  7329. } else { ch = next }
  7330. return true
  7331. }
  7332. if (unit == "char") {
  7333. moveOnce()
  7334. } else if (unit == "column") {
  7335. moveOnce(true)
  7336. } else if (unit == "word" || unit == "group") {
  7337. var sawType = null, group = unit == "group"
  7338. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
  7339. for (var first = true;; first = false) {
  7340. if (dir < 0 && !moveOnce(!first)) { break }
  7341. var cur = lineObj.text.charAt(ch) || "\n"
  7342. var type = isWordChar(cur, helper) ? "w"
  7343. : group && cur == "\n" ? "n"
  7344. : !group || /\s/.test(cur) ? null
  7345. : "p"
  7346. if (group && !first && !type) { type = "s" }
  7347. if (sawType && sawType != type) {
  7348. if (dir < 0) {dir = 1; moveOnce()}
  7349. break
  7350. }
  7351. if (type) { sawType = type }
  7352. if (dir > 0 && !moveOnce(!first)) { break }
  7353. }
  7354. }
  7355. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true)
  7356. if (!cmp(pos, result)) { result.hitSide = true }
  7357. return result
  7358. }
  7359. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7360. // "page" or "line". The resulting position will have a hitSide=true
  7361. // property if it reached the end of the document.
  7362. function findPosV(cm, pos, dir, unit) {
  7363. var doc = cm.doc, x = pos.left, y
  7364. if (unit == "page") {
  7365. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  7366. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
  7367. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  7368. } else if (unit == "line") {
  7369. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  7370. }
  7371. var target
  7372. for (;;) {
  7373. target = coordsChar(cm, x, y)
  7374. if (!target.outside) { break }
  7375. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7376. y += dir * 5
  7377. }
  7378. return target
  7379. }
  7380. // CONTENTEDITABLE INPUT STYLE
  7381. function ContentEditableInput(cm) {
  7382. this.cm = cm
  7383. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  7384. this.polling = new Delayed()
  7385. this.composing = null
  7386. this.gracePeriod = false
  7387. this.readDOMTimeout = null
  7388. }
  7389. ContentEditableInput.prototype = copyObj({
  7390. init: function(display) {
  7391. var this$1 = this;
  7392. var input = this, cm = input.cm
  7393. var div = input.div = display.lineDiv
  7394. disableBrowserMagic(div, cm.options.spellcheck)
  7395. on(div, "paste", function (e) {
  7396. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7397. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7398. if (ie_version <= 11) { setTimeout(operation(cm, function () {
  7399. if (!input.pollContent()) { regChange(cm) }
  7400. }), 20) }
  7401. })
  7402. on(div, "compositionstart", function (e) {
  7403. this$1.composing = {data: e.data}
  7404. })
  7405. on(div, "compositionupdate", function (e) {
  7406. if (!this$1.composing) { this$1.composing = {data: e.data} }
  7407. })
  7408. on(div, "compositionend", function (e) {
  7409. if (this$1.composing) {
  7410. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
  7411. this$1.composing = null
  7412. }
  7413. })
  7414. on(div, "touchstart", function () { return input.forceCompositionEnd(); })
  7415. on(div, "input", function () {
  7416. if (!this$1.composing) { this$1.readFromDOMSoon() }
  7417. })
  7418. function onCopyCut(e) {
  7419. if (signalDOMEvent(cm, e)) { return }
  7420. if (cm.somethingSelected()) {
  7421. setLastCopied({lineWise: false, text: cm.getSelections()})
  7422. if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
  7423. } else if (!cm.options.lineWiseCopyCut) {
  7424. return
  7425. } else {
  7426. var ranges = copyableRanges(cm)
  7427. setLastCopied({lineWise: true, text: ranges.text})
  7428. if (e.type == "cut") {
  7429. cm.operation(function () {
  7430. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  7431. cm.replaceSelection("", null, "cut")
  7432. })
  7433. }
  7434. }
  7435. if (e.clipboardData) {
  7436. e.clipboardData.clearData()
  7437. var content = lastCopied.text.join("\n")
  7438. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7439. e.clipboardData.setData("Text", content)
  7440. if (e.clipboardData.getData("Text") == content) {
  7441. e.preventDefault()
  7442. return
  7443. }
  7444. }
  7445. // Old-fashioned briefly-focus-a-textarea hack
  7446. var kludge = hiddenTextarea(), te = kludge.firstChild
  7447. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  7448. te.value = lastCopied.text.join("\n")
  7449. var hadFocus = document.activeElement
  7450. selectInput(te)
  7451. setTimeout(function () {
  7452. cm.display.lineSpace.removeChild(kludge)
  7453. hadFocus.focus()
  7454. if (hadFocus == div) { input.showPrimarySelection() }
  7455. }, 50)
  7456. }
  7457. on(div, "copy", onCopyCut)
  7458. on(div, "cut", onCopyCut)
  7459. },
  7460. prepareSelection: function() {
  7461. var result = prepareSelection(this.cm, false)
  7462. result.focus = this.cm.state.focused
  7463. return result
  7464. },
  7465. showSelection: function(info, takeFocus) {
  7466. if (!info || !this.cm.display.view.length) { return }
  7467. if (info.focus || takeFocus) { this.showPrimarySelection() }
  7468. this.showMultipleSelections(info)
  7469. },
  7470. showPrimarySelection: function() {
  7471. var sel = window.getSelection(), prim = this.cm.doc.sel.primary()
  7472. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset)
  7473. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset)
  7474. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7475. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  7476. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  7477. { return }
  7478. var start = posToDOM(this.cm, prim.from())
  7479. var end = posToDOM(this.cm, prim.to())
  7480. if (!start && !end) { return }
  7481. var view = this.cm.display.view
  7482. var old = sel.rangeCount && sel.getRangeAt(0)
  7483. if (!start) {
  7484. start = {node: view[0].measure.map[2], offset: 0}
  7485. } else if (!end) { // FIXME dangerously hacky
  7486. var measure = view[view.length - 1].measure
  7487. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  7488. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}
  7489. }
  7490. var rng
  7491. try { rng = range(start.node, start.offset, end.offset, end.node) }
  7492. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7493. if (rng) {
  7494. if (!gecko && this.cm.state.focused) {
  7495. sel.collapse(start.node, start.offset)
  7496. if (!rng.collapsed) {
  7497. sel.removeAllRanges()
  7498. sel.addRange(rng)
  7499. }
  7500. } else {
  7501. sel.removeAllRanges()
  7502. sel.addRange(rng)
  7503. }
  7504. if (old && sel.anchorNode == null) { sel.addRange(old) }
  7505. else if (gecko) { this.startGracePeriod() }
  7506. }
  7507. this.rememberSelection()
  7508. },
  7509. startGracePeriod: function() {
  7510. var this$1 = this;
  7511. clearTimeout(this.gracePeriod)
  7512. this.gracePeriod = setTimeout(function () {
  7513. this$1.gracePeriod = false
  7514. if (this$1.selectionChanged())
  7515. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
  7516. }, 20)
  7517. },
  7518. showMultipleSelections: function(info) {
  7519. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  7520. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  7521. },
  7522. rememberSelection: function() {
  7523. var sel = window.getSelection()
  7524. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  7525. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  7526. },
  7527. selectionInEditor: function() {
  7528. var sel = window.getSelection()
  7529. if (!sel.rangeCount) { return false }
  7530. var node = sel.getRangeAt(0).commonAncestorContainer
  7531. return contains(this.div, node)
  7532. },
  7533. focus: function() {
  7534. if (this.cm.options.readOnly != "nocursor") {
  7535. if (!this.selectionInEditor())
  7536. { this.showSelection(this.prepareSelection(), true) }
  7537. this.div.focus()
  7538. }
  7539. },
  7540. blur: function() { this.div.blur() },
  7541. getField: function() { return this.div },
  7542. supportsTouch: function() { return true },
  7543. receivedFocus: function() {
  7544. var input = this
  7545. if (this.selectionInEditor())
  7546. { this.pollSelection() }
  7547. else
  7548. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
  7549. function poll() {
  7550. if (input.cm.state.focused) {
  7551. input.pollSelection()
  7552. input.polling.set(input.cm.options.pollInterval, poll)
  7553. }
  7554. }
  7555. this.polling.set(this.cm.options.pollInterval, poll)
  7556. },
  7557. selectionChanged: function() {
  7558. var sel = window.getSelection()
  7559. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7560. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  7561. },
  7562. pollSelection: function() {
  7563. if (!this.composing && this.readDOMTimeout == null && !this.gracePeriod && this.selectionChanged()) {
  7564. var sel = window.getSelection(), cm = this.cm
  7565. this.rememberSelection()
  7566. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7567. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  7568. if (anchor && head) { runInOp(cm, function () {
  7569. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  7570. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
  7571. }) }
  7572. }
  7573. },
  7574. pollContent: function() {
  7575. if (this.readDOMTimeout != null) {
  7576. clearTimeout(this.readDOMTimeout)
  7577. this.readDOMTimeout = null
  7578. }
  7579. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  7580. var from = sel.from(), to = sel.to()
  7581. if (from.ch == 0 && from.line > cm.firstLine())
  7582. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
  7583. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  7584. { to = Pos(to.line + 1, 0) }
  7585. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  7586. var fromIndex, fromLine, fromNode
  7587. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  7588. fromLine = lineNo(display.view[0].line)
  7589. fromNode = display.view[0].node
  7590. } else {
  7591. fromLine = lineNo(display.view[fromIndex].line)
  7592. fromNode = display.view[fromIndex - 1].node.nextSibling
  7593. }
  7594. var toIndex = findViewIndex(cm, to.line)
  7595. var toLine, toNode
  7596. if (toIndex == display.view.length - 1) {
  7597. toLine = display.viewTo - 1
  7598. toNode = display.lineDiv.lastChild
  7599. } else {
  7600. toLine = lineNo(display.view[toIndex + 1].line) - 1
  7601. toNode = display.view[toIndex + 1].node.previousSibling
  7602. }
  7603. if (!fromNode) { return false }
  7604. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  7605. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  7606. while (newText.length > 1 && oldText.length > 1) {
  7607. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  7608. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  7609. else { break }
  7610. }
  7611. var cutFront = 0, cutEnd = 0
  7612. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  7613. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  7614. { ++cutFront }
  7615. var newBot = lst(newText), oldBot = lst(oldText)
  7616. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  7617. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  7618. while (cutEnd < maxCutEnd &&
  7619. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  7620. { ++cutEnd }
  7621. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  7622. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  7623. var chFrom = Pos(fromLine, cutFront)
  7624. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  7625. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  7626. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  7627. return true
  7628. }
  7629. },
  7630. ensurePolled: function() {
  7631. this.forceCompositionEnd()
  7632. },
  7633. reset: function() {
  7634. this.forceCompositionEnd()
  7635. },
  7636. forceCompositionEnd: function() {
  7637. if (!this.composing) { return }
  7638. this.composing = null
  7639. if (!this.pollContent()) { regChange(this.cm) }
  7640. this.div.blur()
  7641. this.div.focus()
  7642. },
  7643. readFromDOMSoon: function() {
  7644. var this$1 = this;
  7645. if (this.readDOMTimeout != null) { return }
  7646. this.readDOMTimeout = setTimeout(function () {
  7647. this$1.readDOMTimeout = null
  7648. if (this$1.composing) { return }
  7649. if (this$1.cm.isReadOnly() || !this$1.pollContent())
  7650. { runInOp(this$1.cm, function () { return regChange(this$1.cm); }) }
  7651. }, 80)
  7652. },
  7653. setUneditable: function(node) {
  7654. node.contentEditable = "false"
  7655. },
  7656. onKeyPress: function(e) {
  7657. e.preventDefault()
  7658. if (!this.cm.isReadOnly())
  7659. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) }
  7660. },
  7661. readOnlyChanged: function(val) {
  7662. this.div.contentEditable = String(val != "nocursor")
  7663. },
  7664. onContextMenu: nothing,
  7665. resetPosition: nothing,
  7666. needsContentAttribute: true
  7667. }, ContentEditableInput.prototype)
  7668. function posToDOM(cm, pos) {
  7669. var view = findViewForLine(cm, pos.line)
  7670. if (!view || view.hidden) { return null }
  7671. var line = getLine(cm.doc, pos.line)
  7672. var info = mapFromLineView(view, line, pos.line)
  7673. var order = getOrder(line), side = "left"
  7674. if (order) {
  7675. var partPos = getBidiPartAt(order, pos.ch)
  7676. side = partPos % 2 ? "right" : "left"
  7677. }
  7678. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  7679. result.offset = result.collapse == "right" ? result.end : result.start
  7680. return result
  7681. }
  7682. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  7683. function domTextBetween(cm, from, to, fromLine, toLine) {
  7684. var text = "", closing = false, lineSep = cm.doc.lineSeparator()
  7685. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  7686. function walk(node) {
  7687. if (node.nodeType == 1) {
  7688. var cmText = node.getAttribute("cm-text")
  7689. if (cmText != null) {
  7690. if (cmText == "") { text += node.textContent.replace(/\u200b/g, "") }
  7691. else { text += cmText }
  7692. return
  7693. }
  7694. var markerID = node.getAttribute("cm-marker"), range$$1
  7695. if (markerID) {
  7696. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  7697. if (found.length && (range$$1 = found[0].find()))
  7698. { text += getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep) }
  7699. return
  7700. }
  7701. if (node.getAttribute("contenteditable") == "false") { return }
  7702. for (var i = 0; i < node.childNodes.length; i++)
  7703. { walk(node.childNodes[i]) }
  7704. if (/^(pre|div|p)$/i.test(node.nodeName))
  7705. { closing = true }
  7706. } else if (node.nodeType == 3) {
  7707. var val = node.nodeValue
  7708. if (!val) { return }
  7709. if (closing) {
  7710. text += lineSep
  7711. closing = false
  7712. }
  7713. text += val
  7714. }
  7715. }
  7716. for (;;) {
  7717. walk(from)
  7718. if (from == to) { break }
  7719. from = from.nextSibling
  7720. }
  7721. return text
  7722. }
  7723. function domToPos(cm, node, offset) {
  7724. var lineNode
  7725. if (node == cm.display.lineDiv) {
  7726. lineNode = cm.display.lineDiv.childNodes[offset]
  7727. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  7728. node = null; offset = 0
  7729. } else {
  7730. for (lineNode = node;; lineNode = lineNode.parentNode) {
  7731. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  7732. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  7733. }
  7734. }
  7735. for (var i = 0; i < cm.display.view.length; i++) {
  7736. var lineView = cm.display.view[i]
  7737. if (lineView.node == lineNode)
  7738. { return locateNodeInLineView(lineView, node, offset) }
  7739. }
  7740. }
  7741. function locateNodeInLineView(lineView, node, offset) {
  7742. var wrapper = lineView.text.firstChild, bad = false
  7743. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  7744. if (node == wrapper) {
  7745. bad = true
  7746. node = wrapper.childNodes[offset]
  7747. offset = 0
  7748. if (!node) {
  7749. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  7750. return badPos(Pos(lineNo(line), line.text.length), bad)
  7751. }
  7752. }
  7753. var textNode = node.nodeType == 3 ? node : null, topNode = node
  7754. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  7755. textNode = node.firstChild
  7756. if (offset) { offset = textNode.nodeValue.length }
  7757. }
  7758. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
  7759. var measure = lineView.measure, maps = measure.maps
  7760. function find(textNode, topNode, offset) {
  7761. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  7762. var map$$1 = i < 0 ? measure.map : maps[i]
  7763. for (var j = 0; j < map$$1.length; j += 3) {
  7764. var curNode = map$$1[j + 2]
  7765. if (curNode == textNode || curNode == topNode) {
  7766. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  7767. var ch = map$$1[j] + offset
  7768. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)] }
  7769. return Pos(line, ch)
  7770. }
  7771. }
  7772. }
  7773. }
  7774. var found = find(textNode, topNode, offset)
  7775. if (found) { return badPos(found, bad) }
  7776. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  7777. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  7778. found = find(after, after.firstChild, 0)
  7779. if (found)
  7780. { return badPos(Pos(found.line, found.ch - dist), bad) }
  7781. else
  7782. { dist += after.textContent.length }
  7783. }
  7784. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  7785. found = find(before, before.firstChild, -1)
  7786. if (found)
  7787. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  7788. else
  7789. { dist$1 += before.textContent.length }
  7790. }
  7791. }
  7792. // TEXTAREA INPUT STYLE
  7793. function TextareaInput(cm) {
  7794. this.cm = cm
  7795. // See input.poll and input.reset
  7796. this.prevInput = ""
  7797. // Flag that indicates whether we expect input to appear real soon
  7798. // now (after some event like 'keypress' or 'input') and are
  7799. // polling intensively.
  7800. this.pollingFast = false
  7801. // Self-resetting timeout for the poller
  7802. this.polling = new Delayed()
  7803. // Tracks when input.reset has punted to just putting a short
  7804. // string into the textarea instead of the full selection.
  7805. this.inaccurateSelection = false
  7806. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  7807. this.hasSelection = false
  7808. this.composing = null
  7809. }
  7810. TextareaInput.prototype = copyObj({
  7811. init: function(display) {
  7812. var this$1 = this;
  7813. var input = this, cm = this.cm
  7814. // Wraps and hides input textarea
  7815. var div = this.wrapper = hiddenTextarea()
  7816. // The semihidden textarea that is focused when the editor is
  7817. // focused, and receives input.
  7818. var te = this.textarea = div.firstChild
  7819. display.wrapper.insertBefore(div, display.wrapper.firstChild)
  7820. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  7821. if (ios) { te.style.width = "0px" }
  7822. on(te, "input", function () {
  7823. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
  7824. input.poll()
  7825. })
  7826. on(te, "paste", function (e) {
  7827. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7828. cm.state.pasteIncoming = true
  7829. input.fastPoll()
  7830. })
  7831. function prepareCopyCut(e) {
  7832. if (signalDOMEvent(cm, e)) { return }
  7833. if (cm.somethingSelected()) {
  7834. setLastCopied({lineWise: false, text: cm.getSelections()})
  7835. if (input.inaccurateSelection) {
  7836. input.prevInput = ""
  7837. input.inaccurateSelection = false
  7838. te.value = lastCopied.text.join("\n")
  7839. selectInput(te)
  7840. }
  7841. } else if (!cm.options.lineWiseCopyCut) {
  7842. return
  7843. } else {
  7844. var ranges = copyableRanges(cm)
  7845. setLastCopied({lineWise: true, text: ranges.text})
  7846. if (e.type == "cut") {
  7847. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  7848. } else {
  7849. input.prevInput = ""
  7850. te.value = ranges.text.join("\n")
  7851. selectInput(te)
  7852. }
  7853. }
  7854. if (e.type == "cut") { cm.state.cutIncoming = true }
  7855. }
  7856. on(te, "cut", prepareCopyCut)
  7857. on(te, "copy", prepareCopyCut)
  7858. on(display.scroller, "paste", function (e) {
  7859. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  7860. cm.state.pasteIncoming = true
  7861. input.focus()
  7862. })
  7863. // Prevent normal selection in the editor (we handle our own)
  7864. on(display.lineSpace, "selectstart", function (e) {
  7865. if (!eventInWidget(display, e)) { e_preventDefault(e) }
  7866. })
  7867. on(te, "compositionstart", function () {
  7868. var start = cm.getCursor("from")
  7869. if (input.composing) { input.composing.range.clear() }
  7870. input.composing = {
  7871. start: start,
  7872. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  7873. }
  7874. })
  7875. on(te, "compositionend", function () {
  7876. if (input.composing) {
  7877. input.poll()
  7878. input.composing.range.clear()
  7879. input.composing = null
  7880. }
  7881. })
  7882. },
  7883. prepareSelection: function() {
  7884. // Redraw the selection and/or cursor
  7885. var cm = this.cm, display = cm.display, doc = cm.doc
  7886. var result = prepareSelection(cm)
  7887. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  7888. if (cm.options.moveInputWithCursor) {
  7889. var headPos = cursorCoords(cm, doc.sel.primary().head, "div")
  7890. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()
  7891. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  7892. headPos.top + lineOff.top - wrapOff.top))
  7893. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  7894. headPos.left + lineOff.left - wrapOff.left))
  7895. }
  7896. return result
  7897. },
  7898. showSelection: function(drawn) {
  7899. var cm = this.cm, display = cm.display
  7900. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  7901. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  7902. if (drawn.teTop != null) {
  7903. this.wrapper.style.top = drawn.teTop + "px"
  7904. this.wrapper.style.left = drawn.teLeft + "px"
  7905. }
  7906. },
  7907. // Reset the input to correspond to the selection (or to be empty,
  7908. // when not typing and nothing is selected)
  7909. reset: function(typing) {
  7910. if (this.contextMenuPending) { return }
  7911. var minimal, selected, cm = this.cm, doc = cm.doc
  7912. if (cm.somethingSelected()) {
  7913. this.prevInput = ""
  7914. var range$$1 = doc.sel.primary()
  7915. minimal = hasCopyEvent &&
  7916. (range$$1.to().line - range$$1.from().line > 100 || (selected = cm.getSelection()).length > 1000)
  7917. var content = minimal ? "-" : selected || cm.getSelection()
  7918. this.textarea.value = content
  7919. if (cm.state.focused) { selectInput(this.textarea) }
  7920. if (ie && ie_version >= 9) { this.hasSelection = content }
  7921. } else if (!typing) {
  7922. this.prevInput = this.textarea.value = ""
  7923. if (ie && ie_version >= 9) { this.hasSelection = null }
  7924. }
  7925. this.inaccurateSelection = minimal
  7926. },
  7927. getField: function() { return this.textarea },
  7928. supportsTouch: function() { return false },
  7929. focus: function() {
  7930. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  7931. try { this.textarea.focus() }
  7932. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  7933. }
  7934. },
  7935. blur: function() { this.textarea.blur() },
  7936. resetPosition: function() {
  7937. this.wrapper.style.top = this.wrapper.style.left = 0
  7938. },
  7939. receivedFocus: function() { this.slowPoll() },
  7940. // Poll for input changes, using the normal rate of polling. This
  7941. // runs as long as the editor is focused.
  7942. slowPoll: function() {
  7943. var this$1 = this;
  7944. if (this.pollingFast) { return }
  7945. this.polling.set(this.cm.options.pollInterval, function () {
  7946. this$1.poll()
  7947. if (this$1.cm.state.focused) { this$1.slowPoll() }
  7948. })
  7949. },
  7950. // When an event has just come in that is likely to add or change
  7951. // something in the input textarea, we poll faster, to ensure that
  7952. // the change appears on the screen quickly.
  7953. fastPoll: function() {
  7954. var missed = false, input = this
  7955. input.pollingFast = true
  7956. function p() {
  7957. var changed = input.poll()
  7958. if (!changed && !missed) {missed = true; input.polling.set(60, p)}
  7959. else {input.pollingFast = false; input.slowPoll()}
  7960. }
  7961. input.polling.set(20, p)
  7962. },
  7963. // Read input from the textarea, and update the document to match.
  7964. // When something is selected, it is present in the textarea, and
  7965. // selected (unless it is huge, in which case a placeholder is
  7966. // used). When nothing is selected, the cursor sits after previously
  7967. // seen text (can be empty), which is stored in prevInput (we must
  7968. // not reset the textarea when typing, because that breaks IME).
  7969. poll: function() {
  7970. var this$1 = this;
  7971. var cm = this.cm, input = this.textarea, prevInput = this.prevInput
  7972. // Since this is called a *lot*, try to bail out as cheaply as
  7973. // possible when it is clear that nothing happened. hasSelection
  7974. // will be the case when there is a lot of text in the textarea,
  7975. // in which case reading its value would be expensive.
  7976. if (this.contextMenuPending || !cm.state.focused ||
  7977. (hasSelection(input) && !prevInput && !this.composing) ||
  7978. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  7979. { return false }
  7980. var text = input.value
  7981. // If nothing changed, bail.
  7982. if (text == prevInput && !cm.somethingSelected()) { return false }
  7983. // Work around nonsensical selection resetting in IE9/10, and
  7984. // inexplicable appearance of private area unicode characters on
  7985. // some key combos in Mac (#2689).
  7986. if (ie && ie_version >= 9 && this.hasSelection === text ||
  7987. mac && /[\uf700-\uf7ff]/.test(text)) {
  7988. cm.display.input.reset()
  7989. return false
  7990. }
  7991. if (cm.doc.sel == cm.display.selForContextMenu) {
  7992. var first = text.charCodeAt(0)
  7993. if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
  7994. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  7995. }
  7996. // Find the part of the input that is actually new
  7997. var same = 0, l = Math.min(prevInput.length, text.length)
  7998. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
  7999. runInOp(cm, function () {
  8000. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8001. null, this$1.composing ? "*compose" : null)
  8002. // Don't leave long text in the textarea, since it makes further polling slow
  8003. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
  8004. else { this$1.prevInput = text }
  8005. if (this$1.composing) {
  8006. this$1.composing.range.clear()
  8007. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8008. {className: "CodeMirror-composing"})
  8009. }
  8010. })
  8011. return true
  8012. },
  8013. ensurePolled: function() {
  8014. if (this.pollingFast && this.poll()) { this.pollingFast = false }
  8015. },
  8016. onKeyPress: function() {
  8017. if (ie && ie_version >= 9) { this.hasSelection = null }
  8018. this.fastPoll()
  8019. },
  8020. onContextMenu: function(e) {
  8021. var input = this, cm = input.cm, display = cm.display, te = input.textarea
  8022. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
  8023. if (!pos || presto) { return } // Opera is difficult.
  8024. // Reset the current text selection only if the click is done outside of the selection
  8025. // and 'resetSelectionOnContextMenu' option is true.
  8026. var reset = cm.options.resetSelectionOnContextMenu
  8027. if (reset && cm.doc.sel.contains(pos) == -1)
  8028. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
  8029. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
  8030. input.wrapper.style.cssText = "position: absolute"
  8031. var wrapperBox = input.wrapper.getBoundingClientRect()
  8032. 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);"
  8033. var oldScrollY
  8034. if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
  8035. display.input.focus()
  8036. if (webkit) { window.scrollTo(null, oldScrollY) }
  8037. display.input.reset()
  8038. // Adds "Select all" to context menu in FF
  8039. if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
  8040. input.contextMenuPending = true
  8041. display.selForContextMenu = cm.doc.sel
  8042. clearTimeout(display.detectingSelectAll)
  8043. // Select-all will be greyed out if there's nothing to select, so
  8044. // this adds a zero-width space so that we can later check whether
  8045. // it got selected.
  8046. function prepareSelectAllHack() {
  8047. if (te.selectionStart != null) {
  8048. var selected = cm.somethingSelected()
  8049. var extval = "\u200b" + (selected ? te.value : "")
  8050. te.value = "\u21da" // Used to catch context-menu undo
  8051. te.value = extval
  8052. input.prevInput = selected ? "" : "\u200b"
  8053. te.selectionStart = 1; te.selectionEnd = extval.length
  8054. // Re-set this, in case some other handler touched the
  8055. // selection in the meantime.
  8056. display.selForContextMenu = cm.doc.sel
  8057. }
  8058. }
  8059. function rehide() {
  8060. input.contextMenuPending = false
  8061. input.wrapper.style.cssText = oldWrapperCSS
  8062. te.style.cssText = oldCSS
  8063. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
  8064. // Try to detect the user choosing select-all
  8065. if (te.selectionStart != null) {
  8066. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
  8067. var i = 0, poll = function () {
  8068. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8069. te.selectionEnd > 0 && input.prevInput == "\u200b")
  8070. { operation(cm, selectAll)(cm) }
  8071. else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500) }
  8072. else { display.input.reset() }
  8073. }
  8074. display.detectingSelectAll = setTimeout(poll, 200)
  8075. }
  8076. }
  8077. if (ie && ie_version >= 9) { prepareSelectAllHack() }
  8078. if (captureRightClick) {
  8079. e_stop(e)
  8080. var mouseup = function () {
  8081. off(window, "mouseup", mouseup)
  8082. setTimeout(rehide, 20)
  8083. }
  8084. on(window, "mouseup", mouseup)
  8085. } else {
  8086. setTimeout(rehide, 50)
  8087. }
  8088. },
  8089. readOnlyChanged: function(val) {
  8090. if (!val) { this.reset() }
  8091. },
  8092. setUneditable: nothing,
  8093. needsContentAttribute: false
  8094. }, TextareaInput.prototype)
  8095. function fromTextArea(textarea, options) {
  8096. options = options ? copyObj(options) : {}
  8097. options.value = textarea.value
  8098. if (!options.tabindex && textarea.tabIndex)
  8099. { options.tabindex = textarea.tabIndex }
  8100. if (!options.placeholder && textarea.placeholder)
  8101. { options.placeholder = textarea.placeholder }
  8102. // Set autofocus to true if this textarea is focused, or if it has
  8103. // autofocus and no other element is focused.
  8104. if (options.autofocus == null) {
  8105. var hasFocus = activeElt()
  8106. options.autofocus = hasFocus == textarea ||
  8107. textarea.getAttribute("autofocus") != null && hasFocus == document.body
  8108. }
  8109. function save() {textarea.value = cm.getValue()}
  8110. var realSubmit
  8111. if (textarea.form) {
  8112. on(textarea.form, "submit", save)
  8113. // Deplorable hack to make the submit method do the right thing.
  8114. if (!options.leaveSubmitMethodAlone) {
  8115. var form = textarea.form
  8116. realSubmit = form.submit
  8117. try {
  8118. var wrappedSubmit = form.submit = function () {
  8119. save()
  8120. form.submit = realSubmit
  8121. form.submit()
  8122. form.submit = wrappedSubmit
  8123. }
  8124. } catch(e) {}
  8125. }
  8126. }
  8127. options.finishInit = function (cm) {
  8128. cm.save = save
  8129. cm.getTextArea = function () { return textarea; }
  8130. cm.toTextArea = function () {
  8131. cm.toTextArea = isNaN // Prevent this from being ran twice
  8132. save()
  8133. textarea.parentNode.removeChild(cm.getWrapperElement())
  8134. textarea.style.display = ""
  8135. if (textarea.form) {
  8136. off(textarea.form, "submit", save)
  8137. if (typeof textarea.form.submit == "function")
  8138. { textarea.form.submit = realSubmit }
  8139. }
  8140. }
  8141. }
  8142. textarea.style.display = "none"
  8143. var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8144. options)
  8145. return cm
  8146. }
  8147. function addLegacyProps(CodeMirror) {
  8148. CodeMirror.off = off
  8149. CodeMirror.on = on
  8150. CodeMirror.wheelEventPixels = wheelEventPixels
  8151. CodeMirror.Doc = Doc
  8152. CodeMirror.splitLines = splitLinesAuto
  8153. CodeMirror.countColumn = countColumn
  8154. CodeMirror.findColumn = findColumn
  8155. CodeMirror.isWordChar = isWordCharBasic
  8156. CodeMirror.Pass = Pass
  8157. CodeMirror.signal = signal
  8158. CodeMirror.Line = Line
  8159. CodeMirror.changeEnd = changeEnd
  8160. CodeMirror.scrollbarModel = scrollbarModel
  8161. CodeMirror.Pos = Pos
  8162. CodeMirror.cmpPos = cmp
  8163. CodeMirror.modes = modes
  8164. CodeMirror.mimeModes = mimeModes
  8165. CodeMirror.resolveMode = resolveMode
  8166. CodeMirror.getMode = getMode
  8167. CodeMirror.modeExtensions = modeExtensions
  8168. CodeMirror.extendMode = extendMode
  8169. CodeMirror.copyState = copyState
  8170. CodeMirror.startState = startState
  8171. CodeMirror.innerMode = innerMode
  8172. CodeMirror.commands = commands
  8173. CodeMirror.keyMap = keyMap
  8174. CodeMirror.keyName = keyName
  8175. CodeMirror.isModifierKey = isModifierKey
  8176. CodeMirror.lookupKey = lookupKey
  8177. CodeMirror.normalizeKeyMap = normalizeKeyMap
  8178. CodeMirror.StringStream = StringStream
  8179. CodeMirror.SharedTextMarker = SharedTextMarker
  8180. CodeMirror.TextMarker = TextMarker
  8181. CodeMirror.LineWidget = LineWidget
  8182. CodeMirror.e_preventDefault = e_preventDefault
  8183. CodeMirror.e_stopPropagation = e_stopPropagation
  8184. CodeMirror.e_stop = e_stop
  8185. CodeMirror.addClass = addClass
  8186. CodeMirror.contains = contains
  8187. CodeMirror.rmClass = rmClass
  8188. CodeMirror.keyNames = keyNames
  8189. }
  8190. // EDITOR CONSTRUCTOR
  8191. defineOptions(CodeMirror$1)
  8192. addEditorMethods(CodeMirror$1)
  8193. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8194. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ")
  8195. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8196. { CodeMirror$1.prototype[prop] = (function(method) {
  8197. return function() {return method.apply(this.doc, arguments)}
  8198. })(Doc.prototype[prop]) } }
  8199. eventMixin(Doc)
  8200. // INPUT HANDLING
  8201. CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
  8202. // MODE DEFINITION AND QUERYING
  8203. // Extra arguments are stored as the mode's dependencies, which is
  8204. // used by (legacy) mechanisms like loadmode.js to automatically
  8205. // load a mode. (Preferred mechanism is the require/define calls.)
  8206. CodeMirror$1.defineMode = function(name/*, mode, …*/) {
  8207. if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name }
  8208. defineMode.apply(this, arguments)
  8209. }
  8210. CodeMirror$1.defineMIME = defineMIME
  8211. // Minimal default mode.
  8212. CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
  8213. CodeMirror$1.defineMIME("text/plain", "null")
  8214. // EXTENSIONS
  8215. CodeMirror$1.defineExtension = function (name, func) {
  8216. CodeMirror$1.prototype[name] = func
  8217. }
  8218. CodeMirror$1.defineDocExtension = function (name, func) {
  8219. Doc.prototype[name] = func
  8220. }
  8221. CodeMirror$1.fromTextArea = fromTextArea
  8222. addLegacyProps(CodeMirror$1)
  8223. CodeMirror$1.version = "5.21.0"
  8224. return CodeMirror$1;
  8225. })));