Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

codemirror.js 389KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // This is CodeMirror (https://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global = global || self, global.CodeMirror = factory());
  12. }(this, (function () { '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 edge = /Edge\/(\d+)/.exec(userAgent);
  21. var ie = ie_upto10 || ie_11up || edge;
  22. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  23. var webkit = !edge && /WebKit\//.test(userAgent);
  24. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  25. var chrome = !edge && /Chrome\//.test(userAgent);
  26. var presto = /Opera\//.test(userAgent);
  27. var safari = /Apple Computer/.test(navigator.vendor);
  28. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  29. var phantom = /PhantomJS/.test(userAgent);
  30. var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  31. var android = /Android/.test(userAgent);
  32. // This is woefully incomplete. Suggestions for alternative methods welcome.
  33. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  34. var mac = ios || /Mac/.test(platform);
  35. var chromeOS = /\bCrOS\b/.test(userAgent);
  36. var windows = /win/i.test(platform);
  37. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  38. if (presto_version) { presto_version = Number(presto_version[1]); }
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  42. var captureRightClick = gecko || (ie && ie_version >= 9);
  43. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  44. var rmClass = function(node, cls) {
  45. var current = node.className;
  46. var match = classTest(cls).exec(current);
  47. if (match) {
  48. var after = current.slice(match.index + match[0].length);
  49. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  50. }
  51. };
  52. function removeChildren(e) {
  53. for (var count = e.childNodes.length; count > 0; --count)
  54. { e.removeChild(e.firstChild); }
  55. return e
  56. }
  57. function removeChildrenAndAdd(parent, e) {
  58. return removeChildren(parent).appendChild(e)
  59. }
  60. function elt(tag, content, className, style) {
  61. var e = document.createElement(tag);
  62. if (className) { e.className = className; }
  63. if (style) { e.style.cssText = style; }
  64. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  65. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  66. return e
  67. }
  68. // wrapper for elt, which removes the elt from the accessibility tree
  69. function eltP(tag, content, className, style) {
  70. var e = elt(tag, content, className, style);
  71. e.setAttribute("role", "presentation");
  72. return e
  73. }
  74. var range;
  75. if (document.createRange) { range = function(node, start, end, endNode) {
  76. var r = document.createRange();
  77. r.setEnd(endNode || node, end);
  78. r.setStart(node, start);
  79. return r
  80. }; }
  81. else { range = function(node, start, end) {
  82. var r = document.body.createTextRange();
  83. try { r.moveToElementText(node.parentNode); }
  84. catch(e) { return r }
  85. r.collapse(true);
  86. r.moveEnd("character", end);
  87. r.moveStart("character", start);
  88. return r
  89. }; }
  90. function contains(parent, child) {
  91. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  92. { child = child.parentNode; }
  93. if (parent.contains)
  94. { return parent.contains(child) }
  95. do {
  96. if (child.nodeType == 11) { child = child.host; }
  97. if (child == parent) { return true }
  98. } while (child = child.parentNode)
  99. }
  100. function activeElt() {
  101. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  102. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  103. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  104. var activeElement;
  105. try {
  106. activeElement = document.activeElement;
  107. } catch(e) {
  108. activeElement = document.body || null;
  109. }
  110. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  111. { activeElement = activeElement.shadowRoot.activeElement; }
  112. return activeElement
  113. }
  114. function addClass(node, cls) {
  115. var current = node.className;
  116. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  117. }
  118. function joinClasses(a, b) {
  119. var as = a.split(" ");
  120. for (var i = 0; i < as.length; i++)
  121. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  122. return b
  123. }
  124. var selectInput = function(node) { node.select(); };
  125. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  126. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  127. else if (ie) // Suppress mysterious IE10 errors
  128. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  129. function bind(f) {
  130. var args = Array.prototype.slice.call(arguments, 1);
  131. return function(){return f.apply(null, args)}
  132. }
  133. function copyObj(obj, target, overwrite) {
  134. if (!target) { target = {}; }
  135. for (var prop in obj)
  136. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  137. { target[prop] = obj[prop]; } }
  138. return target
  139. }
  140. // Counts the column offset in a string, taking tabs into account.
  141. // Used mostly to find indentation.
  142. function countColumn(string, end, tabSize, startIndex, startValue) {
  143. if (end == null) {
  144. end = string.search(/[^\s\u00a0]/);
  145. if (end == -1) { end = string.length; }
  146. }
  147. for (var i = startIndex || 0, n = startValue || 0;;) {
  148. var nextTab = string.indexOf("\t", i);
  149. if (nextTab < 0 || nextTab >= end)
  150. { return n + (end - i) }
  151. n += nextTab - i;
  152. n += tabSize - (n % tabSize);
  153. i = nextTab + 1;
  154. }
  155. }
  156. var Delayed = function() {
  157. this.id = null;
  158. this.f = null;
  159. this.time = 0;
  160. this.handler = bind(this.onTimeout, this);
  161. };
  162. Delayed.prototype.onTimeout = function (self) {
  163. self.id = 0;
  164. if (self.time <= +new Date) {
  165. self.f();
  166. } else {
  167. setTimeout(self.handler, self.time - +new Date);
  168. }
  169. };
  170. Delayed.prototype.set = function (ms, f) {
  171. this.f = f;
  172. var time = +new Date + ms;
  173. if (!this.id || time < this.time) {
  174. clearTimeout(this.id);
  175. this.id = setTimeout(this.handler, ms);
  176. this.time = time;
  177. }
  178. };
  179. function indexOf(array, elt) {
  180. for (var i = 0; i < array.length; ++i)
  181. { if (array[i] == elt) { return i } }
  182. return -1
  183. }
  184. // Number of pixels added to scroller and sizer to hide scrollbar
  185. var scrollerGap = 50;
  186. // Returned or thrown by various protocols to signal 'I'm not
  187. // handling this'.
  188. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  189. // Reused option objects for setSelection & friends
  190. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  191. // The inverse of countColumn -- find the offset that corresponds to
  192. // a particular column.
  193. function findColumn(string, goal, tabSize) {
  194. for (var pos = 0, col = 0;;) {
  195. var nextTab = string.indexOf("\t", pos);
  196. if (nextTab == -1) { nextTab = string.length; }
  197. var skipped = nextTab - pos;
  198. if (nextTab == string.length || col + skipped >= goal)
  199. { return pos + Math.min(skipped, goal - col) }
  200. col += nextTab - pos;
  201. col += tabSize - (col % tabSize);
  202. pos = nextTab + 1;
  203. if (col >= goal) { return pos }
  204. }
  205. }
  206. var spaceStrs = [""];
  207. function spaceStr(n) {
  208. while (spaceStrs.length <= n)
  209. { spaceStrs.push(lst(spaceStrs) + " "); }
  210. return spaceStrs[n]
  211. }
  212. function lst(arr) { return arr[arr.length-1] }
  213. function map(array, f) {
  214. var out = [];
  215. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  216. return out
  217. }
  218. function insertSorted(array, value, score) {
  219. var pos = 0, priority = score(value);
  220. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  221. array.splice(pos, 0, value);
  222. }
  223. function nothing() {}
  224. function createObj(base, props) {
  225. var inst;
  226. if (Object.create) {
  227. inst = Object.create(base);
  228. } else {
  229. nothing.prototype = base;
  230. inst = new nothing();
  231. }
  232. if (props) { copyObj(props, inst); }
  233. return inst
  234. }
  235. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  236. function isWordCharBasic(ch) {
  237. return /\w/.test(ch) || ch > "\x80" &&
  238. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  239. }
  240. function isWordChar(ch, helper) {
  241. if (!helper) { return isWordCharBasic(ch) }
  242. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  243. return helper.test(ch)
  244. }
  245. function isEmpty(obj) {
  246. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  247. return true
  248. }
  249. // Extending unicode characters. A series of a non-extending char +
  250. // any number of extending chars is treated as a single unit as far
  251. // as editing and measuring is concerned. This is not fully correct,
  252. // since some scripts/fonts/browsers also treat other configurations
  253. // of code points as a group.
  254. 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]/;
  255. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  256. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  257. function skipExtendingChars(str, pos, dir) {
  258. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  259. return pos
  260. }
  261. // Returns the value from the range [`from`; `to`] that satisfies
  262. // `pred` and is closest to `from`. Assumes that at least `to`
  263. // satisfies `pred`. Supports `from` being greater than `to`.
  264. function findFirst(pred, from, to) {
  265. // At any point we are certain `to` satisfies `pred`, don't know
  266. // whether `from` does.
  267. var dir = from > to ? -1 : 1;
  268. for (;;) {
  269. if (from == to) { return from }
  270. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  271. if (mid == from) { return pred(mid) ? from : to }
  272. if (pred(mid)) { to = mid; }
  273. else { from = mid + dir; }
  274. }
  275. }
  276. // BIDI HELPERS
  277. function iterateBidiSections(order, from, to, f) {
  278. if (!order) { return f(from, to, "ltr", 0) }
  279. var found = false;
  280. for (var i = 0; i < order.length; ++i) {
  281. var part = order[i];
  282. if (part.from < to && part.to > from || from == to && part.to == from) {
  283. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  284. found = true;
  285. }
  286. }
  287. if (!found) { f(from, to, "ltr"); }
  288. }
  289. var bidiOther = null;
  290. function getBidiPartAt(order, ch, sticky) {
  291. var found;
  292. bidiOther = null;
  293. for (var i = 0; i < order.length; ++i) {
  294. var cur = order[i];
  295. if (cur.from < ch && cur.to > ch) { return i }
  296. if (cur.to == ch) {
  297. if (cur.from != cur.to && sticky == "before") { found = i; }
  298. else { bidiOther = i; }
  299. }
  300. if (cur.from == ch) {
  301. if (cur.from != cur.to && sticky != "before") { found = i; }
  302. else { bidiOther = i; }
  303. }
  304. }
  305. return found != null ? found : bidiOther
  306. }
  307. // Bidirectional ordering algorithm
  308. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  309. // that this (partially) implements.
  310. // One-char codes used for character types:
  311. // L (L): Left-to-Right
  312. // R (R): Right-to-Left
  313. // r (AL): Right-to-Left Arabic
  314. // 1 (EN): European Number
  315. // + (ES): European Number Separator
  316. // % (ET): European Number Terminator
  317. // n (AN): Arabic Number
  318. // , (CS): Common Number Separator
  319. // m (NSM): Non-Spacing Mark
  320. // b (BN): Boundary Neutral
  321. // s (B): Paragraph Separator
  322. // t (S): Segment Separator
  323. // w (WS): Whitespace
  324. // N (ON): Other Neutrals
  325. // Returns null if characters are ordered as they appear
  326. // (left-to-right), or an array of sections ({from, to, level}
  327. // objects) in the order in which they occur visually.
  328. var bidiOrdering = (function() {
  329. // Character types for codepoints 0 to 0xff
  330. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  331. // Character types for codepoints 0x600 to 0x6f9
  332. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  333. function charType(code) {
  334. if (code <= 0xf7) { return lowTypes.charAt(code) }
  335. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  336. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  337. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  338. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  339. else if (code == 0x200c) { return "b" }
  340. else { return "L" }
  341. }
  342. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  343. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  344. function BidiSpan(level, from, to) {
  345. this.level = level;
  346. this.from = from; this.to = to;
  347. }
  348. return function(str, direction) {
  349. var outerType = direction == "ltr" ? "L" : "R";
  350. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  351. var len = str.length, types = [];
  352. for (var i = 0; i < len; ++i)
  353. { types.push(charType(str.charCodeAt(i))); }
  354. // W1. Examine each non-spacing mark (NSM) in the level run, and
  355. // change the type of the NSM to the type of the previous
  356. // character. If the NSM is at the start of the level run, it will
  357. // get the type of sor.
  358. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  359. var type = types[i$1];
  360. if (type == "m") { types[i$1] = prev; }
  361. else { prev = type; }
  362. }
  363. // W2. Search backwards from each instance of a European number
  364. // until the first strong type (R, L, AL, or sor) is found. If an
  365. // AL is found, change the type of the European number to Arabic
  366. // number.
  367. // W3. Change all ALs to R.
  368. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  369. var type$1 = types[i$2];
  370. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  371. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  372. }
  373. // W4. A single European separator between two European numbers
  374. // changes to a European number. A single common separator between
  375. // two numbers of the same type changes to that type.
  376. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  377. var type$2 = types[i$3];
  378. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  379. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  380. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  381. prev$1 = type$2;
  382. }
  383. // W5. A sequence of European terminators adjacent to European
  384. // numbers changes to all European numbers.
  385. // W6. Otherwise, separators and terminators change to Other
  386. // Neutral.
  387. for (var i$4 = 0; i$4 < len; ++i$4) {
  388. var type$3 = types[i$4];
  389. if (type$3 == ",") { types[i$4] = "N"; }
  390. else if (type$3 == "%") {
  391. var end = (void 0);
  392. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  393. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  394. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  395. i$4 = end - 1;
  396. }
  397. }
  398. // W7. Search backwards from each instance of a European number
  399. // until the first strong type (R, L, or sor) is found. If an L is
  400. // found, then change the type of the European number to L.
  401. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  402. var type$4 = types[i$5];
  403. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  404. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  405. }
  406. // N1. A sequence of neutrals takes the direction of the
  407. // surrounding strong text if the text on both sides has the same
  408. // direction. European and Arabic numbers act as if they were R in
  409. // terms of their influence on neutrals. Start-of-level-run (sor)
  410. // and end-of-level-run (eor) are used at level run boundaries.
  411. // N2. Any remaining neutrals take the embedding direction.
  412. for (var i$6 = 0; i$6 < len; ++i$6) {
  413. if (isNeutral.test(types[i$6])) {
  414. var end$1 = (void 0);
  415. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  416. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  417. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  418. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  419. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  420. i$6 = end$1 - 1;
  421. }
  422. }
  423. // Here we depart from the documented algorithm, in order to avoid
  424. // building up an actual levels array. Since there are only three
  425. // levels (0, 1, 2) in an implementation that doesn't take
  426. // explicit embedding into account, we can build up the order on
  427. // the fly, without following the level-based algorithm.
  428. var order = [], m;
  429. for (var i$7 = 0; i$7 < len;) {
  430. if (countsAsLeft.test(types[i$7])) {
  431. var start = i$7;
  432. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  433. order.push(new BidiSpan(0, start, i$7));
  434. } else {
  435. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  436. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  437. for (var j$2 = pos; j$2 < i$7;) {
  438. if (countsAsNum.test(types[j$2])) {
  439. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  440. var nstart = j$2;
  441. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  442. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  443. at += isRTL;
  444. pos = j$2;
  445. } else { ++j$2; }
  446. }
  447. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  448. }
  449. }
  450. if (direction == "ltr") {
  451. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  452. order[0].from = m[0].length;
  453. order.unshift(new BidiSpan(0, 0, m[0].length));
  454. }
  455. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  456. lst(order).to -= m[0].length;
  457. order.push(new BidiSpan(0, len - m[0].length, len));
  458. }
  459. }
  460. return direction == "rtl" ? order.reverse() : order
  461. }
  462. })();
  463. // Get the bidi ordering for the given line (and cache it). Returns
  464. // false for lines that are fully left-to-right, and an array of
  465. // BidiSpan objects otherwise.
  466. function getOrder(line, direction) {
  467. var order = line.order;
  468. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  469. return order
  470. }
  471. // EVENT HANDLING
  472. // Lightweight event framework. on/off also work on DOM nodes,
  473. // registering native DOM handlers.
  474. var noHandlers = [];
  475. var on = function(emitter, type, f) {
  476. if (emitter.addEventListener) {
  477. emitter.addEventListener(type, f, false);
  478. } else if (emitter.attachEvent) {
  479. emitter.attachEvent("on" + type, f);
  480. } else {
  481. var map = emitter._handlers || (emitter._handlers = {});
  482. map[type] = (map[type] || noHandlers).concat(f);
  483. }
  484. };
  485. function getHandlers(emitter, type) {
  486. return emitter._handlers && emitter._handlers[type] || noHandlers
  487. }
  488. function off(emitter, type, f) {
  489. if (emitter.removeEventListener) {
  490. emitter.removeEventListener(type, f, false);
  491. } else if (emitter.detachEvent) {
  492. emitter.detachEvent("on" + type, f);
  493. } else {
  494. var map = emitter._handlers, arr = map && map[type];
  495. if (arr) {
  496. var index = indexOf(arr, f);
  497. if (index > -1)
  498. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  499. }
  500. }
  501. }
  502. function signal(emitter, type /*, values...*/) {
  503. var handlers = getHandlers(emitter, type);
  504. if (!handlers.length) { return }
  505. var args = Array.prototype.slice.call(arguments, 2);
  506. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  507. }
  508. // The DOM events that CodeMirror handles can be overridden by
  509. // registering a (non-DOM) handler on the editor for the event name,
  510. // and preventDefault-ing the event in that handler.
  511. function signalDOMEvent(cm, e, override) {
  512. if (typeof e == "string")
  513. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  514. signal(cm, override || e.type, cm, e);
  515. return e_defaultPrevented(e) || e.codemirrorIgnore
  516. }
  517. function signalCursorActivity(cm) {
  518. var arr = cm._handlers && cm._handlers.cursorActivity;
  519. if (!arr) { return }
  520. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  521. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  522. { set.push(arr[i]); } }
  523. }
  524. function hasHandler(emitter, type) {
  525. return getHandlers(emitter, type).length > 0
  526. }
  527. // Add on and off methods to a constructor's prototype, to make
  528. // registering events on such objects more convenient.
  529. function eventMixin(ctor) {
  530. ctor.prototype.on = function(type, f) {on(this, type, f);};
  531. ctor.prototype.off = function(type, f) {off(this, type, f);};
  532. }
  533. // Due to the fact that we still support jurassic IE versions, some
  534. // compatibility wrappers are needed.
  535. function e_preventDefault(e) {
  536. if (e.preventDefault) { e.preventDefault(); }
  537. else { e.returnValue = false; }
  538. }
  539. function e_stopPropagation(e) {
  540. if (e.stopPropagation) { e.stopPropagation(); }
  541. else { e.cancelBubble = true; }
  542. }
  543. function e_defaultPrevented(e) {
  544. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  545. }
  546. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  547. function e_target(e) {return e.target || e.srcElement}
  548. function e_button(e) {
  549. var b = e.which;
  550. if (b == null) {
  551. if (e.button & 1) { b = 1; }
  552. else if (e.button & 2) { b = 3; }
  553. else if (e.button & 4) { b = 2; }
  554. }
  555. if (mac && e.ctrlKey && b == 1) { b = 3; }
  556. return b
  557. }
  558. // Detect drag-and-drop
  559. var dragAndDrop = function() {
  560. // There is *some* kind of drag-and-drop support in IE6-8, but I
  561. // couldn't get it to work yet.
  562. if (ie && ie_version < 9) { return false }
  563. var div = elt('div');
  564. return "draggable" in div || "dragDrop" in div
  565. }();
  566. var zwspSupported;
  567. function zeroWidthElement(measure) {
  568. if (zwspSupported == null) {
  569. var test = elt("span", "\u200b");
  570. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  571. if (measure.firstChild.offsetHeight != 0)
  572. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  573. }
  574. var node = zwspSupported ? elt("span", "\u200b") :
  575. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  576. node.setAttribute("cm-text", "");
  577. return node
  578. }
  579. // Feature-detect IE's crummy client rect reporting for bidi text
  580. var badBidiRects;
  581. function hasBadBidiRects(measure) {
  582. if (badBidiRects != null) { return badBidiRects }
  583. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  584. var r0 = range(txt, 0, 1).getBoundingClientRect();
  585. var r1 = range(txt, 1, 2).getBoundingClientRect();
  586. removeChildren(measure);
  587. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  588. return badBidiRects = (r1.right - r0.right < 3)
  589. }
  590. // See if "".split is the broken IE version, if so, provide an
  591. // alternative way to split lines.
  592. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  593. var pos = 0, result = [], l = string.length;
  594. while (pos <= l) {
  595. var nl = string.indexOf("\n", pos);
  596. if (nl == -1) { nl = string.length; }
  597. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  598. var rt = line.indexOf("\r");
  599. if (rt != -1) {
  600. result.push(line.slice(0, rt));
  601. pos += rt + 1;
  602. } else {
  603. result.push(line);
  604. pos = nl + 1;
  605. }
  606. }
  607. return result
  608. } : function (string) { return string.split(/\r\n?|\n/); };
  609. var hasSelection = window.getSelection ? function (te) {
  610. try { return te.selectionStart != te.selectionEnd }
  611. catch(e) { return false }
  612. } : function (te) {
  613. var range;
  614. try {range = te.ownerDocument.selection.createRange();}
  615. catch(e) {}
  616. if (!range || range.parentElement() != te) { return false }
  617. return range.compareEndPoints("StartToEnd", range) != 0
  618. };
  619. var hasCopyEvent = (function () {
  620. var e = elt("div");
  621. if ("oncopy" in e) { return true }
  622. e.setAttribute("oncopy", "return;");
  623. return typeof e.oncopy == "function"
  624. })();
  625. var badZoomedRects = null;
  626. function hasBadZoomedRects(measure) {
  627. if (badZoomedRects != null) { return badZoomedRects }
  628. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  629. var normal = node.getBoundingClientRect();
  630. var fromRange = range(node, 0, 1).getBoundingClientRect();
  631. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  632. }
  633. // Known modes, by name and by MIME
  634. var modes = {}, mimeModes = {};
  635. // Extra arguments are stored as the mode's dependencies, which is
  636. // used by (legacy) mechanisms like loadmode.js to automatically
  637. // load a mode. (Preferred mechanism is the require/define calls.)
  638. function defineMode(name, mode) {
  639. if (arguments.length > 2)
  640. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  641. modes[name] = mode;
  642. }
  643. function defineMIME(mime, spec) {
  644. mimeModes[mime] = spec;
  645. }
  646. // Given a MIME type, a {name, ...options} config object, or a name
  647. // string, return a mode config object.
  648. function resolveMode(spec) {
  649. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  650. spec = mimeModes[spec];
  651. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  652. var found = mimeModes[spec.name];
  653. if (typeof found == "string") { found = {name: found}; }
  654. spec = createObj(found, spec);
  655. spec.name = found.name;
  656. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  657. return resolveMode("application/xml")
  658. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  659. return resolveMode("application/json")
  660. }
  661. if (typeof spec == "string") { return {name: spec} }
  662. else { return spec || {name: "null"} }
  663. }
  664. // Given a mode spec (anything that resolveMode accepts), find and
  665. // initialize an actual mode object.
  666. function getMode(options, spec) {
  667. spec = resolveMode(spec);
  668. var mfactory = modes[spec.name];
  669. if (!mfactory) { return getMode(options, "text/plain") }
  670. var modeObj = mfactory(options, spec);
  671. if (modeExtensions.hasOwnProperty(spec.name)) {
  672. var exts = modeExtensions[spec.name];
  673. for (var prop in exts) {
  674. if (!exts.hasOwnProperty(prop)) { continue }
  675. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  676. modeObj[prop] = exts[prop];
  677. }
  678. }
  679. modeObj.name = spec.name;
  680. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  681. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  682. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  683. return modeObj
  684. }
  685. // This can be used to attach properties to mode objects from
  686. // outside the actual mode definition.
  687. var modeExtensions = {};
  688. function extendMode(mode, properties) {
  689. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  690. copyObj(properties, exts);
  691. }
  692. function copyState(mode, state) {
  693. if (state === true) { return state }
  694. if (mode.copyState) { return mode.copyState(state) }
  695. var nstate = {};
  696. for (var n in state) {
  697. var val = state[n];
  698. if (val instanceof Array) { val = val.concat([]); }
  699. nstate[n] = val;
  700. }
  701. return nstate
  702. }
  703. // Given a mode and a state (for that mode), find the inner mode and
  704. // state at the position that the state refers to.
  705. function innerMode(mode, state) {
  706. var info;
  707. while (mode.innerMode) {
  708. info = mode.innerMode(state);
  709. if (!info || info.mode == mode) { break }
  710. state = info.state;
  711. mode = info.mode;
  712. }
  713. return info || {mode: mode, state: state}
  714. }
  715. function startState(mode, a1, a2) {
  716. return mode.startState ? mode.startState(a1, a2) : true
  717. }
  718. // STRING STREAM
  719. // Fed to the mode parsers, provides helper functions to make
  720. // parsers more succinct.
  721. var StringStream = function(string, tabSize, lineOracle) {
  722. this.pos = this.start = 0;
  723. this.string = string;
  724. this.tabSize = tabSize || 8;
  725. this.lastColumnPos = this.lastColumnValue = 0;
  726. this.lineStart = 0;
  727. this.lineOracle = lineOracle;
  728. };
  729. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  730. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  731. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  732. StringStream.prototype.next = function () {
  733. if (this.pos < this.string.length)
  734. { return this.string.charAt(this.pos++) }
  735. };
  736. StringStream.prototype.eat = function (match) {
  737. var ch = this.string.charAt(this.pos);
  738. var ok;
  739. if (typeof match == "string") { ok = ch == match; }
  740. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  741. if (ok) {++this.pos; return ch}
  742. };
  743. StringStream.prototype.eatWhile = function (match) {
  744. var start = this.pos;
  745. while (this.eat(match)){}
  746. return this.pos > start
  747. };
  748. StringStream.prototype.eatSpace = function () {
  749. var start = this.pos;
  750. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  751. return this.pos > start
  752. };
  753. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  754. StringStream.prototype.skipTo = function (ch) {
  755. var found = this.string.indexOf(ch, this.pos);
  756. if (found > -1) {this.pos = found; return true}
  757. };
  758. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  759. StringStream.prototype.column = function () {
  760. if (this.lastColumnPos < this.start) {
  761. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  762. this.lastColumnPos = this.start;
  763. }
  764. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  765. };
  766. StringStream.prototype.indentation = function () {
  767. return countColumn(this.string, null, this.tabSize) -
  768. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  769. };
  770. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  771. if (typeof pattern == "string") {
  772. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  773. var substr = this.string.substr(this.pos, pattern.length);
  774. if (cased(substr) == cased(pattern)) {
  775. if (consume !== false) { this.pos += pattern.length; }
  776. return true
  777. }
  778. } else {
  779. var match = this.string.slice(this.pos).match(pattern);
  780. if (match && match.index > 0) { return null }
  781. if (match && consume !== false) { this.pos += match[0].length; }
  782. return match
  783. }
  784. };
  785. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  786. StringStream.prototype.hideFirstChars = function (n, inner) {
  787. this.lineStart += n;
  788. try { return inner() }
  789. finally { this.lineStart -= n; }
  790. };
  791. StringStream.prototype.lookAhead = function (n) {
  792. var oracle = this.lineOracle;
  793. return oracle && oracle.lookAhead(n)
  794. };
  795. StringStream.prototype.baseToken = function () {
  796. var oracle = this.lineOracle;
  797. return oracle && oracle.baseToken(this.pos)
  798. };
  799. // Find the line object corresponding to the given line number.
  800. function getLine(doc, n) {
  801. n -= doc.first;
  802. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  803. var chunk = doc;
  804. while (!chunk.lines) {
  805. for (var i = 0;; ++i) {
  806. var child = chunk.children[i], sz = child.chunkSize();
  807. if (n < sz) { chunk = child; break }
  808. n -= sz;
  809. }
  810. }
  811. return chunk.lines[n]
  812. }
  813. // Get the part of a document between two positions, as an array of
  814. // strings.
  815. function getBetween(doc, start, end) {
  816. var out = [], n = start.line;
  817. doc.iter(start.line, end.line + 1, function (line) {
  818. var text = line.text;
  819. if (n == end.line) { text = text.slice(0, end.ch); }
  820. if (n == start.line) { text = text.slice(start.ch); }
  821. out.push(text);
  822. ++n;
  823. });
  824. return out
  825. }
  826. // Get the lines between from and to, as array of strings.
  827. function getLines(doc, from, to) {
  828. var out = [];
  829. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  830. return out
  831. }
  832. // Update the height of a line, propagating the height change
  833. // upwards to parent nodes.
  834. function updateLineHeight(line, height) {
  835. var diff = height - line.height;
  836. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  837. }
  838. // Given a line object, find its line number by walking up through
  839. // its parent links.
  840. function lineNo(line) {
  841. if (line.parent == null) { return null }
  842. var cur = line.parent, no = indexOf(cur.lines, line);
  843. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  844. for (var i = 0;; ++i) {
  845. if (chunk.children[i] == cur) { break }
  846. no += chunk.children[i].chunkSize();
  847. }
  848. }
  849. return no + cur.first
  850. }
  851. // Find the line at the given vertical position, using the height
  852. // information in the document tree.
  853. function lineAtHeight(chunk, h) {
  854. var n = chunk.first;
  855. outer: do {
  856. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  857. var child = chunk.children[i$1], ch = child.height;
  858. if (h < ch) { chunk = child; continue outer }
  859. h -= ch;
  860. n += child.chunkSize();
  861. }
  862. return n
  863. } while (!chunk.lines)
  864. var i = 0;
  865. for (; i < chunk.lines.length; ++i) {
  866. var line = chunk.lines[i], lh = line.height;
  867. if (h < lh) { break }
  868. h -= lh;
  869. }
  870. return n + i
  871. }
  872. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  873. function lineNumberFor(options, i) {
  874. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  875. }
  876. // A Pos instance represents a position within the text.
  877. function Pos(line, ch, sticky) {
  878. if ( sticky === void 0 ) sticky = null;
  879. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  880. this.line = line;
  881. this.ch = ch;
  882. this.sticky = sticky;
  883. }
  884. // Compare two positions, return 0 if they are the same, a negative
  885. // number when a is less, and a positive number otherwise.
  886. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  887. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  888. function copyPos(x) {return Pos(x.line, x.ch)}
  889. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  890. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  891. // Most of the external API clips given positions to make sure they
  892. // actually exist within the document.
  893. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  894. function clipPos(doc, pos) {
  895. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  896. var last = doc.first + doc.size - 1;
  897. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  898. return clipToLen(pos, getLine(doc, pos.line).text.length)
  899. }
  900. function clipToLen(pos, linelen) {
  901. var ch = pos.ch;
  902. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  903. else if (ch < 0) { return Pos(pos.line, 0) }
  904. else { return pos }
  905. }
  906. function clipPosArray(doc, array) {
  907. var out = [];
  908. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  909. return out
  910. }
  911. var SavedContext = function(state, lookAhead) {
  912. this.state = state;
  913. this.lookAhead = lookAhead;
  914. };
  915. var Context = function(doc, state, line, lookAhead) {
  916. this.state = state;
  917. this.doc = doc;
  918. this.line = line;
  919. this.maxLookAhead = lookAhead || 0;
  920. this.baseTokens = null;
  921. this.baseTokenPos = 1;
  922. };
  923. Context.prototype.lookAhead = function (n) {
  924. var line = this.doc.getLine(this.line + n);
  925. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  926. return line
  927. };
  928. Context.prototype.baseToken = function (n) {
  929. if (!this.baseTokens) { return null }
  930. while (this.baseTokens[this.baseTokenPos] <= n)
  931. { this.baseTokenPos += 2; }
  932. var type = this.baseTokens[this.baseTokenPos + 1];
  933. return {type: type && type.replace(/( |^)overlay .*/, ""),
  934. size: this.baseTokens[this.baseTokenPos] - n}
  935. };
  936. Context.prototype.nextLine = function () {
  937. this.line++;
  938. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  939. };
  940. Context.fromSaved = function (doc, saved, line) {
  941. if (saved instanceof SavedContext)
  942. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  943. else
  944. { return new Context(doc, copyState(doc.mode, saved), line) }
  945. };
  946. Context.prototype.save = function (copy) {
  947. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  948. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  949. };
  950. // Compute a style array (an array starting with a mode generation
  951. // -- for invalidation -- followed by pairs of end positions and
  952. // style strings), which is used to highlight the tokens on the
  953. // line.
  954. function highlightLine(cm, line, context, forceToEnd) {
  955. // A styles array always starts with a number identifying the
  956. // mode/overlays that it is based on (for easy invalidation).
  957. var st = [cm.state.modeGen], lineClasses = {};
  958. // Compute the base array of styles
  959. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  960. lineClasses, forceToEnd);
  961. var state = context.state;
  962. // Run overlays, adjust style array.
  963. var loop = function ( o ) {
  964. context.baseTokens = st;
  965. var overlay = cm.state.overlays[o], i = 1, at = 0;
  966. context.state = true;
  967. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  968. var start = i;
  969. // Ensure there's a token end at the current position, and that i points at it
  970. while (at < end) {
  971. var i_end = st[i];
  972. if (i_end > end)
  973. { st.splice(i, 1, end, st[i+1], i_end); }
  974. i += 2;
  975. at = Math.min(end, i_end);
  976. }
  977. if (!style) { return }
  978. if (overlay.opaque) {
  979. st.splice(start, i - start, end, "overlay " + style);
  980. i = start + 2;
  981. } else {
  982. for (; start < i; start += 2) {
  983. var cur = st[start+1];
  984. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  985. }
  986. }
  987. }, lineClasses);
  988. context.state = state;
  989. context.baseTokens = null;
  990. context.baseTokenPos = 1;
  991. };
  992. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  993. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  994. }
  995. function getLineStyles(cm, line, updateFrontier) {
  996. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  997. var context = getContextBefore(cm, lineNo(line));
  998. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  999. var result = highlightLine(cm, line, context);
  1000. if (resetState) { context.state = resetState; }
  1001. line.stateAfter = context.save(!resetState);
  1002. line.styles = result.styles;
  1003. if (result.classes) { line.styleClasses = result.classes; }
  1004. else if (line.styleClasses) { line.styleClasses = null; }
  1005. if (updateFrontier === cm.doc.highlightFrontier)
  1006. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1007. }
  1008. return line.styles
  1009. }
  1010. function getContextBefore(cm, n, precise) {
  1011. var doc = cm.doc, display = cm.display;
  1012. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1013. var start = findStartLine(cm, n, precise);
  1014. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1015. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1016. doc.iter(start, n, function (line) {
  1017. processLine(cm, line.text, context);
  1018. var pos = context.line;
  1019. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1020. context.nextLine();
  1021. });
  1022. if (precise) { doc.modeFrontier = context.line; }
  1023. return context
  1024. }
  1025. // Lightweight form of highlight -- proceed over this line and
  1026. // update state, but don't save a style array. Used for lines that
  1027. // aren't currently visible.
  1028. function processLine(cm, text, context, startAt) {
  1029. var mode = cm.doc.mode;
  1030. var stream = new StringStream(text, cm.options.tabSize, context);
  1031. stream.start = stream.pos = startAt || 0;
  1032. if (text == "") { callBlankLine(mode, context.state); }
  1033. while (!stream.eol()) {
  1034. readToken(mode, stream, context.state);
  1035. stream.start = stream.pos;
  1036. }
  1037. }
  1038. function callBlankLine(mode, state) {
  1039. if (mode.blankLine) { return mode.blankLine(state) }
  1040. if (!mode.innerMode) { return }
  1041. var inner = innerMode(mode, state);
  1042. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1043. }
  1044. function readToken(mode, stream, state, inner) {
  1045. for (var i = 0; i < 10; i++) {
  1046. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1047. var style = mode.token(stream, state);
  1048. if (stream.pos > stream.start) { return style }
  1049. }
  1050. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1051. }
  1052. var Token = function(stream, type, state) {
  1053. this.start = stream.start; this.end = stream.pos;
  1054. this.string = stream.current();
  1055. this.type = type || null;
  1056. this.state = state;
  1057. };
  1058. // Utility for getTokenAt and getLineTokens
  1059. function takeToken(cm, pos, precise, asArray) {
  1060. var doc = cm.doc, mode = doc.mode, style;
  1061. pos = clipPos(doc, pos);
  1062. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1063. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1064. if (asArray) { tokens = []; }
  1065. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1066. stream.start = stream.pos;
  1067. style = readToken(mode, stream, context.state);
  1068. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1069. }
  1070. return asArray ? tokens : new Token(stream, style, context.state)
  1071. }
  1072. function extractLineClasses(type, output) {
  1073. if (type) { for (;;) {
  1074. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1075. if (!lineClass) { break }
  1076. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1077. var prop = lineClass[1] ? "bgClass" : "textClass";
  1078. if (output[prop] == null)
  1079. { output[prop] = lineClass[2]; }
  1080. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1081. { output[prop] += " " + lineClass[2]; }
  1082. } }
  1083. return type
  1084. }
  1085. // Run the given mode's parser over a line, calling f for each token.
  1086. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1087. var flattenSpans = mode.flattenSpans;
  1088. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1089. var curStart = 0, curStyle = null;
  1090. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1091. var inner = cm.options.addModeClass && [null];
  1092. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1093. while (!stream.eol()) {
  1094. if (stream.pos > cm.options.maxHighlightLength) {
  1095. flattenSpans = false;
  1096. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1097. stream.pos = text.length;
  1098. style = null;
  1099. } else {
  1100. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1101. }
  1102. if (inner) {
  1103. var mName = inner[0].name;
  1104. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1105. }
  1106. if (!flattenSpans || curStyle != style) {
  1107. while (curStart < stream.start) {
  1108. curStart = Math.min(stream.start, curStart + 5000);
  1109. f(curStart, curStyle);
  1110. }
  1111. curStyle = style;
  1112. }
  1113. stream.start = stream.pos;
  1114. }
  1115. while (curStart < stream.pos) {
  1116. // Webkit seems to refuse to render text nodes longer than 57444
  1117. // characters, and returns inaccurate measurements in nodes
  1118. // starting around 5000 chars.
  1119. var pos = Math.min(stream.pos, curStart + 5000);
  1120. f(pos, curStyle);
  1121. curStart = pos;
  1122. }
  1123. }
  1124. // Finds the line to start with when starting a parse. Tries to
  1125. // find a line with a stateAfter, so that it can start with a
  1126. // valid state. If that fails, it returns the line with the
  1127. // smallest indentation, which tends to need the least context to
  1128. // parse correctly.
  1129. function findStartLine(cm, n, precise) {
  1130. var minindent, minline, doc = cm.doc;
  1131. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1132. for (var search = n; search > lim; --search) {
  1133. if (search <= doc.first) { return doc.first }
  1134. var line = getLine(doc, search - 1), after = line.stateAfter;
  1135. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1136. { return search }
  1137. var indented = countColumn(line.text, null, cm.options.tabSize);
  1138. if (minline == null || minindent > indented) {
  1139. minline = search - 1;
  1140. minindent = indented;
  1141. }
  1142. }
  1143. return minline
  1144. }
  1145. function retreatFrontier(doc, n) {
  1146. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1147. if (doc.highlightFrontier < n - 10) { return }
  1148. var start = doc.first;
  1149. for (var line = n - 1; line > start; line--) {
  1150. var saved = getLine(doc, line).stateAfter;
  1151. // change is on 3
  1152. // state on line 1 looked ahead 2 -- so saw 3
  1153. // test 1 + 2 < 3 should cover this
  1154. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1155. start = line + 1;
  1156. break
  1157. }
  1158. }
  1159. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1160. }
  1161. // Optimize some code when these features are not used.
  1162. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1163. function seeReadOnlySpans() {
  1164. sawReadOnlySpans = true;
  1165. }
  1166. function seeCollapsedSpans() {
  1167. sawCollapsedSpans = true;
  1168. }
  1169. // TEXTMARKER SPANS
  1170. function MarkedSpan(marker, from, to) {
  1171. this.marker = marker;
  1172. this.from = from; this.to = to;
  1173. }
  1174. // Search an array of spans for a span matching the given marker.
  1175. function getMarkedSpanFor(spans, marker) {
  1176. if (spans) { for (var i = 0; i < spans.length; ++i) {
  1177. var span = spans[i];
  1178. if (span.marker == marker) { return span }
  1179. } }
  1180. }
  1181. // Remove a span from an array, returning undefined if no spans are
  1182. // left (we don't store arrays for lines without spans).
  1183. function removeMarkedSpan(spans, span) {
  1184. var r;
  1185. for (var i = 0; i < spans.length; ++i)
  1186. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1187. return r
  1188. }
  1189. // Add a span to a line.
  1190. function addMarkedSpan(line, span, op) {
  1191. var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
  1192. if (inThisOp && inThisOp.has(line.markedSpans)) {
  1193. line.markedSpans.push(span);
  1194. } else {
  1195. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1196. if (inThisOp) { inThisOp.add(line.markedSpans); }
  1197. }
  1198. span.marker.attachLine(line);
  1199. }
  1200. // Used for the algorithm that adjusts markers for a change in the
  1201. // document. These functions cut an array of spans at a given
  1202. // character position, returning an array of remaining chunks (or
  1203. // undefined if nothing remains).
  1204. function markedSpansBefore(old, startCh, isInsert) {
  1205. var nw;
  1206. if (old) { for (var i = 0; i < old.length; ++i) {
  1207. var span = old[i], marker = span.marker;
  1208. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1209. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1210. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1211. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1212. }
  1213. } }
  1214. return nw
  1215. }
  1216. function markedSpansAfter(old, endCh, isInsert) {
  1217. var nw;
  1218. if (old) { for (var i = 0; i < old.length; ++i) {
  1219. var span = old[i], marker = span.marker;
  1220. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1221. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1222. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1223. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1224. span.to == null ? null : span.to - endCh));
  1225. }
  1226. } }
  1227. return nw
  1228. }
  1229. // Given a change object, compute the new set of marker spans that
  1230. // cover the line in which the change took place. Removes spans
  1231. // entirely within the change, reconnects spans belonging to the
  1232. // same marker that appear on both sides of the change, and cuts off
  1233. // spans partially within the change. Returns an array of span
  1234. // arrays with one element for each line in (after) the change.
  1235. function stretchSpansOverChange(doc, change) {
  1236. if (change.full) { return null }
  1237. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1238. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1239. if (!oldFirst && !oldLast) { return null }
  1240. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1241. // Get the spans that 'stick out' on both sides
  1242. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1243. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1244. // Next, merge those two ends
  1245. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1246. if (first) {
  1247. // Fix up .to properties of first
  1248. for (var i = 0; i < first.length; ++i) {
  1249. var span = first[i];
  1250. if (span.to == null) {
  1251. var found = getMarkedSpanFor(last, span.marker);
  1252. if (!found) { span.to = startCh; }
  1253. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1254. }
  1255. }
  1256. }
  1257. if (last) {
  1258. // Fix up .from in last (or move them into first in case of sameLine)
  1259. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1260. var span$1 = last[i$1];
  1261. if (span$1.to != null) { span$1.to += offset; }
  1262. if (span$1.from == null) {
  1263. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1264. if (!found$1) {
  1265. span$1.from = offset;
  1266. if (sameLine) { (first || (first = [])).push(span$1); }
  1267. }
  1268. } else {
  1269. span$1.from += offset;
  1270. if (sameLine) { (first || (first = [])).push(span$1); }
  1271. }
  1272. }
  1273. }
  1274. // Make sure we didn't create any zero-length spans
  1275. if (first) { first = clearEmptySpans(first); }
  1276. if (last && last != first) { last = clearEmptySpans(last); }
  1277. var newMarkers = [first];
  1278. if (!sameLine) {
  1279. // Fill gap with whole-line-spans
  1280. var gap = change.text.length - 2, gapMarkers;
  1281. if (gap > 0 && first)
  1282. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1283. { if (first[i$2].to == null)
  1284. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1285. for (var i$3 = 0; i$3 < gap; ++i$3)
  1286. { newMarkers.push(gapMarkers); }
  1287. newMarkers.push(last);
  1288. }
  1289. return newMarkers
  1290. }
  1291. // Remove spans that are empty and don't have a clearWhenEmpty
  1292. // option of false.
  1293. function clearEmptySpans(spans) {
  1294. for (var i = 0; i < spans.length; ++i) {
  1295. var span = spans[i];
  1296. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1297. { spans.splice(i--, 1); }
  1298. }
  1299. if (!spans.length) { return null }
  1300. return spans
  1301. }
  1302. // Used to 'clip' out readOnly ranges when making a change.
  1303. function removeReadOnlyRanges(doc, from, to) {
  1304. var markers = null;
  1305. doc.iter(from.line, to.line + 1, function (line) {
  1306. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1307. var mark = line.markedSpans[i].marker;
  1308. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1309. { (markers || (markers = [])).push(mark); }
  1310. } }
  1311. });
  1312. if (!markers) { return null }
  1313. var parts = [{from: from, to: to}];
  1314. for (var i = 0; i < markers.length; ++i) {
  1315. var mk = markers[i], m = mk.find(0);
  1316. for (var j = 0; j < parts.length; ++j) {
  1317. var p = parts[j];
  1318. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1319. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1320. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1321. { newParts.push({from: p.from, to: m.from}); }
  1322. if (dto > 0 || !mk.inclusiveRight && !dto)
  1323. { newParts.push({from: m.to, to: p.to}); }
  1324. parts.splice.apply(parts, newParts);
  1325. j += newParts.length - 3;
  1326. }
  1327. }
  1328. return parts
  1329. }
  1330. // Connect or disconnect spans from a line.
  1331. function detachMarkedSpans(line) {
  1332. var spans = line.markedSpans;
  1333. if (!spans) { return }
  1334. for (var i = 0; i < spans.length; ++i)
  1335. { spans[i].marker.detachLine(line); }
  1336. line.markedSpans = null;
  1337. }
  1338. function attachMarkedSpans(line, spans) {
  1339. if (!spans) { return }
  1340. for (var i = 0; i < spans.length; ++i)
  1341. { spans[i].marker.attachLine(line); }
  1342. line.markedSpans = spans;
  1343. }
  1344. // Helpers used when computing which overlapping collapsed span
  1345. // counts as the larger one.
  1346. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1347. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1348. // Returns a number indicating which of two overlapping collapsed
  1349. // spans is larger (and thus includes the other). Falls back to
  1350. // comparing ids when the spans cover exactly the same range.
  1351. function compareCollapsedMarkers(a, b) {
  1352. var lenDiff = a.lines.length - b.lines.length;
  1353. if (lenDiff != 0) { return lenDiff }
  1354. var aPos = a.find(), bPos = b.find();
  1355. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1356. if (fromCmp) { return -fromCmp }
  1357. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1358. if (toCmp) { return toCmp }
  1359. return b.id - a.id
  1360. }
  1361. // Find out whether a line ends or starts in a collapsed span. If
  1362. // so, return the marker for that span.
  1363. function collapsedSpanAtSide(line, start) {
  1364. var sps = sawCollapsedSpans && line.markedSpans, found;
  1365. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1366. sp = sps[i];
  1367. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1368. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1369. { found = sp.marker; }
  1370. } }
  1371. return found
  1372. }
  1373. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1374. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1375. function collapsedSpanAround(line, ch) {
  1376. var sps = sawCollapsedSpans && line.markedSpans, found;
  1377. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1378. var sp = sps[i];
  1379. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1380. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1381. } }
  1382. return found
  1383. }
  1384. // Test whether there exists a collapsed span that partially
  1385. // overlaps (covers the start or end, but not both) of a new span.
  1386. // Such overlap is not allowed.
  1387. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1388. var line = getLine(doc, lineNo);
  1389. var sps = sawCollapsedSpans && line.markedSpans;
  1390. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1391. var sp = sps[i];
  1392. if (!sp.marker.collapsed) { continue }
  1393. var found = sp.marker.find(0);
  1394. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1395. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1396. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1397. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1398. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1399. { return true }
  1400. } }
  1401. }
  1402. // A visual line is a line as drawn on the screen. Folding, for
  1403. // example, can cause multiple logical lines to appear on the same
  1404. // visual line. This finds the start of the visual line that the
  1405. // given line is part of (usually that is the line itself).
  1406. function visualLine(line) {
  1407. var merged;
  1408. while (merged = collapsedSpanAtStart(line))
  1409. { line = merged.find(-1, true).line; }
  1410. return line
  1411. }
  1412. function visualLineEnd(line) {
  1413. var merged;
  1414. while (merged = collapsedSpanAtEnd(line))
  1415. { line = merged.find(1, true).line; }
  1416. return line
  1417. }
  1418. // Returns an array of logical lines that continue the visual line
  1419. // started by the argument, or undefined if there are no such lines.
  1420. function visualLineContinued(line) {
  1421. var merged, lines;
  1422. while (merged = collapsedSpanAtEnd(line)) {
  1423. line = merged.find(1, true).line
  1424. ;(lines || (lines = [])).push(line);
  1425. }
  1426. return lines
  1427. }
  1428. // Get the line number of the start of the visual line that the
  1429. // given line number is part of.
  1430. function visualLineNo(doc, lineN) {
  1431. var line = getLine(doc, lineN), vis = visualLine(line);
  1432. if (line == vis) { return lineN }
  1433. return lineNo(vis)
  1434. }
  1435. // Get the line number of the start of the next visual line after
  1436. // the given line.
  1437. function visualLineEndNo(doc, lineN) {
  1438. if (lineN > doc.lastLine()) { return lineN }
  1439. var line = getLine(doc, lineN), merged;
  1440. if (!lineIsHidden(doc, line)) { return lineN }
  1441. while (merged = collapsedSpanAtEnd(line))
  1442. { line = merged.find(1, true).line; }
  1443. return lineNo(line) + 1
  1444. }
  1445. // Compute whether a line is hidden. Lines count as hidden when they
  1446. // are part of a visual line that starts with another line, or when
  1447. // they are entirely covered by collapsed, non-widget span.
  1448. function lineIsHidden(doc, line) {
  1449. var sps = sawCollapsedSpans && line.markedSpans;
  1450. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1451. sp = sps[i];
  1452. if (!sp.marker.collapsed) { continue }
  1453. if (sp.from == null) { return true }
  1454. if (sp.marker.widgetNode) { continue }
  1455. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1456. { return true }
  1457. } }
  1458. }
  1459. function lineIsHiddenInner(doc, line, span) {
  1460. if (span.to == null) {
  1461. var end = span.marker.find(1, true);
  1462. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1463. }
  1464. if (span.marker.inclusiveRight && span.to == line.text.length)
  1465. { return true }
  1466. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1467. sp = line.markedSpans[i];
  1468. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1469. (sp.to == null || sp.to != span.from) &&
  1470. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1471. lineIsHiddenInner(doc, line, sp)) { return true }
  1472. }
  1473. }
  1474. // Find the height above the given line.
  1475. function heightAtLine(lineObj) {
  1476. lineObj = visualLine(lineObj);
  1477. var h = 0, chunk = lineObj.parent;
  1478. for (var i = 0; i < chunk.lines.length; ++i) {
  1479. var line = chunk.lines[i];
  1480. if (line == lineObj) { break }
  1481. else { h += line.height; }
  1482. }
  1483. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1484. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1485. var cur = p.children[i$1];
  1486. if (cur == chunk) { break }
  1487. else { h += cur.height; }
  1488. }
  1489. }
  1490. return h
  1491. }
  1492. // Compute the character length of a line, taking into account
  1493. // collapsed ranges (see markText) that might hide parts, and join
  1494. // other lines onto it.
  1495. function lineLength(line) {
  1496. if (line.height == 0) { return 0 }
  1497. var len = line.text.length, merged, cur = line;
  1498. while (merged = collapsedSpanAtStart(cur)) {
  1499. var found = merged.find(0, true);
  1500. cur = found.from.line;
  1501. len += found.from.ch - found.to.ch;
  1502. }
  1503. cur = line;
  1504. while (merged = collapsedSpanAtEnd(cur)) {
  1505. var found$1 = merged.find(0, true);
  1506. len -= cur.text.length - found$1.from.ch;
  1507. cur = found$1.to.line;
  1508. len += cur.text.length - found$1.to.ch;
  1509. }
  1510. return len
  1511. }
  1512. // Find the longest line in the document.
  1513. function findMaxLine(cm) {
  1514. var d = cm.display, doc = cm.doc;
  1515. d.maxLine = getLine(doc, doc.first);
  1516. d.maxLineLength = lineLength(d.maxLine);
  1517. d.maxLineChanged = true;
  1518. doc.iter(function (line) {
  1519. var len = lineLength(line);
  1520. if (len > d.maxLineLength) {
  1521. d.maxLineLength = len;
  1522. d.maxLine = line;
  1523. }
  1524. });
  1525. }
  1526. // LINE DATA STRUCTURE
  1527. // Line objects. These hold state related to a line, including
  1528. // highlighting info (the styles array).
  1529. var Line = function(text, markedSpans, estimateHeight) {
  1530. this.text = text;
  1531. attachMarkedSpans(this, markedSpans);
  1532. this.height = estimateHeight ? estimateHeight(this) : 1;
  1533. };
  1534. Line.prototype.lineNo = function () { return lineNo(this) };
  1535. eventMixin(Line);
  1536. // Change the content (text, markers) of a line. Automatically
  1537. // invalidates cached information and tries to re-estimate the
  1538. // line's height.
  1539. function updateLine(line, text, markedSpans, estimateHeight) {
  1540. line.text = text;
  1541. if (line.stateAfter) { line.stateAfter = null; }
  1542. if (line.styles) { line.styles = null; }
  1543. if (line.order != null) { line.order = null; }
  1544. detachMarkedSpans(line);
  1545. attachMarkedSpans(line, markedSpans);
  1546. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1547. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1548. }
  1549. // Detach a line from the document tree and its markers.
  1550. function cleanUpLine(line) {
  1551. line.parent = null;
  1552. detachMarkedSpans(line);
  1553. }
  1554. // Convert a style as returned by a mode (either null, or a string
  1555. // containing one or more styles) to a CSS style. This is cached,
  1556. // and also looks for line-wide styles.
  1557. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1558. function interpretTokenStyle(style, options) {
  1559. if (!style || /^\s*$/.test(style)) { return null }
  1560. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1561. return cache[style] ||
  1562. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1563. }
  1564. // Render the DOM representation of the text of a line. Also builds
  1565. // up a 'line map', which points at the DOM nodes that represent
  1566. // specific stretches of text, and is used by the measuring code.
  1567. // The returned object contains the DOM node, this map, and
  1568. // information about line-wide styles that were set by the mode.
  1569. function buildLineContent(cm, lineView) {
  1570. // The padding-right forces the element to have a 'border', which
  1571. // is needed on Webkit to be able to get line-level bounding
  1572. // rectangles for it (in measureChar).
  1573. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1574. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1575. col: 0, pos: 0, cm: cm,
  1576. trailingSpace: false,
  1577. splitSpaces: cm.getOption("lineWrapping")};
  1578. lineView.measure = {};
  1579. // Iterate over the logical lines that make up this visual line.
  1580. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1581. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1582. builder.pos = 0;
  1583. builder.addToken = buildToken;
  1584. // Optionally wire in some hacks into the token-rendering
  1585. // algorithm, to deal with browser quirks.
  1586. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1587. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1588. builder.map = [];
  1589. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1590. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1591. if (line.styleClasses) {
  1592. if (line.styleClasses.bgClass)
  1593. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1594. if (line.styleClasses.textClass)
  1595. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1596. }
  1597. // Ensure at least a single node is present, for measuring.
  1598. if (builder.map.length == 0)
  1599. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1600. // Store the map and a cache object for the current logical line
  1601. if (i == 0) {
  1602. lineView.measure.map = builder.map;
  1603. lineView.measure.cache = {};
  1604. } else {
  1605. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1606. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1607. }
  1608. }
  1609. // See issue #2901
  1610. if (webkit) {
  1611. var last = builder.content.lastChild;
  1612. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1613. { builder.content.className = "cm-tab-wrap-hack"; }
  1614. }
  1615. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1616. if (builder.pre.className)
  1617. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1618. return builder
  1619. }
  1620. function defaultSpecialCharPlaceholder(ch) {
  1621. var token = elt("span", "\u2022", "cm-invalidchar");
  1622. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1623. token.setAttribute("aria-label", token.title);
  1624. return token
  1625. }
  1626. // Build up the DOM representation for a single token, and add it to
  1627. // the line map. Takes care to render special characters separately.
  1628. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1629. if (!text) { return }
  1630. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1631. var special = builder.cm.state.specialChars, mustWrap = false;
  1632. var content;
  1633. if (!special.test(text)) {
  1634. builder.col += text.length;
  1635. content = document.createTextNode(displayText);
  1636. builder.map.push(builder.pos, builder.pos + text.length, content);
  1637. if (ie && ie_version < 9) { mustWrap = true; }
  1638. builder.pos += text.length;
  1639. } else {
  1640. content = document.createDocumentFragment();
  1641. var pos = 0;
  1642. while (true) {
  1643. special.lastIndex = pos;
  1644. var m = special.exec(text);
  1645. var skipped = m ? m.index - pos : text.length - pos;
  1646. if (skipped) {
  1647. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1648. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1649. else { content.appendChild(txt); }
  1650. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1651. builder.col += skipped;
  1652. builder.pos += skipped;
  1653. }
  1654. if (!m) { break }
  1655. pos += skipped + 1;
  1656. var txt$1 = (void 0);
  1657. if (m[0] == "\t") {
  1658. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1659. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1660. txt$1.setAttribute("role", "presentation");
  1661. txt$1.setAttribute("cm-text", "\t");
  1662. builder.col += tabWidth;
  1663. } else if (m[0] == "\r" || m[0] == "\n") {
  1664. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1665. txt$1.setAttribute("cm-text", m[0]);
  1666. builder.col += 1;
  1667. } else {
  1668. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1669. txt$1.setAttribute("cm-text", m[0]);
  1670. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1671. else { content.appendChild(txt$1); }
  1672. builder.col += 1;
  1673. }
  1674. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1675. builder.pos++;
  1676. }
  1677. }
  1678. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1679. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  1680. var fullStyle = style || "";
  1681. if (startStyle) { fullStyle += startStyle; }
  1682. if (endStyle) { fullStyle += endStyle; }
  1683. var token = elt("span", [content], fullStyle, css);
  1684. if (attributes) {
  1685. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1686. { token.setAttribute(attr, attributes[attr]); } }
  1687. }
  1688. return builder.content.appendChild(token)
  1689. }
  1690. builder.content.appendChild(content);
  1691. }
  1692. // Change some spaces to NBSP to prevent the browser from collapsing
  1693. // trailing spaces at the end of a line when rendering text (issue #1362).
  1694. function splitSpaces(text, trailingBefore) {
  1695. if (text.length > 1 && !/ /.test(text)) { return text }
  1696. var spaceBefore = trailingBefore, result = "";
  1697. for (var i = 0; i < text.length; i++) {
  1698. var ch = text.charAt(i);
  1699. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1700. { ch = "\u00a0"; }
  1701. result += ch;
  1702. spaceBefore = ch == " ";
  1703. }
  1704. return result
  1705. }
  1706. // Work around nonsense dimensions being reported for stretches of
  1707. // right-to-left text.
  1708. function buildTokenBadBidi(inner, order) {
  1709. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1710. style = style ? style + " cm-force-border" : "cm-force-border";
  1711. var start = builder.pos, end = start + text.length;
  1712. for (;;) {
  1713. // Find the part that overlaps with the start of this text
  1714. var part = (void 0);
  1715. for (var i = 0; i < order.length; i++) {
  1716. part = order[i];
  1717. if (part.to > start && part.from <= start) { break }
  1718. }
  1719. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1720. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1721. startStyle = null;
  1722. text = text.slice(part.to - start);
  1723. start = part.to;
  1724. }
  1725. }
  1726. }
  1727. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1728. var widget = !ignoreWidget && marker.widgetNode;
  1729. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1730. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1731. if (!widget)
  1732. { widget = builder.content.appendChild(document.createElement("span")); }
  1733. widget.setAttribute("cm-marker", marker.id);
  1734. }
  1735. if (widget) {
  1736. builder.cm.display.input.setUneditable(widget);
  1737. builder.content.appendChild(widget);
  1738. }
  1739. builder.pos += size;
  1740. builder.trailingSpace = false;
  1741. }
  1742. // Outputs a number of spans to make up a line, taking highlighting
  1743. // and marked text into account.
  1744. function insertLineContent(line, builder, styles) {
  1745. var spans = line.markedSpans, allText = line.text, at = 0;
  1746. if (!spans) {
  1747. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1748. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1749. return
  1750. }
  1751. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1752. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1753. for (;;) {
  1754. if (nextChange == pos) { // Update current marker set
  1755. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1756. attributes = null;
  1757. collapsed = null; nextChange = Infinity;
  1758. var foundBookmarks = [], endStyles = (void 0);
  1759. for (var j = 0; j < spans.length; ++j) {
  1760. var sp = spans[j], m = sp.marker;
  1761. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1762. foundBookmarks.push(m);
  1763. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1764. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1765. nextChange = sp.to;
  1766. spanEndStyle = "";
  1767. }
  1768. if (m.className) { spanStyle += " " + m.className; }
  1769. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1770. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1771. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1772. // support for the old title property
  1773. // https://github.com/codemirror/CodeMirror/pull/5673
  1774. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1775. if (m.attributes) {
  1776. for (var attr in m.attributes)
  1777. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1778. }
  1779. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1780. { collapsed = sp; }
  1781. } else if (sp.from > pos && nextChange > sp.from) {
  1782. nextChange = sp.from;
  1783. }
  1784. }
  1785. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1786. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1787. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1788. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1789. if (collapsed && (collapsed.from || 0) == pos) {
  1790. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1791. collapsed.marker, collapsed.from == null);
  1792. if (collapsed.to == null) { return }
  1793. if (collapsed.to == pos) { collapsed = false; }
  1794. }
  1795. }
  1796. if (pos >= len) { break }
  1797. var upto = Math.min(len, nextChange);
  1798. while (true) {
  1799. if (text) {
  1800. var end = pos + text.length;
  1801. if (!collapsed) {
  1802. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1803. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1804. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1805. }
  1806. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1807. pos = end;
  1808. spanStartStyle = "";
  1809. }
  1810. text = allText.slice(at, at = styles[i++]);
  1811. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1812. }
  1813. }
  1814. }
  1815. // These objects are used to represent the visible (currently drawn)
  1816. // part of the document. A LineView may correspond to multiple
  1817. // logical lines, if those are connected by collapsed ranges.
  1818. function LineView(doc, line, lineN) {
  1819. // The starting line
  1820. this.line = line;
  1821. // Continuing lines, if any
  1822. this.rest = visualLineContinued(line);
  1823. // Number of logical lines in this visual line
  1824. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1825. this.node = this.text = null;
  1826. this.hidden = lineIsHidden(doc, line);
  1827. }
  1828. // Create a range of LineView objects for the given lines.
  1829. function buildViewArray(cm, from, to) {
  1830. var array = [], nextPos;
  1831. for (var pos = from; pos < to; pos = nextPos) {
  1832. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1833. nextPos = pos + view.size;
  1834. array.push(view);
  1835. }
  1836. return array
  1837. }
  1838. var operationGroup = null;
  1839. function pushOperation(op) {
  1840. if (operationGroup) {
  1841. operationGroup.ops.push(op);
  1842. } else {
  1843. op.ownsGroup = operationGroup = {
  1844. ops: [op],
  1845. delayedCallbacks: []
  1846. };
  1847. }
  1848. }
  1849. function fireCallbacksForOps(group) {
  1850. // Calls delayed callbacks and cursorActivity handlers until no
  1851. // new ones appear
  1852. var callbacks = group.delayedCallbacks, i = 0;
  1853. do {
  1854. for (; i < callbacks.length; i++)
  1855. { callbacks[i].call(null); }
  1856. for (var j = 0; j < group.ops.length; j++) {
  1857. var op = group.ops[j];
  1858. if (op.cursorActivityHandlers)
  1859. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1860. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1861. }
  1862. } while (i < callbacks.length)
  1863. }
  1864. function finishOperation(op, endCb) {
  1865. var group = op.ownsGroup;
  1866. if (!group) { return }
  1867. try { fireCallbacksForOps(group); }
  1868. finally {
  1869. operationGroup = null;
  1870. endCb(group);
  1871. }
  1872. }
  1873. var orphanDelayedCallbacks = null;
  1874. // Often, we want to signal events at a point where we are in the
  1875. // middle of some work, but don't want the handler to start calling
  1876. // other methods on the editor, which might be in an inconsistent
  1877. // state or simply not expect any other events to happen.
  1878. // signalLater looks whether there are any handlers, and schedules
  1879. // them to be executed when the last operation ends, or, if no
  1880. // operation is active, when a timeout fires.
  1881. function signalLater(emitter, type /*, values...*/) {
  1882. var arr = getHandlers(emitter, type);
  1883. if (!arr.length) { return }
  1884. var args = Array.prototype.slice.call(arguments, 2), list;
  1885. if (operationGroup) {
  1886. list = operationGroup.delayedCallbacks;
  1887. } else if (orphanDelayedCallbacks) {
  1888. list = orphanDelayedCallbacks;
  1889. } else {
  1890. list = orphanDelayedCallbacks = [];
  1891. setTimeout(fireOrphanDelayed, 0);
  1892. }
  1893. var loop = function ( i ) {
  1894. list.push(function () { return arr[i].apply(null, args); });
  1895. };
  1896. for (var i = 0; i < arr.length; ++i)
  1897. loop( i );
  1898. }
  1899. function fireOrphanDelayed() {
  1900. var delayed = orphanDelayedCallbacks;
  1901. orphanDelayedCallbacks = null;
  1902. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1903. }
  1904. // When an aspect of a line changes, a string is added to
  1905. // lineView.changes. This updates the relevant part of the line's
  1906. // DOM structure.
  1907. function updateLineForChanges(cm, lineView, lineN, dims) {
  1908. for (var j = 0; j < lineView.changes.length; j++) {
  1909. var type = lineView.changes[j];
  1910. if (type == "text") { updateLineText(cm, lineView); }
  1911. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1912. else if (type == "class") { updateLineClasses(cm, lineView); }
  1913. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1914. }
  1915. lineView.changes = null;
  1916. }
  1917. // Lines with gutter elements, widgets or a background class need to
  1918. // be wrapped, and have the extra elements added to the wrapper div
  1919. function ensureLineWrapped(lineView) {
  1920. if (lineView.node == lineView.text) {
  1921. lineView.node = elt("div", null, null, "position: relative");
  1922. if (lineView.text.parentNode)
  1923. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1924. lineView.node.appendChild(lineView.text);
  1925. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1926. }
  1927. return lineView.node
  1928. }
  1929. function updateLineBackground(cm, lineView) {
  1930. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1931. if (cls) { cls += " CodeMirror-linebackground"; }
  1932. if (lineView.background) {
  1933. if (cls) { lineView.background.className = cls; }
  1934. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1935. } else if (cls) {
  1936. var wrap = ensureLineWrapped(lineView);
  1937. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1938. cm.display.input.setUneditable(lineView.background);
  1939. }
  1940. }
  1941. // Wrapper around buildLineContent which will reuse the structure
  1942. // in display.externalMeasured when possible.
  1943. function getLineContent(cm, lineView) {
  1944. var ext = cm.display.externalMeasured;
  1945. if (ext && ext.line == lineView.line) {
  1946. cm.display.externalMeasured = null;
  1947. lineView.measure = ext.measure;
  1948. return ext.built
  1949. }
  1950. return buildLineContent(cm, lineView)
  1951. }
  1952. // Redraw the line's text. Interacts with the background and text
  1953. // classes because the mode may output tokens that influence these
  1954. // classes.
  1955. function updateLineText(cm, lineView) {
  1956. var cls = lineView.text.className;
  1957. var built = getLineContent(cm, lineView);
  1958. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  1959. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  1960. lineView.text = built.pre;
  1961. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1962. lineView.bgClass = built.bgClass;
  1963. lineView.textClass = built.textClass;
  1964. updateLineClasses(cm, lineView);
  1965. } else if (cls) {
  1966. lineView.text.className = cls;
  1967. }
  1968. }
  1969. function updateLineClasses(cm, lineView) {
  1970. updateLineBackground(cm, lineView);
  1971. if (lineView.line.wrapClass)
  1972. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  1973. else if (lineView.node != lineView.text)
  1974. { lineView.node.className = ""; }
  1975. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  1976. lineView.text.className = textClass || "";
  1977. }
  1978. function updateLineGutter(cm, lineView, lineN, dims) {
  1979. if (lineView.gutter) {
  1980. lineView.node.removeChild(lineView.gutter);
  1981. lineView.gutter = null;
  1982. }
  1983. if (lineView.gutterBackground) {
  1984. lineView.node.removeChild(lineView.gutterBackground);
  1985. lineView.gutterBackground = null;
  1986. }
  1987. if (lineView.line.gutterClass) {
  1988. var wrap = ensureLineWrapped(lineView);
  1989. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1990. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  1991. cm.display.input.setUneditable(lineView.gutterBackground);
  1992. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  1993. }
  1994. var markers = lineView.line.gutterMarkers;
  1995. if (cm.options.lineNumbers || markers) {
  1996. var wrap$1 = ensureLineWrapped(lineView);
  1997. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  1998. gutterWrap.setAttribute("aria-hidden", "true");
  1999. cm.display.input.setUneditable(gutterWrap);
  2000. wrap$1.insertBefore(gutterWrap, lineView.text);
  2001. if (lineView.line.gutterClass)
  2002. { gutterWrap.className += " " + lineView.line.gutterClass; }
  2003. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2004. { lineView.lineNumber = gutterWrap.appendChild(
  2005. elt("div", lineNumberFor(cm.options, lineN),
  2006. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2007. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2008. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2009. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2010. if (found)
  2011. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2012. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2013. } }
  2014. }
  2015. }
  2016. function updateLineWidgets(cm, lineView, dims) {
  2017. if (lineView.alignable) { lineView.alignable = null; }
  2018. var isWidget = classTest("CodeMirror-linewidget");
  2019. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2020. next = node.nextSibling;
  2021. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2022. }
  2023. insertLineWidgets(cm, lineView, dims);
  2024. }
  2025. // Build a line's DOM representation from scratch
  2026. function buildLineElement(cm, lineView, lineN, dims) {
  2027. var built = getLineContent(cm, lineView);
  2028. lineView.text = lineView.node = built.pre;
  2029. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2030. if (built.textClass) { lineView.textClass = built.textClass; }
  2031. updateLineClasses(cm, lineView);
  2032. updateLineGutter(cm, lineView, lineN, dims);
  2033. insertLineWidgets(cm, lineView, dims);
  2034. return lineView.node
  2035. }
  2036. // A lineView may contain multiple logical lines (when merged by
  2037. // collapsed spans). The widgets for all of them need to be drawn.
  2038. function insertLineWidgets(cm, lineView, dims) {
  2039. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2040. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2041. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2042. }
  2043. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2044. if (!line.widgets) { return }
  2045. var wrap = ensureLineWrapped(lineView);
  2046. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2047. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2048. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2049. positionLineWidget(widget, node, lineView, dims);
  2050. cm.display.input.setUneditable(node);
  2051. if (allowAbove && widget.above)
  2052. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2053. else
  2054. { wrap.appendChild(node); }
  2055. signalLater(widget, "redraw");
  2056. }
  2057. }
  2058. function positionLineWidget(widget, node, lineView, dims) {
  2059. if (widget.noHScroll) {
  2060. (lineView.alignable || (lineView.alignable = [])).push(node);
  2061. var width = dims.wrapperWidth;
  2062. node.style.left = dims.fixedPos + "px";
  2063. if (!widget.coverGutter) {
  2064. width -= dims.gutterTotalWidth;
  2065. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2066. }
  2067. node.style.width = width + "px";
  2068. }
  2069. if (widget.coverGutter) {
  2070. node.style.zIndex = 5;
  2071. node.style.position = "relative";
  2072. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2073. }
  2074. }
  2075. function widgetHeight(widget) {
  2076. if (widget.height != null) { return widget.height }
  2077. var cm = widget.doc.cm;
  2078. if (!cm) { return 0 }
  2079. if (!contains(document.body, widget.node)) {
  2080. var parentStyle = "position: relative;";
  2081. if (widget.coverGutter)
  2082. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2083. if (widget.noHScroll)
  2084. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2085. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2086. }
  2087. return widget.height = widget.node.parentNode.offsetHeight
  2088. }
  2089. // Return true when the given mouse event happened in a widget
  2090. function eventInWidget(display, e) {
  2091. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2092. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2093. (n.parentNode == display.sizer && n != display.mover))
  2094. { return true }
  2095. }
  2096. }
  2097. // POSITION MEASUREMENT
  2098. function paddingTop(display) {return display.lineSpace.offsetTop}
  2099. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2100. function paddingH(display) {
  2101. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2102. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2103. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2104. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2105. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2106. return data
  2107. }
  2108. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2109. function displayWidth(cm) {
  2110. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2111. }
  2112. function displayHeight(cm) {
  2113. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2114. }
  2115. // Ensure the lineView.wrapping.heights array is populated. This is
  2116. // an array of bottom offsets for the lines that make up a drawn
  2117. // line. When lineWrapping is on, there might be more than one
  2118. // height.
  2119. function ensureLineHeights(cm, lineView, rect) {
  2120. var wrapping = cm.options.lineWrapping;
  2121. var curWidth = wrapping && displayWidth(cm);
  2122. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2123. var heights = lineView.measure.heights = [];
  2124. if (wrapping) {
  2125. lineView.measure.width = curWidth;
  2126. var rects = lineView.text.firstChild.getClientRects();
  2127. for (var i = 0; i < rects.length - 1; i++) {
  2128. var cur = rects[i], next = rects[i + 1];
  2129. if (Math.abs(cur.bottom - next.bottom) > 2)
  2130. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2131. }
  2132. }
  2133. heights.push(rect.bottom - rect.top);
  2134. }
  2135. }
  2136. // Find a line map (mapping character offsets to text nodes) and a
  2137. // measurement cache for the given line number. (A line view might
  2138. // contain multiple lines when collapsed ranges are present.)
  2139. function mapFromLineView(lineView, line, lineN) {
  2140. if (lineView.line == line)
  2141. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2142. for (var i = 0; i < lineView.rest.length; i++)
  2143. { if (lineView.rest[i] == line)
  2144. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2145. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2146. { if (lineNo(lineView.rest[i$1]) > lineN)
  2147. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2148. }
  2149. // Render a line into the hidden node display.externalMeasured. Used
  2150. // when measurement is needed for a line that's not in the viewport.
  2151. function updateExternalMeasurement(cm, line) {
  2152. line = visualLine(line);
  2153. var lineN = lineNo(line);
  2154. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2155. view.lineN = lineN;
  2156. var built = view.built = buildLineContent(cm, view);
  2157. view.text = built.pre;
  2158. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2159. return view
  2160. }
  2161. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2162. // for a given character.
  2163. function measureChar(cm, line, ch, bias) {
  2164. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2165. }
  2166. // Find a line view that corresponds to the given line number.
  2167. function findViewForLine(cm, lineN) {
  2168. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2169. { return cm.display.view[findViewIndex(cm, lineN)] }
  2170. var ext = cm.display.externalMeasured;
  2171. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2172. { return ext }
  2173. }
  2174. // Measurement can be split in two steps, the set-up work that
  2175. // applies to the whole line, and the measurement of the actual
  2176. // character. Functions like coordsChar, that need to do a lot of
  2177. // measurements in a row, can thus ensure that the set-up work is
  2178. // only done once.
  2179. function prepareMeasureForLine(cm, line) {
  2180. var lineN = lineNo(line);
  2181. var view = findViewForLine(cm, lineN);
  2182. if (view && !view.text) {
  2183. view = null;
  2184. } else if (view && view.changes) {
  2185. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2186. cm.curOp.forceUpdate = true;
  2187. }
  2188. if (!view)
  2189. { view = updateExternalMeasurement(cm, line); }
  2190. var info = mapFromLineView(view, line, lineN);
  2191. return {
  2192. line: line, view: view, rect: null,
  2193. map: info.map, cache: info.cache, before: info.before,
  2194. hasHeights: false
  2195. }
  2196. }
  2197. // Given a prepared measurement object, measures the position of an
  2198. // actual character (or fetches it from the cache).
  2199. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2200. if (prepared.before) { ch = -1; }
  2201. var key = ch + (bias || ""), found;
  2202. if (prepared.cache.hasOwnProperty(key)) {
  2203. found = prepared.cache[key];
  2204. } else {
  2205. if (!prepared.rect)
  2206. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2207. if (!prepared.hasHeights) {
  2208. ensureLineHeights(cm, prepared.view, prepared.rect);
  2209. prepared.hasHeights = true;
  2210. }
  2211. found = measureCharInner(cm, prepared, ch, bias);
  2212. if (!found.bogus) { prepared.cache[key] = found; }
  2213. }
  2214. return {left: found.left, right: found.right,
  2215. top: varHeight ? found.rtop : found.top,
  2216. bottom: varHeight ? found.rbottom : found.bottom}
  2217. }
  2218. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2219. function nodeAndOffsetInLineMap(map, ch, bias) {
  2220. var node, start, end, collapse, mStart, mEnd;
  2221. // First, search the line map for the text node corresponding to,
  2222. // or closest to, the target character.
  2223. for (var i = 0; i < map.length; i += 3) {
  2224. mStart = map[i];
  2225. mEnd = map[i + 1];
  2226. if (ch < mStart) {
  2227. start = 0; end = 1;
  2228. collapse = "left";
  2229. } else if (ch < mEnd) {
  2230. start = ch - mStart;
  2231. end = start + 1;
  2232. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2233. end = mEnd - mStart;
  2234. start = end - 1;
  2235. if (ch >= mEnd) { collapse = "right"; }
  2236. }
  2237. if (start != null) {
  2238. node = map[i + 2];
  2239. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2240. { collapse = bias; }
  2241. if (bias == "left" && start == 0)
  2242. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2243. node = map[(i -= 3) + 2];
  2244. collapse = "left";
  2245. } }
  2246. if (bias == "right" && start == mEnd - mStart)
  2247. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2248. node = map[(i += 3) + 2];
  2249. collapse = "right";
  2250. } }
  2251. break
  2252. }
  2253. }
  2254. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2255. }
  2256. function getUsefulRect(rects, bias) {
  2257. var rect = nullRect;
  2258. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2259. if ((rect = rects[i]).left != rect.right) { break }
  2260. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2261. if ((rect = rects[i$1]).left != rect.right) { break }
  2262. } }
  2263. return rect
  2264. }
  2265. function measureCharInner(cm, prepared, ch, bias) {
  2266. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2267. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2268. var rect;
  2269. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2270. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2271. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2272. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2273. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2274. { rect = node.parentNode.getBoundingClientRect(); }
  2275. else
  2276. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2277. if (rect.left || rect.right || start == 0) { break }
  2278. end = start;
  2279. start = start - 1;
  2280. collapse = "right";
  2281. }
  2282. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2283. } else { // If it is a widget, simply get the box for the whole widget.
  2284. if (start > 0) { collapse = bias = "right"; }
  2285. var rects;
  2286. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2287. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2288. else
  2289. { rect = node.getBoundingClientRect(); }
  2290. }
  2291. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2292. var rSpan = node.parentNode.getClientRects()[0];
  2293. if (rSpan)
  2294. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2295. else
  2296. { rect = nullRect; }
  2297. }
  2298. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2299. var mid = (rtop + rbot) / 2;
  2300. var heights = prepared.view.measure.heights;
  2301. var i = 0;
  2302. for (; i < heights.length - 1; i++)
  2303. { if (mid < heights[i]) { break } }
  2304. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2305. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2306. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2307. top: top, bottom: bot};
  2308. if (!rect.left && !rect.right) { result.bogus = true; }
  2309. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2310. return result
  2311. }
  2312. // Work around problem with bounding client rects on ranges being
  2313. // returned incorrectly when zoomed on IE10 and below.
  2314. function maybeUpdateRectForZooming(measure, rect) {
  2315. if (!window.screen || screen.logicalXDPI == null ||
  2316. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2317. { return rect }
  2318. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2319. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2320. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2321. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2322. }
  2323. function clearLineMeasurementCacheFor(lineView) {
  2324. if (lineView.measure) {
  2325. lineView.measure.cache = {};
  2326. lineView.measure.heights = null;
  2327. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2328. { lineView.measure.caches[i] = {}; } }
  2329. }
  2330. }
  2331. function clearLineMeasurementCache(cm) {
  2332. cm.display.externalMeasure = null;
  2333. removeChildren(cm.display.lineMeasure);
  2334. for (var i = 0; i < cm.display.view.length; i++)
  2335. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2336. }
  2337. function clearCaches(cm) {
  2338. clearLineMeasurementCache(cm);
  2339. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2340. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2341. cm.display.lineNumChars = null;
  2342. }
  2343. function pageScrollX() {
  2344. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2345. // which causes page_Offset and bounding client rects to use
  2346. // different reference viewports and invalidate our calculations.
  2347. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2348. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2349. }
  2350. function pageScrollY() {
  2351. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2352. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2353. }
  2354. function widgetTopHeight(lineObj) {
  2355. var height = 0;
  2356. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2357. { height += widgetHeight(lineObj.widgets[i]); } } }
  2358. return height
  2359. }
  2360. // Converts a {top, bottom, left, right} box from line-local
  2361. // coordinates into another coordinate system. Context may be one of
  2362. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2363. // or "page".
  2364. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2365. if (!includeWidgets) {
  2366. var height = widgetTopHeight(lineObj);
  2367. rect.top += height; rect.bottom += height;
  2368. }
  2369. if (context == "line") { return rect }
  2370. if (!context) { context = "local"; }
  2371. var yOff = heightAtLine(lineObj);
  2372. if (context == "local") { yOff += paddingTop(cm.display); }
  2373. else { yOff -= cm.display.viewOffset; }
  2374. if (context == "page" || context == "window") {
  2375. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2376. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2377. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2378. rect.left += xOff; rect.right += xOff;
  2379. }
  2380. rect.top += yOff; rect.bottom += yOff;
  2381. return rect
  2382. }
  2383. // Coverts a box from "div" coords to another coordinate system.
  2384. // Context may be "window", "page", "div", or "local"./null.
  2385. function fromCoordSystem(cm, coords, context) {
  2386. if (context == "div") { return coords }
  2387. var left = coords.left, top = coords.top;
  2388. // First move into "page" coordinate system
  2389. if (context == "page") {
  2390. left -= pageScrollX();
  2391. top -= pageScrollY();
  2392. } else if (context == "local" || !context) {
  2393. var localBox = cm.display.sizer.getBoundingClientRect();
  2394. left += localBox.left;
  2395. top += localBox.top;
  2396. }
  2397. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2398. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2399. }
  2400. function charCoords(cm, pos, context, lineObj, bias) {
  2401. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2402. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2403. }
  2404. // Returns a box for a given cursor position, which may have an
  2405. // 'other' property containing the position of the secondary cursor
  2406. // on a bidi boundary.
  2407. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2408. // and after `char - 1` in writing order of `char - 1`
  2409. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2410. // and before `char` in writing order of `char`
  2411. // Examples (upper-case letters are RTL, lower-case are LTR):
  2412. // Pos(0, 1, ...)
  2413. // before after
  2414. // ab a|b a|b
  2415. // aB a|B aB|
  2416. // Ab |Ab A|b
  2417. // AB B|A B|A
  2418. // Every position after the last character on a line is considered to stick
  2419. // to the last character on the line.
  2420. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2421. lineObj = lineObj || getLine(cm.doc, pos.line);
  2422. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2423. function get(ch, right) {
  2424. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2425. if (right) { m.left = m.right; } else { m.right = m.left; }
  2426. return intoCoordSystem(cm, lineObj, m, context)
  2427. }
  2428. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2429. if (ch >= lineObj.text.length) {
  2430. ch = lineObj.text.length;
  2431. sticky = "before";
  2432. } else if (ch <= 0) {
  2433. ch = 0;
  2434. sticky = "after";
  2435. }
  2436. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2437. function getBidi(ch, partPos, invert) {
  2438. var part = order[partPos], right = part.level == 1;
  2439. return get(invert ? ch - 1 : ch, right != invert)
  2440. }
  2441. var partPos = getBidiPartAt(order, ch, sticky);
  2442. var other = bidiOther;
  2443. var val = getBidi(ch, partPos, sticky == "before");
  2444. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2445. return val
  2446. }
  2447. // Used to cheaply estimate the coordinates for a position. Used for
  2448. // intermediate scroll updates.
  2449. function estimateCoords(cm, pos) {
  2450. var left = 0;
  2451. pos = clipPos(cm.doc, pos);
  2452. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2453. var lineObj = getLine(cm.doc, pos.line);
  2454. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2455. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2456. }
  2457. // Positions returned by coordsChar contain some extra information.
  2458. // xRel is the relative x position of the input coordinates compared
  2459. // to the found position (so xRel > 0 means the coordinates are to
  2460. // the right of the character position, for example). When outside
  2461. // is true, that means the coordinates lie outside the line's
  2462. // vertical range.
  2463. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2464. var pos = Pos(line, ch, sticky);
  2465. pos.xRel = xRel;
  2466. if (outside) { pos.outside = outside; }
  2467. return pos
  2468. }
  2469. // Compute the character position closest to the given coordinates.
  2470. // Input must be lineSpace-local ("div" coordinate system).
  2471. function coordsChar(cm, x, y) {
  2472. var doc = cm.doc;
  2473. y += cm.display.viewOffset;
  2474. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2475. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2476. if (lineN > last)
  2477. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2478. if (x < 0) { x = 0; }
  2479. var lineObj = getLine(doc, lineN);
  2480. for (;;) {
  2481. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2482. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2483. if (!collapsed) { return found }
  2484. var rangeEnd = collapsed.find(1);
  2485. if (rangeEnd.line == lineN) { return rangeEnd }
  2486. lineObj = getLine(doc, lineN = rangeEnd.line);
  2487. }
  2488. }
  2489. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2490. y -= widgetTopHeight(lineObj);
  2491. var end = lineObj.text.length;
  2492. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2493. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2494. return {begin: begin, end: end}
  2495. }
  2496. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2497. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2498. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2499. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2500. }
  2501. // Returns true if the given side of a box is after the given
  2502. // coordinates, in top-to-bottom, left-to-right order.
  2503. function boxIsAfter(box, x, y, left) {
  2504. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2505. }
  2506. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2507. // Move y into line-local coordinate space
  2508. y -= heightAtLine(lineObj);
  2509. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2510. // When directly calling `measureCharPrepared`, we have to adjust
  2511. // for the widgets at this line.
  2512. var widgetHeight = widgetTopHeight(lineObj);
  2513. var begin = 0, end = lineObj.text.length, ltr = true;
  2514. var order = getOrder(lineObj, cm.doc.direction);
  2515. // If the line isn't plain left-to-right text, first figure out
  2516. // which bidi section the coordinates fall into.
  2517. if (order) {
  2518. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2519. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2520. ltr = part.level != 1;
  2521. // The awkward -1 offsets are needed because findFirst (called
  2522. // on these below) will treat its first bound as inclusive,
  2523. // second as exclusive, but we want to actually address the
  2524. // characters in the part's range
  2525. begin = ltr ? part.from : part.to - 1;
  2526. end = ltr ? part.to : part.from - 1;
  2527. }
  2528. // A binary search to find the first character whose bounding box
  2529. // starts after the coordinates. If we run across any whose box wrap
  2530. // the coordinates, store that.
  2531. var chAround = null, boxAround = null;
  2532. var ch = findFirst(function (ch) {
  2533. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2534. box.top += widgetHeight; box.bottom += widgetHeight;
  2535. if (!boxIsAfter(box, x, y, false)) { return false }
  2536. if (box.top <= y && box.left <= x) {
  2537. chAround = ch;
  2538. boxAround = box;
  2539. }
  2540. return true
  2541. }, begin, end);
  2542. var baseX, sticky, outside = false;
  2543. // If a box around the coordinates was found, use that
  2544. if (boxAround) {
  2545. // Distinguish coordinates nearer to the left or right side of the box
  2546. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2547. ch = chAround + (atStart ? 0 : 1);
  2548. sticky = atStart ? "after" : "before";
  2549. baseX = atLeft ? boxAround.left : boxAround.right;
  2550. } else {
  2551. // (Adjust for extended bound, if necessary.)
  2552. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2553. // To determine which side to associate with, get the box to the
  2554. // left of the character and compare it's vertical position to the
  2555. // coordinates
  2556. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2557. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2558. "after" : "before";
  2559. // Now get accurate coordinates for this place, in order to get a
  2560. // base X position
  2561. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2562. baseX = coords.left;
  2563. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2564. }
  2565. ch = skipExtendingChars(lineObj.text, ch, 1);
  2566. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2567. }
  2568. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2569. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2570. // situation, we can take this ordering to correspond to the visual
  2571. // ordering. This finds the first part whose end is after the given
  2572. // coordinates.
  2573. var index = findFirst(function (i) {
  2574. var part = order[i], ltr = part.level != 1;
  2575. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2576. "line", lineObj, preparedMeasure), x, y, true)
  2577. }, 0, order.length - 1);
  2578. var part = order[index];
  2579. // If this isn't the first part, the part's start is also after
  2580. // the coordinates, and the coordinates aren't on the same line as
  2581. // that start, move one part back.
  2582. if (index > 0) {
  2583. var ltr = part.level != 1;
  2584. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2585. "line", lineObj, preparedMeasure);
  2586. if (boxIsAfter(start, x, y, true) && start.top > y)
  2587. { part = order[index - 1]; }
  2588. }
  2589. return part
  2590. }
  2591. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2592. // In a wrapped line, rtl text on wrapping boundaries can do things
  2593. // that don't correspond to the ordering in our `order` array at
  2594. // all, so a binary search doesn't work, and we want to return a
  2595. // part that only spans one line so that the binary search in
  2596. // coordsCharInner is safe. As such, we first find the extent of the
  2597. // wrapped line, and then do a flat search in which we discard any
  2598. // spans that aren't on the line.
  2599. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2600. var begin = ref.begin;
  2601. var end = ref.end;
  2602. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2603. var part = null, closestDist = null;
  2604. for (var i = 0; i < order.length; i++) {
  2605. var p = order[i];
  2606. if (p.from >= end || p.to <= begin) { continue }
  2607. var ltr = p.level != 1;
  2608. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2609. // Weigh against spans ending before this, so that they are only
  2610. // picked if nothing ends after
  2611. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2612. if (!part || closestDist > dist) {
  2613. part = p;
  2614. closestDist = dist;
  2615. }
  2616. }
  2617. if (!part) { part = order[order.length - 1]; }
  2618. // Clip the part to the wrapped line.
  2619. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2620. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2621. return part
  2622. }
  2623. var measureText;
  2624. // Compute the default text height.
  2625. function textHeight(display) {
  2626. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2627. if (measureText == null) {
  2628. measureText = elt("pre", null, "CodeMirror-line-like");
  2629. // Measure a bunch of lines, for browsers that compute
  2630. // fractional heights.
  2631. for (var i = 0; i < 49; ++i) {
  2632. measureText.appendChild(document.createTextNode("x"));
  2633. measureText.appendChild(elt("br"));
  2634. }
  2635. measureText.appendChild(document.createTextNode("x"));
  2636. }
  2637. removeChildrenAndAdd(display.measure, measureText);
  2638. var height = measureText.offsetHeight / 50;
  2639. if (height > 3) { display.cachedTextHeight = height; }
  2640. removeChildren(display.measure);
  2641. return height || 1
  2642. }
  2643. // Compute the default character width.
  2644. function charWidth(display) {
  2645. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2646. var anchor = elt("span", "xxxxxxxxxx");
  2647. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2648. removeChildrenAndAdd(display.measure, pre);
  2649. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2650. if (width > 2) { display.cachedCharWidth = width; }
  2651. return width || 10
  2652. }
  2653. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2654. // view, so that we don't interleave reading and writing to the DOM.
  2655. function getDimensions(cm) {
  2656. var d = cm.display, left = {}, width = {};
  2657. var gutterLeft = d.gutters.clientLeft;
  2658. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2659. var id = cm.display.gutterSpecs[i].className;
  2660. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2661. width[id] = n.clientWidth;
  2662. }
  2663. return {fixedPos: compensateForHScroll(d),
  2664. gutterTotalWidth: d.gutters.offsetWidth,
  2665. gutterLeft: left,
  2666. gutterWidth: width,
  2667. wrapperWidth: d.wrapper.clientWidth}
  2668. }
  2669. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2670. // but using getBoundingClientRect to get a sub-pixel-accurate
  2671. // result.
  2672. function compensateForHScroll(display) {
  2673. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2674. }
  2675. // Returns a function that estimates the height of a line, to use as
  2676. // first approximation until the line becomes visible (and is thus
  2677. // properly measurable).
  2678. function estimateHeight(cm) {
  2679. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2680. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2681. return function (line) {
  2682. if (lineIsHidden(cm.doc, line)) { return 0 }
  2683. var widgetsHeight = 0;
  2684. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2685. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2686. } }
  2687. if (wrapping)
  2688. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2689. else
  2690. { return widgetsHeight + th }
  2691. }
  2692. }
  2693. function estimateLineHeights(cm) {
  2694. var doc = cm.doc, est = estimateHeight(cm);
  2695. doc.iter(function (line) {
  2696. var estHeight = est(line);
  2697. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2698. });
  2699. }
  2700. // Given a mouse event, find the corresponding position. If liberal
  2701. // is false, it checks whether a gutter or scrollbar was clicked,
  2702. // and returns null if it was. forRect is used by rectangular
  2703. // selections, and tries to estimate a character position even for
  2704. // coordinates beyond the right of the text.
  2705. function posFromMouse(cm, e, liberal, forRect) {
  2706. var display = cm.display;
  2707. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2708. var x, y, space = display.lineSpace.getBoundingClientRect();
  2709. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2710. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2711. catch (e$1) { return null }
  2712. var coords = coordsChar(cm, x, y), line;
  2713. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2714. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2715. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2716. }
  2717. return coords
  2718. }
  2719. // Find the view element corresponding to a given line. Return null
  2720. // when the line isn't visible.
  2721. function findViewIndex(cm, n) {
  2722. if (n >= cm.display.viewTo) { return null }
  2723. n -= cm.display.viewFrom;
  2724. if (n < 0) { return null }
  2725. var view = cm.display.view;
  2726. for (var i = 0; i < view.length; i++) {
  2727. n -= view[i].size;
  2728. if (n < 0) { return i }
  2729. }
  2730. }
  2731. // Updates the display.view data structure for a given change to the
  2732. // document. From and to are in pre-change coordinates. Lendiff is
  2733. // the amount of lines added or subtracted by the change. This is
  2734. // used for changes that span multiple lines, or change the way
  2735. // lines are divided into visual lines. regLineChange (below)
  2736. // registers single-line changes.
  2737. function regChange(cm, from, to, lendiff) {
  2738. if (from == null) { from = cm.doc.first; }
  2739. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2740. if (!lendiff) { lendiff = 0; }
  2741. var display = cm.display;
  2742. if (lendiff && to < display.viewTo &&
  2743. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2744. { display.updateLineNumbers = from; }
  2745. cm.curOp.viewChanged = true;
  2746. if (from >= display.viewTo) { // Change after
  2747. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2748. { resetView(cm); }
  2749. } else if (to <= display.viewFrom) { // Change before
  2750. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2751. resetView(cm);
  2752. } else {
  2753. display.viewFrom += lendiff;
  2754. display.viewTo += lendiff;
  2755. }
  2756. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2757. resetView(cm);
  2758. } else if (from <= display.viewFrom) { // Top overlap
  2759. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2760. if (cut) {
  2761. display.view = display.view.slice(cut.index);
  2762. display.viewFrom = cut.lineN;
  2763. display.viewTo += lendiff;
  2764. } else {
  2765. resetView(cm);
  2766. }
  2767. } else if (to >= display.viewTo) { // Bottom overlap
  2768. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2769. if (cut$1) {
  2770. display.view = display.view.slice(0, cut$1.index);
  2771. display.viewTo = cut$1.lineN;
  2772. } else {
  2773. resetView(cm);
  2774. }
  2775. } else { // Gap in the middle
  2776. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2777. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2778. if (cutTop && cutBot) {
  2779. display.view = display.view.slice(0, cutTop.index)
  2780. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2781. .concat(display.view.slice(cutBot.index));
  2782. display.viewTo += lendiff;
  2783. } else {
  2784. resetView(cm);
  2785. }
  2786. }
  2787. var ext = display.externalMeasured;
  2788. if (ext) {
  2789. if (to < ext.lineN)
  2790. { ext.lineN += lendiff; }
  2791. else if (from < ext.lineN + ext.size)
  2792. { display.externalMeasured = null; }
  2793. }
  2794. }
  2795. // Register a change to a single line. Type must be one of "text",
  2796. // "gutter", "class", "widget"
  2797. function regLineChange(cm, line, type) {
  2798. cm.curOp.viewChanged = true;
  2799. var display = cm.display, ext = cm.display.externalMeasured;
  2800. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2801. { display.externalMeasured = null; }
  2802. if (line < display.viewFrom || line >= display.viewTo) { return }
  2803. var lineView = display.view[findViewIndex(cm, line)];
  2804. if (lineView.node == null) { return }
  2805. var arr = lineView.changes || (lineView.changes = []);
  2806. if (indexOf(arr, type) == -1) { arr.push(type); }
  2807. }
  2808. // Clear the view.
  2809. function resetView(cm) {
  2810. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2811. cm.display.view = [];
  2812. cm.display.viewOffset = 0;
  2813. }
  2814. function viewCuttingPoint(cm, oldN, newN, dir) {
  2815. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2816. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2817. { return {index: index, lineN: newN} }
  2818. var n = cm.display.viewFrom;
  2819. for (var i = 0; i < index; i++)
  2820. { n += view[i].size; }
  2821. if (n != oldN) {
  2822. if (dir > 0) {
  2823. if (index == view.length - 1) { return null }
  2824. diff = (n + view[index].size) - oldN;
  2825. index++;
  2826. } else {
  2827. diff = n - oldN;
  2828. }
  2829. oldN += diff; newN += diff;
  2830. }
  2831. while (visualLineNo(cm.doc, newN) != newN) {
  2832. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2833. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2834. index += dir;
  2835. }
  2836. return {index: index, lineN: newN}
  2837. }
  2838. // Force the view to cover a given range, adding empty view element
  2839. // or clipping off existing ones as needed.
  2840. function adjustView(cm, from, to) {
  2841. var display = cm.display, view = display.view;
  2842. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2843. display.view = buildViewArray(cm, from, to);
  2844. display.viewFrom = from;
  2845. } else {
  2846. if (display.viewFrom > from)
  2847. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2848. else if (display.viewFrom < from)
  2849. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2850. display.viewFrom = from;
  2851. if (display.viewTo < to)
  2852. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2853. else if (display.viewTo > to)
  2854. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2855. }
  2856. display.viewTo = to;
  2857. }
  2858. // Count the number of lines in the view whose DOM representation is
  2859. // out of date (or nonexistent).
  2860. function countDirtyView(cm) {
  2861. var view = cm.display.view, dirty = 0;
  2862. for (var i = 0; i < view.length; i++) {
  2863. var lineView = view[i];
  2864. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2865. }
  2866. return dirty
  2867. }
  2868. function updateSelection(cm) {
  2869. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2870. }
  2871. function prepareSelection(cm, primary) {
  2872. if ( primary === void 0 ) primary = true;
  2873. var doc = cm.doc, result = {};
  2874. var curFragment = result.cursors = document.createDocumentFragment();
  2875. var selFragment = result.selection = document.createDocumentFragment();
  2876. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2877. if (!primary && i == doc.sel.primIndex) { continue }
  2878. var range = doc.sel.ranges[i];
  2879. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2880. var collapsed = range.empty();
  2881. if (collapsed || cm.options.showCursorWhenSelecting)
  2882. { drawSelectionCursor(cm, range.head, curFragment); }
  2883. if (!collapsed)
  2884. { drawSelectionRange(cm, range, selFragment); }
  2885. }
  2886. return result
  2887. }
  2888. // Draws a cursor for the given range
  2889. function drawSelectionCursor(cm, head, output) {
  2890. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2891. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2892. cursor.style.left = pos.left + "px";
  2893. cursor.style.top = pos.top + "px";
  2894. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2895. if (pos.other) {
  2896. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2897. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2898. otherCursor.style.display = "";
  2899. otherCursor.style.left = pos.other.left + "px";
  2900. otherCursor.style.top = pos.other.top + "px";
  2901. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2902. }
  2903. }
  2904. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2905. // Draws the given range as a highlighted selection
  2906. function drawSelectionRange(cm, range, output) {
  2907. var display = cm.display, doc = cm.doc;
  2908. var fragment = document.createDocumentFragment();
  2909. var padding = paddingH(cm.display), leftSide = padding.left;
  2910. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2911. var docLTR = doc.direction == "ltr";
  2912. function add(left, top, width, bottom) {
  2913. if (top < 0) { top = 0; }
  2914. top = Math.round(top);
  2915. bottom = Math.round(bottom);
  2916. 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")));
  2917. }
  2918. function drawForLine(line, fromArg, toArg) {
  2919. var lineObj = getLine(doc, line);
  2920. var lineLen = lineObj.text.length;
  2921. var start, end;
  2922. function coords(ch, bias) {
  2923. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2924. }
  2925. function wrapX(pos, dir, side) {
  2926. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2927. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2928. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2929. return coords(ch, prop)[prop]
  2930. }
  2931. var order = getOrder(lineObj, doc.direction);
  2932. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2933. var ltr = dir == "ltr";
  2934. var fromPos = coords(from, ltr ? "left" : "right");
  2935. var toPos = coords(to - 1, ltr ? "right" : "left");
  2936. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2937. var first = i == 0, last = !order || i == order.length - 1;
  2938. if (toPos.top - fromPos.top <= 3) { // Single line
  2939. var openLeft = (docLTR ? openStart : openEnd) && first;
  2940. var openRight = (docLTR ? openEnd : openStart) && last;
  2941. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2942. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2943. add(left, fromPos.top, right - left, fromPos.bottom);
  2944. } else { // Multiple lines
  2945. var topLeft, topRight, botLeft, botRight;
  2946. if (ltr) {
  2947. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2948. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2949. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2950. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2951. } else {
  2952. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2953. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2954. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2955. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2956. }
  2957. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2958. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2959. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2960. }
  2961. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2962. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2963. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2964. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2965. });
  2966. return {start: start, end: end}
  2967. }
  2968. var sFrom = range.from(), sTo = range.to();
  2969. if (sFrom.line == sTo.line) {
  2970. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2971. } else {
  2972. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2973. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2974. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2975. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2976. if (singleVLine) {
  2977. if (leftEnd.top < rightStart.top - 2) {
  2978. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2979. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2980. } else {
  2981. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2982. }
  2983. }
  2984. if (leftEnd.bottom < rightStart.top)
  2985. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  2986. }
  2987. output.appendChild(fragment);
  2988. }
  2989. // Cursor-blinking
  2990. function restartBlink(cm) {
  2991. if (!cm.state.focused) { return }
  2992. var display = cm.display;
  2993. clearInterval(display.blinker);
  2994. var on = true;
  2995. display.cursorDiv.style.visibility = "";
  2996. if (cm.options.cursorBlinkRate > 0)
  2997. { display.blinker = setInterval(function () {
  2998. if (!cm.hasFocus()) { onBlur(cm); }
  2999. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  3000. }, cm.options.cursorBlinkRate); }
  3001. else if (cm.options.cursorBlinkRate < 0)
  3002. { display.cursorDiv.style.visibility = "hidden"; }
  3003. }
  3004. function ensureFocus(cm) {
  3005. if (!cm.hasFocus()) {
  3006. cm.display.input.focus();
  3007. if (!cm.state.focused) { onFocus(cm); }
  3008. }
  3009. }
  3010. function delayBlurEvent(cm) {
  3011. cm.state.delayingBlurEvent = true;
  3012. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  3013. cm.state.delayingBlurEvent = false;
  3014. if (cm.state.focused) { onBlur(cm); }
  3015. } }, 100);
  3016. }
  3017. function onFocus(cm, e) {
  3018. if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  3019. if (cm.options.readOnly == "nocursor") { return }
  3020. if (!cm.state.focused) {
  3021. signal(cm, "focus", cm, e);
  3022. cm.state.focused = true;
  3023. addClass(cm.display.wrapper, "CodeMirror-focused");
  3024. // This test prevents this from firing when a context
  3025. // menu is closed (since the input reset would kill the
  3026. // select-all detection hack)
  3027. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3028. cm.display.input.reset();
  3029. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3030. }
  3031. cm.display.input.receivedFocus();
  3032. }
  3033. restartBlink(cm);
  3034. }
  3035. function onBlur(cm, e) {
  3036. if (cm.state.delayingBlurEvent) { return }
  3037. if (cm.state.focused) {
  3038. signal(cm, "blur", cm, e);
  3039. cm.state.focused = false;
  3040. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3041. }
  3042. clearInterval(cm.display.blinker);
  3043. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3044. }
  3045. // Read the actual heights of the rendered lines, and update their
  3046. // stored heights to match.
  3047. function updateHeightsInViewport(cm) {
  3048. var display = cm.display;
  3049. var prevBottom = display.lineDiv.offsetTop;
  3050. for (var i = 0; i < display.view.length; i++) {
  3051. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3052. var height = (void 0), width = 0;
  3053. if (cur.hidden) { continue }
  3054. if (ie && ie_version < 8) {
  3055. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3056. height = bot - prevBottom;
  3057. prevBottom = bot;
  3058. } else {
  3059. var box = cur.node.getBoundingClientRect();
  3060. height = box.bottom - box.top;
  3061. // Check that lines don't extend past the right of the current
  3062. // editor width
  3063. if (!wrapping && cur.text.firstChild)
  3064. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3065. }
  3066. var diff = cur.line.height - height;
  3067. if (diff > .005 || diff < -.005) {
  3068. updateLineHeight(cur.line, height);
  3069. updateWidgetHeight(cur.line);
  3070. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3071. { updateWidgetHeight(cur.rest[j]); } }
  3072. }
  3073. if (width > cm.display.sizerWidth) {
  3074. var chWidth = Math.ceil(width / charWidth(cm.display));
  3075. if (chWidth > cm.display.maxLineLength) {
  3076. cm.display.maxLineLength = chWidth;
  3077. cm.display.maxLine = cur.line;
  3078. cm.display.maxLineChanged = true;
  3079. }
  3080. }
  3081. }
  3082. }
  3083. // Read and store the height of line widgets associated with the
  3084. // given line.
  3085. function updateWidgetHeight(line) {
  3086. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3087. var w = line.widgets[i], parent = w.node.parentNode;
  3088. if (parent) { w.height = parent.offsetHeight; }
  3089. } }
  3090. }
  3091. // Compute the lines that are visible in a given viewport (defaults
  3092. // the the current scroll position). viewport may contain top,
  3093. // height, and ensure (see op.scrollToPos) properties.
  3094. function visibleLines(display, doc, viewport) {
  3095. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3096. top = Math.floor(top - paddingTop(display));
  3097. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3098. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3099. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3100. // forces those lines into the viewport (if possible).
  3101. if (viewport && viewport.ensure) {
  3102. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3103. if (ensureFrom < from) {
  3104. from = ensureFrom;
  3105. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3106. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3107. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3108. to = ensureTo;
  3109. }
  3110. }
  3111. return {from: from, to: Math.max(to, from + 1)}
  3112. }
  3113. // SCROLLING THINGS INTO VIEW
  3114. // If an editor sits on the top or bottom of the window, partially
  3115. // scrolled out of view, this ensures that the cursor is visible.
  3116. function maybeScrollWindow(cm, rect) {
  3117. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3118. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3119. if (rect.top + box.top < 0) { doScroll = true; }
  3120. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3121. if (doScroll != null && !phantom) {
  3122. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
  3123. cm.display.lineSpace.appendChild(scrollNode);
  3124. scrollNode.scrollIntoView(doScroll);
  3125. cm.display.lineSpace.removeChild(scrollNode);
  3126. }
  3127. }
  3128. // Scroll a given position into view (immediately), verifying that
  3129. // it actually became visible (as line heights are accurately
  3130. // measured, the position of something may 'drift' during drawing).
  3131. function scrollPosIntoView(cm, pos, end, margin) {
  3132. if (margin == null) { margin = 0; }
  3133. var rect;
  3134. if (!cm.options.lineWrapping && pos == end) {
  3135. // Set pos and end to the cursor positions around the character pos sticks to
  3136. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3137. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3138. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3139. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3140. }
  3141. for (var limit = 0; limit < 5; limit++) {
  3142. var changed = false;
  3143. var coords = cursorCoords(cm, pos);
  3144. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3145. rect = {left: Math.min(coords.left, endCoords.left),
  3146. top: Math.min(coords.top, endCoords.top) - margin,
  3147. right: Math.max(coords.left, endCoords.left),
  3148. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3149. var scrollPos = calculateScrollPos(cm, rect);
  3150. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3151. if (scrollPos.scrollTop != null) {
  3152. updateScrollTop(cm, scrollPos.scrollTop);
  3153. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3154. }
  3155. if (scrollPos.scrollLeft != null) {
  3156. setScrollLeft(cm, scrollPos.scrollLeft);
  3157. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3158. }
  3159. if (!changed) { break }
  3160. }
  3161. return rect
  3162. }
  3163. // Scroll a given set of coordinates into view (immediately).
  3164. function scrollIntoView(cm, rect) {
  3165. var scrollPos = calculateScrollPos(cm, rect);
  3166. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3167. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3168. }
  3169. // Calculate a new scroll position needed to scroll the given
  3170. // rectangle into view. Returns an object with scrollTop and
  3171. // scrollLeft properties. When these are undefined, the
  3172. // vertical/horizontal position does not need to be adjusted.
  3173. function calculateScrollPos(cm, rect) {
  3174. var display = cm.display, snapMargin = textHeight(cm.display);
  3175. if (rect.top < 0) { rect.top = 0; }
  3176. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3177. var screen = displayHeight(cm), result = {};
  3178. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3179. var docBottom = cm.doc.height + paddingVert(display);
  3180. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3181. if (rect.top < screentop) {
  3182. result.scrollTop = atTop ? 0 : rect.top;
  3183. } else if (rect.bottom > screentop + screen) {
  3184. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3185. if (newTop != screentop) { result.scrollTop = newTop; }
  3186. }
  3187. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  3188. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  3189. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  3190. var tooWide = rect.right - rect.left > screenw;
  3191. if (tooWide) { rect.right = rect.left + screenw; }
  3192. if (rect.left < 10)
  3193. { result.scrollLeft = 0; }
  3194. else if (rect.left < screenleft)
  3195. { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  3196. else if (rect.right > screenw + screenleft - 3)
  3197. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3198. return result
  3199. }
  3200. // Store a relative adjustment to the scroll position in the current
  3201. // operation (to be applied when the operation finishes).
  3202. function addToScrollTop(cm, top) {
  3203. if (top == null) { return }
  3204. resolveScrollToPos(cm);
  3205. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3206. }
  3207. // Make sure that at the end of the operation the current cursor is
  3208. // shown.
  3209. function ensureCursorVisible(cm) {
  3210. resolveScrollToPos(cm);
  3211. var cur = cm.getCursor();
  3212. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3213. }
  3214. function scrollToCoords(cm, x, y) {
  3215. if (x != null || y != null) { resolveScrollToPos(cm); }
  3216. if (x != null) { cm.curOp.scrollLeft = x; }
  3217. if (y != null) { cm.curOp.scrollTop = y; }
  3218. }
  3219. function scrollToRange(cm, range) {
  3220. resolveScrollToPos(cm);
  3221. cm.curOp.scrollToPos = range;
  3222. }
  3223. // When an operation has its scrollToPos property set, and another
  3224. // scroll action is applied before the end of the operation, this
  3225. // 'simulates' scrolling that position into view in a cheap way, so
  3226. // that the effect of intermediate scroll commands is not ignored.
  3227. function resolveScrollToPos(cm) {
  3228. var range = cm.curOp.scrollToPos;
  3229. if (range) {
  3230. cm.curOp.scrollToPos = null;
  3231. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3232. scrollToCoordsRange(cm, from, to, range.margin);
  3233. }
  3234. }
  3235. function scrollToCoordsRange(cm, from, to, margin) {
  3236. var sPos = calculateScrollPos(cm, {
  3237. left: Math.min(from.left, to.left),
  3238. top: Math.min(from.top, to.top) - margin,
  3239. right: Math.max(from.right, to.right),
  3240. bottom: Math.max(from.bottom, to.bottom) + margin
  3241. });
  3242. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3243. }
  3244. // Sync the scrollable area and scrollbars, ensure the viewport
  3245. // covers the visible area.
  3246. function updateScrollTop(cm, val) {
  3247. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3248. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3249. setScrollTop(cm, val, true);
  3250. if (gecko) { updateDisplaySimple(cm); }
  3251. startWorker(cm, 100);
  3252. }
  3253. function setScrollTop(cm, val, forceScroll) {
  3254. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3255. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3256. cm.doc.scrollTop = val;
  3257. cm.display.scrollbars.setScrollTop(val);
  3258. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3259. }
  3260. // Sync scroller and scrollbar, ensure the gutter elements are
  3261. // aligned.
  3262. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3263. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3264. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3265. cm.doc.scrollLeft = val;
  3266. alignHorizontally(cm);
  3267. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3268. cm.display.scrollbars.setScrollLeft(val);
  3269. }
  3270. // SCROLLBARS
  3271. // Prepare DOM reads needed to update the scrollbars. Done in one
  3272. // shot to minimize update/measure roundtrips.
  3273. function measureForScrollbars(cm) {
  3274. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3275. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3276. return {
  3277. clientHeight: d.scroller.clientHeight,
  3278. viewHeight: d.wrapper.clientHeight,
  3279. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3280. viewWidth: d.wrapper.clientWidth,
  3281. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3282. docHeight: docH,
  3283. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3284. nativeBarWidth: d.nativeBarWidth,
  3285. gutterWidth: gutterW
  3286. }
  3287. }
  3288. var NativeScrollbars = function(place, scroll, cm) {
  3289. this.cm = cm;
  3290. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3291. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3292. vert.tabIndex = horiz.tabIndex = -1;
  3293. place(vert); place(horiz);
  3294. on(vert, "scroll", function () {
  3295. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3296. });
  3297. on(horiz, "scroll", function () {
  3298. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3299. });
  3300. this.checkedZeroWidth = false;
  3301. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3302. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3303. };
  3304. NativeScrollbars.prototype.update = function (measure) {
  3305. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3306. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3307. var sWidth = measure.nativeBarWidth;
  3308. if (needsV) {
  3309. this.vert.style.display = "block";
  3310. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3311. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3312. // A bug in IE8 can cause this value to be negative, so guard it.
  3313. this.vert.firstChild.style.height =
  3314. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3315. } else {
  3316. this.vert.style.display = "";
  3317. this.vert.firstChild.style.height = "0";
  3318. }
  3319. if (needsH) {
  3320. this.horiz.style.display = "block";
  3321. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3322. this.horiz.style.left = measure.barLeft + "px";
  3323. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3324. this.horiz.firstChild.style.width =
  3325. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3326. } else {
  3327. this.horiz.style.display = "";
  3328. this.horiz.firstChild.style.width = "0";
  3329. }
  3330. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3331. if (sWidth == 0) { this.zeroWidthHack(); }
  3332. this.checkedZeroWidth = true;
  3333. }
  3334. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3335. };
  3336. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3337. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3338. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3339. };
  3340. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3341. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3342. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3343. };
  3344. NativeScrollbars.prototype.zeroWidthHack = function () {
  3345. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3346. this.horiz.style.height = this.vert.style.width = w;
  3347. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3348. this.disableHoriz = new Delayed;
  3349. this.disableVert = new Delayed;
  3350. };
  3351. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3352. bar.style.pointerEvents = "auto";
  3353. function maybeDisable() {
  3354. // To find out whether the scrollbar is still visible, we
  3355. // check whether the element under the pixel in the bottom
  3356. // right corner of the scrollbar box is the scrollbar box
  3357. // itself (when the bar is still visible) or its filler child
  3358. // (when the bar is hidden). If it is still visible, we keep
  3359. // it enabled, if it's hidden, we disable pointer events.
  3360. var box = bar.getBoundingClientRect();
  3361. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3362. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3363. if (elt != bar) { bar.style.pointerEvents = "none"; }
  3364. else { delay.set(1000, maybeDisable); }
  3365. }
  3366. delay.set(1000, maybeDisable);
  3367. };
  3368. NativeScrollbars.prototype.clear = function () {
  3369. var parent = this.horiz.parentNode;
  3370. parent.removeChild(this.horiz);
  3371. parent.removeChild(this.vert);
  3372. };
  3373. var NullScrollbars = function () {};
  3374. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3375. NullScrollbars.prototype.setScrollLeft = function () {};
  3376. NullScrollbars.prototype.setScrollTop = function () {};
  3377. NullScrollbars.prototype.clear = function () {};
  3378. function updateScrollbars(cm, measure) {
  3379. if (!measure) { measure = measureForScrollbars(cm); }
  3380. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3381. updateScrollbarsInner(cm, measure);
  3382. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3383. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3384. { updateHeightsInViewport(cm); }
  3385. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3386. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3387. }
  3388. }
  3389. // Re-synchronize the fake scrollbars with the actual size of the
  3390. // content.
  3391. function updateScrollbarsInner(cm, measure) {
  3392. var d = cm.display;
  3393. var sizes = d.scrollbars.update(measure);
  3394. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3395. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3396. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3397. if (sizes.right && sizes.bottom) {
  3398. d.scrollbarFiller.style.display = "block";
  3399. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3400. d.scrollbarFiller.style.width = sizes.right + "px";
  3401. } else { d.scrollbarFiller.style.display = ""; }
  3402. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3403. d.gutterFiller.style.display = "block";
  3404. d.gutterFiller.style.height = sizes.bottom + "px";
  3405. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3406. } else { d.gutterFiller.style.display = ""; }
  3407. }
  3408. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3409. function initScrollbars(cm) {
  3410. if (cm.display.scrollbars) {
  3411. cm.display.scrollbars.clear();
  3412. if (cm.display.scrollbars.addClass)
  3413. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3414. }
  3415. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3416. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3417. // Prevent clicks in the scrollbars from killing focus
  3418. on(node, "mousedown", function () {
  3419. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3420. });
  3421. node.setAttribute("cm-not-content", "true");
  3422. }, function (pos, axis) {
  3423. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3424. else { updateScrollTop(cm, pos); }
  3425. }, cm);
  3426. if (cm.display.scrollbars.addClass)
  3427. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3428. }
  3429. // Operations are used to wrap a series of changes to the editor
  3430. // state in such a way that each change won't have to update the
  3431. // cursor and display (which would be awkward, slow, and
  3432. // error-prone). Instead, display updates are batched and then all
  3433. // combined and executed at once.
  3434. var nextOpId = 0;
  3435. // Start a new operation.
  3436. function startOperation(cm) {
  3437. cm.curOp = {
  3438. cm: cm,
  3439. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3440. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3441. forceUpdate: false, // Used to force a redraw
  3442. updateInput: 0, // Whether to reset the input textarea
  3443. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3444. changeObjs: null, // Accumulated changes, for firing change events
  3445. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3446. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3447. selectionChanged: false, // Whether the selection needs to be redrawn
  3448. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3449. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3450. scrollToPos: null, // Used to scroll to a specific position
  3451. focus: false,
  3452. id: ++nextOpId, // Unique ID
  3453. markArrays: null // Used by addMarkedSpan
  3454. };
  3455. pushOperation(cm.curOp);
  3456. }
  3457. // Finish an operation, updating the display and signalling delayed events
  3458. function endOperation(cm) {
  3459. var op = cm.curOp;
  3460. if (op) { finishOperation(op, function (group) {
  3461. for (var i = 0; i < group.ops.length; i++)
  3462. { group.ops[i].cm.curOp = null; }
  3463. endOperations(group);
  3464. }); }
  3465. }
  3466. // The DOM updates done when an operation finishes are batched so
  3467. // that the minimum number of relayouts are required.
  3468. function endOperations(group) {
  3469. var ops = group.ops;
  3470. for (var i = 0; i < ops.length; i++) // Read DOM
  3471. { endOperation_R1(ops[i]); }
  3472. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3473. { endOperation_W1(ops[i$1]); }
  3474. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3475. { endOperation_R2(ops[i$2]); }
  3476. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3477. { endOperation_W2(ops[i$3]); }
  3478. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3479. { endOperation_finish(ops[i$4]); }
  3480. }
  3481. function endOperation_R1(op) {
  3482. var cm = op.cm, display = cm.display;
  3483. maybeClipScrollbars(cm);
  3484. if (op.updateMaxLine) { findMaxLine(cm); }
  3485. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3486. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3487. op.scrollToPos.to.line >= display.viewTo) ||
  3488. display.maxLineChanged && cm.options.lineWrapping;
  3489. op.update = op.mustUpdate &&
  3490. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3491. }
  3492. function endOperation_W1(op) {
  3493. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3494. }
  3495. function endOperation_R2(op) {
  3496. var cm = op.cm, display = cm.display;
  3497. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3498. op.barMeasure = measureForScrollbars(cm);
  3499. // If the max line changed since it was last measured, measure it,
  3500. // and ensure the document's width matches it.
  3501. // updateDisplay_W2 will use these properties to do the actual resizing
  3502. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3503. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3504. cm.display.sizerWidth = op.adjustWidthTo;
  3505. op.barMeasure.scrollWidth =
  3506. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3507. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3508. }
  3509. if (op.updatedDisplay || op.selectionChanged)
  3510. { op.preparedSelection = display.input.prepareSelection(); }
  3511. }
  3512. function endOperation_W2(op) {
  3513. var cm = op.cm;
  3514. if (op.adjustWidthTo != null) {
  3515. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3516. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3517. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3518. cm.display.maxLineChanged = false;
  3519. }
  3520. var takeFocus = op.focus && op.focus == activeElt();
  3521. if (op.preparedSelection)
  3522. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3523. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3524. { updateScrollbars(cm, op.barMeasure); }
  3525. if (op.updatedDisplay)
  3526. { setDocumentHeight(cm, op.barMeasure); }
  3527. if (op.selectionChanged) { restartBlink(cm); }
  3528. if (cm.state.focused && op.updateInput)
  3529. { cm.display.input.reset(op.typing); }
  3530. if (takeFocus) { ensureFocus(op.cm); }
  3531. }
  3532. function endOperation_finish(op) {
  3533. var cm = op.cm, display = cm.display, doc = cm.doc;
  3534. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3535. // Abort mouse wheel delta measurement, when scrolling explicitly
  3536. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3537. { display.wheelStartX = display.wheelStartY = null; }
  3538. // Propagate the scroll position to the actual DOM scroller
  3539. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3540. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3541. // If we need to scroll a specific position into view, do so.
  3542. if (op.scrollToPos) {
  3543. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3544. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3545. maybeScrollWindow(cm, rect);
  3546. }
  3547. // Fire events for markers that are hidden/unidden by editing or
  3548. // undoing
  3549. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3550. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3551. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3552. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3553. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3554. if (display.wrapper.offsetHeight)
  3555. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3556. // Fire change events, and delayed event handlers
  3557. if (op.changeObjs)
  3558. { signal(cm, "changes", cm, op.changeObjs); }
  3559. if (op.update)
  3560. { op.update.finish(); }
  3561. }
  3562. // Run the given function in an operation
  3563. function runInOp(cm, f) {
  3564. if (cm.curOp) { return f() }
  3565. startOperation(cm);
  3566. try { return f() }
  3567. finally { endOperation(cm); }
  3568. }
  3569. // Wraps a function in an operation. Returns the wrapped function.
  3570. function operation(cm, f) {
  3571. return function() {
  3572. if (cm.curOp) { return f.apply(cm, arguments) }
  3573. startOperation(cm);
  3574. try { return f.apply(cm, arguments) }
  3575. finally { endOperation(cm); }
  3576. }
  3577. }
  3578. // Used to add methods to editor and doc instances, wrapping them in
  3579. // operations.
  3580. function methodOp(f) {
  3581. return function() {
  3582. if (this.curOp) { return f.apply(this, arguments) }
  3583. startOperation(this);
  3584. try { return f.apply(this, arguments) }
  3585. finally { endOperation(this); }
  3586. }
  3587. }
  3588. function docMethodOp(f) {
  3589. return function() {
  3590. var cm = this.cm;
  3591. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3592. startOperation(cm);
  3593. try { return f.apply(this, arguments) }
  3594. finally { endOperation(cm); }
  3595. }
  3596. }
  3597. // HIGHLIGHT WORKER
  3598. function startWorker(cm, time) {
  3599. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3600. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3601. }
  3602. function highlightWorker(cm) {
  3603. var doc = cm.doc;
  3604. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3605. var end = +new Date + cm.options.workTime;
  3606. var context = getContextBefore(cm, doc.highlightFrontier);
  3607. var changedLines = [];
  3608. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3609. if (context.line >= cm.display.viewFrom) { // Visible
  3610. var oldStyles = line.styles;
  3611. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3612. var highlighted = highlightLine(cm, line, context, true);
  3613. if (resetState) { context.state = resetState; }
  3614. line.styles = highlighted.styles;
  3615. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3616. if (newCls) { line.styleClasses = newCls; }
  3617. else if (oldCls) { line.styleClasses = null; }
  3618. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3619. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3620. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3621. if (ischange) { changedLines.push(context.line); }
  3622. line.stateAfter = context.save();
  3623. context.nextLine();
  3624. } else {
  3625. if (line.text.length <= cm.options.maxHighlightLength)
  3626. { processLine(cm, line.text, context); }
  3627. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3628. context.nextLine();
  3629. }
  3630. if (+new Date > end) {
  3631. startWorker(cm, cm.options.workDelay);
  3632. return true
  3633. }
  3634. });
  3635. doc.highlightFrontier = context.line;
  3636. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3637. if (changedLines.length) { runInOp(cm, function () {
  3638. for (var i = 0; i < changedLines.length; i++)
  3639. { regLineChange(cm, changedLines[i], "text"); }
  3640. }); }
  3641. }
  3642. // DISPLAY DRAWING
  3643. var DisplayUpdate = function(cm, viewport, force) {
  3644. var display = cm.display;
  3645. this.viewport = viewport;
  3646. // Store some values that we'll need later (but don't want to force a relayout for)
  3647. this.visible = visibleLines(display, cm.doc, viewport);
  3648. this.editorIsHidden = !display.wrapper.offsetWidth;
  3649. this.wrapperHeight = display.wrapper.clientHeight;
  3650. this.wrapperWidth = display.wrapper.clientWidth;
  3651. this.oldDisplayWidth = displayWidth(cm);
  3652. this.force = force;
  3653. this.dims = getDimensions(cm);
  3654. this.events = [];
  3655. };
  3656. DisplayUpdate.prototype.signal = function (emitter, type) {
  3657. if (hasHandler(emitter, type))
  3658. { this.events.push(arguments); }
  3659. };
  3660. DisplayUpdate.prototype.finish = function () {
  3661. for (var i = 0; i < this.events.length; i++)
  3662. { signal.apply(null, this.events[i]); }
  3663. };
  3664. function maybeClipScrollbars(cm) {
  3665. var display = cm.display;
  3666. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3667. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3668. display.heightForcer.style.height = scrollGap(cm) + "px";
  3669. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3670. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3671. display.scrollbarsClipped = true;
  3672. }
  3673. }
  3674. function selectionSnapshot(cm) {
  3675. if (cm.hasFocus()) { return null }
  3676. var active = activeElt();
  3677. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3678. var result = {activeElt: active};
  3679. if (window.getSelection) {
  3680. var sel = window.getSelection();
  3681. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3682. result.anchorNode = sel.anchorNode;
  3683. result.anchorOffset = sel.anchorOffset;
  3684. result.focusNode = sel.focusNode;
  3685. result.focusOffset = sel.focusOffset;
  3686. }
  3687. }
  3688. return result
  3689. }
  3690. function restoreSelection(snapshot) {
  3691. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3692. snapshot.activeElt.focus();
  3693. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  3694. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3695. var sel = window.getSelection(), range = document.createRange();
  3696. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3697. range.collapse(false);
  3698. sel.removeAllRanges();
  3699. sel.addRange(range);
  3700. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3701. }
  3702. }
  3703. // Does the actual updating of the line display. Bails out
  3704. // (returning false) when there is nothing to be done and forced is
  3705. // false.
  3706. function updateDisplayIfNeeded(cm, update) {
  3707. var display = cm.display, doc = cm.doc;
  3708. if (update.editorIsHidden) {
  3709. resetView(cm);
  3710. return false
  3711. }
  3712. // Bail out if the visible area is already rendered and nothing changed.
  3713. if (!update.force &&
  3714. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3715. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3716. display.renderedView == display.view && countDirtyView(cm) == 0)
  3717. { return false }
  3718. if (maybeUpdateLineNumberWidth(cm)) {
  3719. resetView(cm);
  3720. update.dims = getDimensions(cm);
  3721. }
  3722. // Compute a suitable new viewport (from & to)
  3723. var end = doc.first + doc.size;
  3724. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3725. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3726. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3727. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3728. if (sawCollapsedSpans) {
  3729. from = visualLineNo(cm.doc, from);
  3730. to = visualLineEndNo(cm.doc, to);
  3731. }
  3732. var different = from != display.viewFrom || to != display.viewTo ||
  3733. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3734. adjustView(cm, from, to);
  3735. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3736. // Position the mover div to align with the current scroll position
  3737. cm.display.mover.style.top = display.viewOffset + "px";
  3738. var toUpdate = countDirtyView(cm);
  3739. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3740. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3741. { return false }
  3742. // For big changes, we hide the enclosing element during the
  3743. // update, since that speeds up the operations on most browsers.
  3744. var selSnapshot = selectionSnapshot(cm);
  3745. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3746. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3747. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3748. display.renderedView = display.view;
  3749. // There might have been a widget with a focused element that got
  3750. // hidden or updated, if so re-focus it.
  3751. restoreSelection(selSnapshot);
  3752. // Prevent selection and cursors from interfering with the scroll
  3753. // width and height.
  3754. removeChildren(display.cursorDiv);
  3755. removeChildren(display.selectionDiv);
  3756. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3757. if (different) {
  3758. display.lastWrapHeight = update.wrapperHeight;
  3759. display.lastWrapWidth = update.wrapperWidth;
  3760. startWorker(cm, 400);
  3761. }
  3762. display.updateLineNumbers = null;
  3763. return true
  3764. }
  3765. function postUpdateDisplay(cm, update) {
  3766. var viewport = update.viewport;
  3767. for (var first = true;; first = false) {
  3768. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3769. // Clip forced viewport to actual scrollable area.
  3770. if (viewport && viewport.top != null)
  3771. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3772. // Updated line heights might result in the drawn area not
  3773. // actually covering the viewport. Keep looping until it does.
  3774. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3775. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3776. { break }
  3777. } else if (first) {
  3778. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3779. }
  3780. if (!updateDisplayIfNeeded(cm, update)) { break }
  3781. updateHeightsInViewport(cm);
  3782. var barMeasure = measureForScrollbars(cm);
  3783. updateSelection(cm);
  3784. updateScrollbars(cm, barMeasure);
  3785. setDocumentHeight(cm, barMeasure);
  3786. update.force = false;
  3787. }
  3788. update.signal(cm, "update", cm);
  3789. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3790. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3791. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3792. }
  3793. }
  3794. function updateDisplaySimple(cm, viewport) {
  3795. var update = new DisplayUpdate(cm, viewport);
  3796. if (updateDisplayIfNeeded(cm, update)) {
  3797. updateHeightsInViewport(cm);
  3798. postUpdateDisplay(cm, update);
  3799. var barMeasure = measureForScrollbars(cm);
  3800. updateSelection(cm);
  3801. updateScrollbars(cm, barMeasure);
  3802. setDocumentHeight(cm, barMeasure);
  3803. update.finish();
  3804. }
  3805. }
  3806. // Sync the actual display DOM structure with display.view, removing
  3807. // nodes for lines that are no longer in view, and creating the ones
  3808. // that are not there yet, and updating the ones that are out of
  3809. // date.
  3810. function patchDisplay(cm, updateNumbersFrom, dims) {
  3811. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3812. var container = display.lineDiv, cur = container.firstChild;
  3813. function rm(node) {
  3814. var next = node.nextSibling;
  3815. // Works around a throw-scroll bug in OS X Webkit
  3816. if (webkit && mac && cm.display.currentWheelTarget == node)
  3817. { node.style.display = "none"; }
  3818. else
  3819. { node.parentNode.removeChild(node); }
  3820. return next
  3821. }
  3822. var view = display.view, lineN = display.viewFrom;
  3823. // Loop over the elements in the view, syncing cur (the DOM nodes
  3824. // in display.lineDiv) with the view as we go.
  3825. for (var i = 0; i < view.length; i++) {
  3826. var lineView = view[i];
  3827. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3828. var node = buildLineElement(cm, lineView, lineN, dims);
  3829. container.insertBefore(node, cur);
  3830. } else { // Already drawn
  3831. while (cur != lineView.node) { cur = rm(cur); }
  3832. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3833. updateNumbersFrom <= lineN && lineView.lineNumber;
  3834. if (lineView.changes) {
  3835. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3836. updateLineForChanges(cm, lineView, lineN, dims);
  3837. }
  3838. if (updateNumber) {
  3839. removeChildren(lineView.lineNumber);
  3840. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3841. }
  3842. cur = lineView.node.nextSibling;
  3843. }
  3844. lineN += lineView.size;
  3845. }
  3846. while (cur) { cur = rm(cur); }
  3847. }
  3848. function updateGutterSpace(display) {
  3849. var width = display.gutters.offsetWidth;
  3850. display.sizer.style.marginLeft = width + "px";
  3851. // Send an event to consumers responding to changes in gutter width.
  3852. signalLater(display, "gutterChanged", display);
  3853. }
  3854. function setDocumentHeight(cm, measure) {
  3855. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3856. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3857. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3858. }
  3859. // Re-align line numbers and gutter marks to compensate for
  3860. // horizontal scrolling.
  3861. function alignHorizontally(cm) {
  3862. var display = cm.display, view = display.view;
  3863. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3864. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3865. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3866. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3867. if (cm.options.fixedGutter) {
  3868. if (view[i].gutter)
  3869. { view[i].gutter.style.left = left; }
  3870. if (view[i].gutterBackground)
  3871. { view[i].gutterBackground.style.left = left; }
  3872. }
  3873. var align = view[i].alignable;
  3874. if (align) { for (var j = 0; j < align.length; j++)
  3875. { align[j].style.left = left; } }
  3876. } }
  3877. if (cm.options.fixedGutter)
  3878. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3879. }
  3880. // Used to ensure that the line number gutter is still the right
  3881. // size for the current document size. Returns true when an update
  3882. // is needed.
  3883. function maybeUpdateLineNumberWidth(cm) {
  3884. if (!cm.options.lineNumbers) { return false }
  3885. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3886. if (last.length != display.lineNumChars) {
  3887. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3888. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3889. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3890. display.lineGutter.style.width = "";
  3891. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3892. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3893. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3894. display.lineGutter.style.width = display.lineNumWidth + "px";
  3895. updateGutterSpace(cm.display);
  3896. return true
  3897. }
  3898. return false
  3899. }
  3900. function getGutters(gutters, lineNumbers) {
  3901. var result = [], sawLineNumbers = false;
  3902. for (var i = 0; i < gutters.length; i++) {
  3903. var name = gutters[i], style = null;
  3904. if (typeof name != "string") { style = name.style; name = name.className; }
  3905. if (name == "CodeMirror-linenumbers") {
  3906. if (!lineNumbers) { continue }
  3907. else { sawLineNumbers = true; }
  3908. }
  3909. result.push({className: name, style: style});
  3910. }
  3911. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  3912. return result
  3913. }
  3914. // Rebuild the gutter elements, ensure the margin to the left of the
  3915. // code matches their width.
  3916. function renderGutters(display) {
  3917. var gutters = display.gutters, specs = display.gutterSpecs;
  3918. removeChildren(gutters);
  3919. display.lineGutter = null;
  3920. for (var i = 0; i < specs.length; ++i) {
  3921. var ref = specs[i];
  3922. var className = ref.className;
  3923. var style = ref.style;
  3924. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  3925. if (style) { gElt.style.cssText = style; }
  3926. if (className == "CodeMirror-linenumbers") {
  3927. display.lineGutter = gElt;
  3928. gElt.style.width = (display.lineNumWidth || 1) + "px";
  3929. }
  3930. }
  3931. gutters.style.display = specs.length ? "" : "none";
  3932. updateGutterSpace(display);
  3933. }
  3934. function updateGutters(cm) {
  3935. renderGutters(cm.display);
  3936. regChange(cm);
  3937. alignHorizontally(cm);
  3938. }
  3939. // The display handles the DOM integration, both for input reading
  3940. // and content drawing. It holds references to DOM nodes and
  3941. // display-related state.
  3942. function Display(place, doc, input, options) {
  3943. var d = this;
  3944. this.input = input;
  3945. // Covers bottom-right square when both scrollbars are present.
  3946. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  3947. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  3948. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  3949. // and h scrollbar is present.
  3950. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  3951. d.gutterFiller.setAttribute("cm-not-content", "true");
  3952. // Will contain the actual code, positioned to cover the viewport.
  3953. d.lineDiv = eltP("div", null, "CodeMirror-code");
  3954. // Elements are added to these to represent selection and cursors.
  3955. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  3956. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  3957. // A visibility: hidden element used to find the size of things.
  3958. d.measure = elt("div", null, "CodeMirror-measure");
  3959. // When lines outside of the viewport are measured, they are drawn in this.
  3960. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  3961. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  3962. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  3963. null, "position: relative; outline: none");
  3964. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  3965. // Moved around its parent to cover visible view.
  3966. d.mover = elt("div", [lines], null, "position: relative");
  3967. // Set to the height of the document, allowing scrolling.
  3968. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  3969. d.sizerWidth = null;
  3970. // Behavior of elts with overflow: auto and padding is
  3971. // inconsistent across browsers. This is used to ensure the
  3972. // scrollable area is big enough.
  3973. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  3974. // Will contain the gutters, if any.
  3975. d.gutters = elt("div", null, "CodeMirror-gutters");
  3976. d.lineGutter = null;
  3977. // Actual scrollable element.
  3978. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  3979. d.scroller.setAttribute("tabIndex", "-1");
  3980. // The element in which the editor lives.
  3981. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  3982. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  3983. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  3984. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  3985. if (place) {
  3986. if (place.appendChild) { place.appendChild(d.wrapper); }
  3987. else { place(d.wrapper); }
  3988. }
  3989. // Current rendered range (may be bigger than the view window).
  3990. d.viewFrom = d.viewTo = doc.first;
  3991. d.reportedViewFrom = d.reportedViewTo = doc.first;
  3992. // Information about the rendered lines.
  3993. d.view = [];
  3994. d.renderedView = null;
  3995. // Holds info about a single rendered line when it was rendered
  3996. // for measurement, while not in view.
  3997. d.externalMeasured = null;
  3998. // Empty space (in pixels) above the view
  3999. d.viewOffset = 0;
  4000. d.lastWrapHeight = d.lastWrapWidth = 0;
  4001. d.updateLineNumbers = null;
  4002. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  4003. d.scrollbarsClipped = false;
  4004. // Used to only resize the line number gutter when necessary (when
  4005. // the amount of lines crosses a boundary that makes its width change)
  4006. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  4007. // Set to true when a non-horizontal-scrolling line widget is
  4008. // added. As an optimization, line widget aligning is skipped when
  4009. // this is false.
  4010. d.alignWidgets = false;
  4011. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4012. // Tracks the maximum line length so that the horizontal scrollbar
  4013. // can be kept static when scrolling.
  4014. d.maxLine = null;
  4015. d.maxLineLength = 0;
  4016. d.maxLineChanged = false;
  4017. // Used for measuring wheel scrolling granularity
  4018. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4019. // True when shift is held down.
  4020. d.shift = false;
  4021. // Used to track whether anything happened since the context menu
  4022. // was opened.
  4023. d.selForContextMenu = null;
  4024. d.activeTouch = null;
  4025. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4026. renderGutters(d);
  4027. input.init(d);
  4028. }
  4029. // Since the delta values reported on mouse wheel events are
  4030. // unstandardized between browsers and even browser versions, and
  4031. // generally horribly unpredictable, this code starts by measuring
  4032. // the scroll effect that the first few mouse wheel events have,
  4033. // and, from that, detects the way it can convert deltas to pixel
  4034. // offsets afterwards.
  4035. //
  4036. // The reason we want to know the amount a wheel event will scroll
  4037. // is that it gives us a chance to update the display before the
  4038. // actual scrolling happens, reducing flickering.
  4039. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4040. // Fill in a browser-detected starting value on browsers where we
  4041. // know one. These don't have to be accurate -- the result of them
  4042. // being wrong would just be a slight flicker on the first wheel
  4043. // scroll (if it is large enough).
  4044. if (ie) { wheelPixelsPerUnit = -.53; }
  4045. else if (gecko) { wheelPixelsPerUnit = 15; }
  4046. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4047. else if (safari) { wheelPixelsPerUnit = -1/3; }
  4048. function wheelEventDelta(e) {
  4049. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4050. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4051. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4052. else if (dy == null) { dy = e.wheelDelta; }
  4053. return {x: dx, y: dy}
  4054. }
  4055. function wheelEventPixels(e) {
  4056. var delta = wheelEventDelta(e);
  4057. delta.x *= wheelPixelsPerUnit;
  4058. delta.y *= wheelPixelsPerUnit;
  4059. return delta
  4060. }
  4061. function onScrollWheel(cm, e) {
  4062. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4063. var display = cm.display, scroll = display.scroller;
  4064. // Quit if there's nothing to scroll here
  4065. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4066. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4067. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4068. // Webkit browsers on OS X abort momentum scrolls when the target
  4069. // of the scroll event is removed from the scrollable element.
  4070. // This hack (see related code in patchDisplay) makes sure the
  4071. // element is kept around.
  4072. if (dy && mac && webkit) {
  4073. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4074. for (var i = 0; i < view.length; i++) {
  4075. if (view[i].node == cur) {
  4076. cm.display.currentWheelTarget = cur;
  4077. break outer
  4078. }
  4079. }
  4080. }
  4081. }
  4082. // On some browsers, horizontal scrolling will cause redraws to
  4083. // happen before the gutter has been realigned, causing it to
  4084. // wriggle around in a most unseemly way. When we have an
  4085. // estimated pixels/delta value, we just handle horizontal
  4086. // scrolling entirely here. It'll be slightly off from native, but
  4087. // better than glitching out.
  4088. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4089. if (dy && canScrollY)
  4090. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  4091. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  4092. // Only prevent default scrolling if vertical scrolling is
  4093. // actually possible. Otherwise, it causes vertical scroll
  4094. // jitter on OSX trackpads when deltaX is small and deltaY
  4095. // is large (issue #3579)
  4096. if (!dy || (dy && canScrollY))
  4097. { e_preventDefault(e); }
  4098. display.wheelStartX = null; // Abort measurement, if in progress
  4099. return
  4100. }
  4101. // 'Project' the visible viewport to cover the area that is being
  4102. // scrolled into view (if we know enough to estimate it).
  4103. if (dy && wheelPixelsPerUnit != null) {
  4104. var pixels = dy * wheelPixelsPerUnit;
  4105. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4106. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4107. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4108. updateDisplaySimple(cm, {top: top, bottom: bot});
  4109. }
  4110. if (wheelSamples < 20) {
  4111. if (display.wheelStartX == null) {
  4112. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4113. display.wheelDX = dx; display.wheelDY = dy;
  4114. setTimeout(function () {
  4115. if (display.wheelStartX == null) { return }
  4116. var movedX = scroll.scrollLeft - display.wheelStartX;
  4117. var movedY = scroll.scrollTop - display.wheelStartY;
  4118. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4119. (movedX && display.wheelDX && movedX / display.wheelDX);
  4120. display.wheelStartX = display.wheelStartY = null;
  4121. if (!sample) { return }
  4122. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4123. ++wheelSamples;
  4124. }, 200);
  4125. } else {
  4126. display.wheelDX += dx; display.wheelDY += dy;
  4127. }
  4128. }
  4129. }
  4130. // Selection objects are immutable. A new one is created every time
  4131. // the selection changes. A selection is one or more non-overlapping
  4132. // (and non-touching) ranges, sorted, and an integer that indicates
  4133. // which one is the primary selection (the one that's scrolled into
  4134. // view, that getCursor returns, etc).
  4135. var Selection = function(ranges, primIndex) {
  4136. this.ranges = ranges;
  4137. this.primIndex = primIndex;
  4138. };
  4139. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4140. Selection.prototype.equals = function (other) {
  4141. if (other == this) { return true }
  4142. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4143. for (var i = 0; i < this.ranges.length; i++) {
  4144. var here = this.ranges[i], there = other.ranges[i];
  4145. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4146. }
  4147. return true
  4148. };
  4149. Selection.prototype.deepCopy = function () {
  4150. var out = [];
  4151. for (var i = 0; i < this.ranges.length; i++)
  4152. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4153. return new Selection(out, this.primIndex)
  4154. };
  4155. Selection.prototype.somethingSelected = function () {
  4156. for (var i = 0; i < this.ranges.length; i++)
  4157. { if (!this.ranges[i].empty()) { return true } }
  4158. return false
  4159. };
  4160. Selection.prototype.contains = function (pos, end) {
  4161. if (!end) { end = pos; }
  4162. for (var i = 0; i < this.ranges.length; i++) {
  4163. var range = this.ranges[i];
  4164. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4165. { return i }
  4166. }
  4167. return -1
  4168. };
  4169. var Range = function(anchor, head) {
  4170. this.anchor = anchor; this.head = head;
  4171. };
  4172. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4173. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4174. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4175. // Take an unsorted, potentially overlapping set of ranges, and
  4176. // build a selection out of it. 'Consumes' ranges array (modifying
  4177. // it).
  4178. function normalizeSelection(cm, ranges, primIndex) {
  4179. var mayTouch = cm && cm.options.selectionsMayTouch;
  4180. var prim = ranges[primIndex];
  4181. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4182. primIndex = indexOf(ranges, prim);
  4183. for (var i = 1; i < ranges.length; i++) {
  4184. var cur = ranges[i], prev = ranges[i - 1];
  4185. var diff = cmp(prev.to(), cur.from());
  4186. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4187. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4188. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4189. if (i <= primIndex) { --primIndex; }
  4190. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4191. }
  4192. }
  4193. return new Selection(ranges, primIndex)
  4194. }
  4195. function simpleSelection(anchor, head) {
  4196. return new Selection([new Range(anchor, head || anchor)], 0)
  4197. }
  4198. // Compute the position of the end of a change (its 'to' property
  4199. // refers to the pre-change end).
  4200. function changeEnd(change) {
  4201. if (!change.text) { return change.to }
  4202. return Pos(change.from.line + change.text.length - 1,
  4203. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4204. }
  4205. // Adjust a position to refer to the post-change position of the
  4206. // same text, or the end of the change if the change covers it.
  4207. function adjustForChange(pos, change) {
  4208. if (cmp(pos, change.from) < 0) { return pos }
  4209. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4210. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4211. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4212. return Pos(line, ch)
  4213. }
  4214. function computeSelAfterChange(doc, change) {
  4215. var out = [];
  4216. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4217. var range = doc.sel.ranges[i];
  4218. out.push(new Range(adjustForChange(range.anchor, change),
  4219. adjustForChange(range.head, change)));
  4220. }
  4221. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4222. }
  4223. function offsetPos(pos, old, nw) {
  4224. if (pos.line == old.line)
  4225. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4226. else
  4227. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4228. }
  4229. // Used by replaceSelections to allow moving the selection to the
  4230. // start or around the replaced test. Hint may be "start" or "around".
  4231. function computeReplacedSel(doc, changes, hint) {
  4232. var out = [];
  4233. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4234. for (var i = 0; i < changes.length; i++) {
  4235. var change = changes[i];
  4236. var from = offsetPos(change.from, oldPrev, newPrev);
  4237. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4238. oldPrev = change.to;
  4239. newPrev = to;
  4240. if (hint == "around") {
  4241. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4242. out[i] = new Range(inv ? to : from, inv ? from : to);
  4243. } else {
  4244. out[i] = new Range(from, from);
  4245. }
  4246. }
  4247. return new Selection(out, doc.sel.primIndex)
  4248. }
  4249. // Used to get the editor into a consistent state again when options change.
  4250. function loadMode(cm) {
  4251. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4252. resetModeState(cm);
  4253. }
  4254. function resetModeState(cm) {
  4255. cm.doc.iter(function (line) {
  4256. if (line.stateAfter) { line.stateAfter = null; }
  4257. if (line.styles) { line.styles = null; }
  4258. });
  4259. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4260. startWorker(cm, 100);
  4261. cm.state.modeGen++;
  4262. if (cm.curOp) { regChange(cm); }
  4263. }
  4264. // DOCUMENT DATA STRUCTURE
  4265. // By default, updates that start and end at the beginning of a line
  4266. // are treated specially, in order to make the association of line
  4267. // widgets and marker elements with the text behave more intuitive.
  4268. function isWholeLineUpdate(doc, change) {
  4269. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4270. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4271. }
  4272. // Perform a change on the document data structure.
  4273. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4274. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4275. function update(line, text, spans) {
  4276. updateLine(line, text, spans, estimateHeight);
  4277. signalLater(line, "change", line, change);
  4278. }
  4279. function linesFor(start, end) {
  4280. var result = [];
  4281. for (var i = start; i < end; ++i)
  4282. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4283. return result
  4284. }
  4285. var from = change.from, to = change.to, text = change.text;
  4286. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4287. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4288. // Adjust the line structure
  4289. if (change.full) {
  4290. doc.insert(0, linesFor(0, text.length));
  4291. doc.remove(text.length, doc.size - text.length);
  4292. } else if (isWholeLineUpdate(doc, change)) {
  4293. // This is a whole-line replace. Treated specially to make
  4294. // sure line objects move the way they are supposed to.
  4295. var added = linesFor(0, text.length - 1);
  4296. update(lastLine, lastLine.text, lastSpans);
  4297. if (nlines) { doc.remove(from.line, nlines); }
  4298. if (added.length) { doc.insert(from.line, added); }
  4299. } else if (firstLine == lastLine) {
  4300. if (text.length == 1) {
  4301. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4302. } else {
  4303. var added$1 = linesFor(1, text.length - 1);
  4304. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4305. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4306. doc.insert(from.line + 1, added$1);
  4307. }
  4308. } else if (text.length == 1) {
  4309. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4310. doc.remove(from.line + 1, nlines);
  4311. } else {
  4312. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4313. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4314. var added$2 = linesFor(1, text.length - 1);
  4315. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4316. doc.insert(from.line + 1, added$2);
  4317. }
  4318. signalLater(doc, "change", doc, change);
  4319. }
  4320. // Call f for all linked documents.
  4321. function linkedDocs(doc, f, sharedHistOnly) {
  4322. function propagate(doc, skip, sharedHist) {
  4323. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4324. var rel = doc.linked[i];
  4325. if (rel.doc == skip) { continue }
  4326. var shared = sharedHist && rel.sharedHist;
  4327. if (sharedHistOnly && !shared) { continue }
  4328. f(rel.doc, shared);
  4329. propagate(rel.doc, doc, shared);
  4330. } }
  4331. }
  4332. propagate(doc, null, true);
  4333. }
  4334. // Attach a document to an editor.
  4335. function attachDoc(cm, doc) {
  4336. if (doc.cm) { throw new Error("This document is already in use.") }
  4337. cm.doc = doc;
  4338. doc.cm = cm;
  4339. estimateLineHeights(cm);
  4340. loadMode(cm);
  4341. setDirectionClass(cm);
  4342. cm.options.direction = doc.direction;
  4343. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4344. cm.options.mode = doc.modeOption;
  4345. regChange(cm);
  4346. }
  4347. function setDirectionClass(cm) {
  4348. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4349. }
  4350. function directionChanged(cm) {
  4351. runInOp(cm, function () {
  4352. setDirectionClass(cm);
  4353. regChange(cm);
  4354. });
  4355. }
  4356. function History(prev) {
  4357. // Arrays of change events and selections. Doing something adds an
  4358. // event to done and clears undo. Undoing moves events from done
  4359. // to undone, redoing moves them in the other direction.
  4360. this.done = []; this.undone = [];
  4361. this.undoDepth = prev ? prev.undoDepth : Infinity;
  4362. // Used to track when changes can be merged into a single undo
  4363. // event
  4364. this.lastModTime = this.lastSelTime = 0;
  4365. this.lastOp = this.lastSelOp = null;
  4366. this.lastOrigin = this.lastSelOrigin = null;
  4367. // Used by the isClean() method
  4368. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  4369. }
  4370. // Create a history change event from an updateDoc-style change
  4371. // object.
  4372. function historyChangeFromChange(doc, change) {
  4373. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4374. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4375. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4376. return histChange
  4377. }
  4378. // Pop all selection events off the end of a history array. Stop at
  4379. // a change event.
  4380. function clearSelectionEvents(array) {
  4381. while (array.length) {
  4382. var last = lst(array);
  4383. if (last.ranges) { array.pop(); }
  4384. else { break }
  4385. }
  4386. }
  4387. // Find the top change event in the history. Pop off selection
  4388. // events that are in the way.
  4389. function lastChangeEvent(hist, force) {
  4390. if (force) {
  4391. clearSelectionEvents(hist.done);
  4392. return lst(hist.done)
  4393. } else if (hist.done.length && !lst(hist.done).ranges) {
  4394. return lst(hist.done)
  4395. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4396. hist.done.pop();
  4397. return lst(hist.done)
  4398. }
  4399. }
  4400. // Register a change in the history. Merges changes that are within
  4401. // a single operation, or are close together with an origin that
  4402. // allows merging (starting with "+") into a single event.
  4403. function addChangeToHistory(doc, change, selAfter, opId) {
  4404. var hist = doc.history;
  4405. hist.undone.length = 0;
  4406. var time = +new Date, cur;
  4407. var last;
  4408. if ((hist.lastOp == opId ||
  4409. hist.lastOrigin == change.origin && change.origin &&
  4410. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4411. change.origin.charAt(0) == "*")) &&
  4412. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4413. // Merge this change into the last event
  4414. last = lst(cur.changes);
  4415. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4416. // Optimized case for simple insertion -- don't want to add
  4417. // new changesets for every character typed
  4418. last.to = changeEnd(change);
  4419. } else {
  4420. // Add new sub-event
  4421. cur.changes.push(historyChangeFromChange(doc, change));
  4422. }
  4423. } else {
  4424. // Can not be merged, start a new event.
  4425. var before = lst(hist.done);
  4426. if (!before || !before.ranges)
  4427. { pushSelectionToHistory(doc.sel, hist.done); }
  4428. cur = {changes: [historyChangeFromChange(doc, change)],
  4429. generation: hist.generation};
  4430. hist.done.push(cur);
  4431. while (hist.done.length > hist.undoDepth) {
  4432. hist.done.shift();
  4433. if (!hist.done[0].ranges) { hist.done.shift(); }
  4434. }
  4435. }
  4436. hist.done.push(selAfter);
  4437. hist.generation = ++hist.maxGeneration;
  4438. hist.lastModTime = hist.lastSelTime = time;
  4439. hist.lastOp = hist.lastSelOp = opId;
  4440. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4441. if (!last) { signal(doc, "historyAdded"); }
  4442. }
  4443. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4444. var ch = origin.charAt(0);
  4445. return ch == "*" ||
  4446. ch == "+" &&
  4447. prev.ranges.length == sel.ranges.length &&
  4448. prev.somethingSelected() == sel.somethingSelected() &&
  4449. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4450. }
  4451. // Called whenever the selection changes, sets the new selection as
  4452. // the pending selection in the history, and pushes the old pending
  4453. // selection into the 'done' array when it was significantly
  4454. // different (in number of selected ranges, emptiness, or time).
  4455. function addSelectionToHistory(doc, sel, opId, options) {
  4456. var hist = doc.history, origin = options && options.origin;
  4457. // A new event is started when the previous origin does not match
  4458. // the current, or the origins don't allow matching. Origins
  4459. // starting with * are always merged, those starting with + are
  4460. // merged when similar and close together in time.
  4461. if (opId == hist.lastSelOp ||
  4462. (origin && hist.lastSelOrigin == origin &&
  4463. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4464. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4465. { hist.done[hist.done.length - 1] = sel; }
  4466. else
  4467. { pushSelectionToHistory(sel, hist.done); }
  4468. hist.lastSelTime = +new Date;
  4469. hist.lastSelOrigin = origin;
  4470. hist.lastSelOp = opId;
  4471. if (options && options.clearRedo !== false)
  4472. { clearSelectionEvents(hist.undone); }
  4473. }
  4474. function pushSelectionToHistory(sel, dest) {
  4475. var top = lst(dest);
  4476. if (!(top && top.ranges && top.equals(sel)))
  4477. { dest.push(sel); }
  4478. }
  4479. // Used to store marked span information in the history.
  4480. function attachLocalSpans(doc, change, from, to) {
  4481. var existing = change["spans_" + doc.id], n = 0;
  4482. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4483. if (line.markedSpans)
  4484. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4485. ++n;
  4486. });
  4487. }
  4488. // When un/re-doing restores text containing marked spans, those
  4489. // that have been explicitly cleared should not be restored.
  4490. function removeClearedSpans(spans) {
  4491. if (!spans) { return null }
  4492. var out;
  4493. for (var i = 0; i < spans.length; ++i) {
  4494. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4495. else if (out) { out.push(spans[i]); }
  4496. }
  4497. return !out ? spans : out.length ? out : null
  4498. }
  4499. // Retrieve and filter the old marked spans stored in a change event.
  4500. function getOldSpans(doc, change) {
  4501. var found = change["spans_" + doc.id];
  4502. if (!found) { return null }
  4503. var nw = [];
  4504. for (var i = 0; i < change.text.length; ++i)
  4505. { nw.push(removeClearedSpans(found[i])); }
  4506. return nw
  4507. }
  4508. // Used for un/re-doing changes from the history. Combines the
  4509. // result of computing the existing spans with the set of spans that
  4510. // existed in the history (so that deleting around a span and then
  4511. // undoing brings back the span).
  4512. function mergeOldSpans(doc, change) {
  4513. var old = getOldSpans(doc, change);
  4514. var stretched = stretchSpansOverChange(doc, change);
  4515. if (!old) { return stretched }
  4516. if (!stretched) { return old }
  4517. for (var i = 0; i < old.length; ++i) {
  4518. var oldCur = old[i], stretchCur = stretched[i];
  4519. if (oldCur && stretchCur) {
  4520. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4521. var span = stretchCur[j];
  4522. for (var k = 0; k < oldCur.length; ++k)
  4523. { if (oldCur[k].marker == span.marker) { continue spans } }
  4524. oldCur.push(span);
  4525. }
  4526. } else if (stretchCur) {
  4527. old[i] = stretchCur;
  4528. }
  4529. }
  4530. return old
  4531. }
  4532. // Used both to provide a JSON-safe object in .getHistory, and, when
  4533. // detaching a document, to split the history in two
  4534. function copyHistoryArray(events, newGroup, instantiateSel) {
  4535. var copy = [];
  4536. for (var i = 0; i < events.length; ++i) {
  4537. var event = events[i];
  4538. if (event.ranges) {
  4539. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4540. continue
  4541. }
  4542. var changes = event.changes, newChanges = [];
  4543. copy.push({changes: newChanges});
  4544. for (var j = 0; j < changes.length; ++j) {
  4545. var change = changes[j], m = (void 0);
  4546. newChanges.push({from: change.from, to: change.to, text: change.text});
  4547. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4548. if (indexOf(newGroup, Number(m[1])) > -1) {
  4549. lst(newChanges)[prop] = change[prop];
  4550. delete change[prop];
  4551. }
  4552. } } }
  4553. }
  4554. }
  4555. return copy
  4556. }
  4557. // The 'scroll' parameter given to many of these indicated whether
  4558. // the new cursor position should be scrolled into view after
  4559. // modifying the selection.
  4560. // If shift is held or the extend flag is set, extends a range to
  4561. // include a given position (and optionally a second position).
  4562. // Otherwise, simply returns the range between the given positions.
  4563. // Used for cursor motion and such.
  4564. function extendRange(range, head, other, extend) {
  4565. if (extend) {
  4566. var anchor = range.anchor;
  4567. if (other) {
  4568. var posBefore = cmp(head, anchor) < 0;
  4569. if (posBefore != (cmp(other, anchor) < 0)) {
  4570. anchor = head;
  4571. head = other;
  4572. } else if (posBefore != (cmp(head, other) < 0)) {
  4573. head = other;
  4574. }
  4575. }
  4576. return new Range(anchor, head)
  4577. } else {
  4578. return new Range(other || head, head)
  4579. }
  4580. }
  4581. // Extend the primary selection range, discard the rest.
  4582. function extendSelection(doc, head, other, options, extend) {
  4583. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4584. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4585. }
  4586. // Extend all selections (pos is an array of selections with length
  4587. // equal the number of selections)
  4588. function extendSelections(doc, heads, options) {
  4589. var out = [];
  4590. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4591. for (var i = 0; i < doc.sel.ranges.length; i++)
  4592. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4593. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4594. setSelection(doc, newSel, options);
  4595. }
  4596. // Updates a single range in the selection.
  4597. function replaceOneSelection(doc, i, range, options) {
  4598. var ranges = doc.sel.ranges.slice(0);
  4599. ranges[i] = range;
  4600. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4601. }
  4602. // Reset the selection to a single range.
  4603. function setSimpleSelection(doc, anchor, head, options) {
  4604. setSelection(doc, simpleSelection(anchor, head), options);
  4605. }
  4606. // Give beforeSelectionChange handlers a change to influence a
  4607. // selection update.
  4608. function filterSelectionChange(doc, sel, options) {
  4609. var obj = {
  4610. ranges: sel.ranges,
  4611. update: function(ranges) {
  4612. this.ranges = [];
  4613. for (var i = 0; i < ranges.length; i++)
  4614. { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4615. clipPos(doc, ranges[i].head)); }
  4616. },
  4617. origin: options && options.origin
  4618. };
  4619. signal(doc, "beforeSelectionChange", doc, obj);
  4620. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4621. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4622. else { return sel }
  4623. }
  4624. function setSelectionReplaceHistory(doc, sel, options) {
  4625. var done = doc.history.done, last = lst(done);
  4626. if (last && last.ranges) {
  4627. done[done.length - 1] = sel;
  4628. setSelectionNoUndo(doc, sel, options);
  4629. } else {
  4630. setSelection(doc, sel, options);
  4631. }
  4632. }
  4633. // Set a new selection.
  4634. function setSelection(doc, sel, options) {
  4635. setSelectionNoUndo(doc, sel, options);
  4636. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4637. }
  4638. function setSelectionNoUndo(doc, sel, options) {
  4639. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4640. { sel = filterSelectionChange(doc, sel, options); }
  4641. var bias = options && options.bias ||
  4642. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4643. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4644. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
  4645. { ensureCursorVisible(doc.cm); }
  4646. }
  4647. function setSelectionInner(doc, sel) {
  4648. if (sel.equals(doc.sel)) { return }
  4649. doc.sel = sel;
  4650. if (doc.cm) {
  4651. doc.cm.curOp.updateInput = 1;
  4652. doc.cm.curOp.selectionChanged = true;
  4653. signalCursorActivity(doc.cm);
  4654. }
  4655. signalLater(doc, "cursorActivity", doc);
  4656. }
  4657. // Verify that the selection does not partially select any atomic
  4658. // marked ranges.
  4659. function reCheckSelection(doc) {
  4660. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4661. }
  4662. // Return a selection that does not partially select any atomic
  4663. // ranges.
  4664. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4665. var out;
  4666. for (var i = 0; i < sel.ranges.length; i++) {
  4667. var range = sel.ranges[i];
  4668. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4669. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4670. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4671. if (out || newAnchor != range.anchor || newHead != range.head) {
  4672. if (!out) { out = sel.ranges.slice(0, i); }
  4673. out[i] = new Range(newAnchor, newHead);
  4674. }
  4675. }
  4676. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4677. }
  4678. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4679. var line = getLine(doc, pos.line);
  4680. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4681. var sp = line.markedSpans[i], m = sp.marker;
  4682. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  4683. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  4684. // is with selectLeft/Right
  4685. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  4686. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  4687. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4688. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4689. if (mayClear) {
  4690. signal(m, "beforeCursorEnter");
  4691. if (m.explicitlyCleared) {
  4692. if (!line.markedSpans) { break }
  4693. else {--i; continue}
  4694. }
  4695. }
  4696. if (!m.atomic) { continue }
  4697. if (oldPos) {
  4698. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4699. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  4700. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4701. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4702. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4703. }
  4704. var far = m.find(dir < 0 ? -1 : 1);
  4705. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  4706. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4707. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4708. }
  4709. } }
  4710. return pos
  4711. }
  4712. // Ensure a given position is not inside an atomic range.
  4713. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4714. var dir = bias || 1;
  4715. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4716. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4717. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4718. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4719. if (!found) {
  4720. doc.cantEdit = true;
  4721. return Pos(doc.first, 0)
  4722. }
  4723. return found
  4724. }
  4725. function movePos(doc, pos, dir, line) {
  4726. if (dir < 0 && pos.ch == 0) {
  4727. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4728. else { return null }
  4729. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4730. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4731. else { return null }
  4732. } else {
  4733. return new Pos(pos.line, pos.ch + dir)
  4734. }
  4735. }
  4736. function selectAll(cm) {
  4737. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4738. }
  4739. // UPDATING
  4740. // Allow "beforeChange" event handlers to influence a change
  4741. function filterChange(doc, change, update) {
  4742. var obj = {
  4743. canceled: false,
  4744. from: change.from,
  4745. to: change.to,
  4746. text: change.text,
  4747. origin: change.origin,
  4748. cancel: function () { return obj.canceled = true; }
  4749. };
  4750. if (update) { obj.update = function (from, to, text, origin) {
  4751. if (from) { obj.from = clipPos(doc, from); }
  4752. if (to) { obj.to = clipPos(doc, to); }
  4753. if (text) { obj.text = text; }
  4754. if (origin !== undefined) { obj.origin = origin; }
  4755. }; }
  4756. signal(doc, "beforeChange", doc, obj);
  4757. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4758. if (obj.canceled) {
  4759. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4760. return null
  4761. }
  4762. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4763. }
  4764. // Apply a change to a document, and add it to the document's
  4765. // history, and propagating it to all linked documents.
  4766. function makeChange(doc, change, ignoreReadOnly) {
  4767. if (doc.cm) {
  4768. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4769. if (doc.cm.state.suppressEdits) { return }
  4770. }
  4771. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4772. change = filterChange(doc, change, true);
  4773. if (!change) { return }
  4774. }
  4775. // Possibly split or suppress the update based on the presence
  4776. // of read-only spans in its range.
  4777. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4778. if (split) {
  4779. for (var i = split.length - 1; i >= 0; --i)
  4780. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4781. } else {
  4782. makeChangeInner(doc, change);
  4783. }
  4784. }
  4785. function makeChangeInner(doc, change) {
  4786. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4787. var selAfter = computeSelAfterChange(doc, change);
  4788. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4789. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4790. var rebased = [];
  4791. linkedDocs(doc, function (doc, sharedHist) {
  4792. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4793. rebaseHist(doc.history, change);
  4794. rebased.push(doc.history);
  4795. }
  4796. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4797. });
  4798. }
  4799. // Revert a change stored in a document's history.
  4800. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4801. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4802. if (suppress && !allowSelectionOnly) { return }
  4803. var hist = doc.history, event, selAfter = doc.sel;
  4804. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4805. // Verify that there is a useable event (so that ctrl-z won't
  4806. // needlessly clear selection events)
  4807. var i = 0;
  4808. for (; i < source.length; i++) {
  4809. event = source[i];
  4810. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4811. { break }
  4812. }
  4813. if (i == source.length) { return }
  4814. hist.lastOrigin = hist.lastSelOrigin = null;
  4815. for (;;) {
  4816. event = source.pop();
  4817. if (event.ranges) {
  4818. pushSelectionToHistory(event, dest);
  4819. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4820. setSelection(doc, event, {clearRedo: false});
  4821. return
  4822. }
  4823. selAfter = event;
  4824. } else if (suppress) {
  4825. source.push(event);
  4826. return
  4827. } else { break }
  4828. }
  4829. // Build up a reverse change object to add to the opposite history
  4830. // stack (redo when undoing, and vice versa).
  4831. var antiChanges = [];
  4832. pushSelectionToHistory(selAfter, dest);
  4833. dest.push({changes: antiChanges, generation: hist.generation});
  4834. hist.generation = event.generation || ++hist.maxGeneration;
  4835. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4836. var loop = function ( i ) {
  4837. var change = event.changes[i];
  4838. change.origin = type;
  4839. if (filter && !filterChange(doc, change, false)) {
  4840. source.length = 0;
  4841. return {}
  4842. }
  4843. antiChanges.push(historyChangeFromChange(doc, change));
  4844. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4845. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4846. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4847. var rebased = [];
  4848. // Propagate to the linked documents
  4849. linkedDocs(doc, function (doc, sharedHist) {
  4850. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4851. rebaseHist(doc.history, change);
  4852. rebased.push(doc.history);
  4853. }
  4854. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4855. });
  4856. };
  4857. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4858. var returned = loop( i$1 );
  4859. if ( returned ) return returned.v;
  4860. }
  4861. }
  4862. // Sub-views need their line numbers shifted when text is added
  4863. // above or below them in the parent document.
  4864. function shiftDoc(doc, distance) {
  4865. if (distance == 0) { return }
  4866. doc.first += distance;
  4867. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4868. Pos(range.anchor.line + distance, range.anchor.ch),
  4869. Pos(range.head.line + distance, range.head.ch)
  4870. ); }), doc.sel.primIndex);
  4871. if (doc.cm) {
  4872. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4873. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4874. { regLineChange(doc.cm, l, "gutter"); }
  4875. }
  4876. }
  4877. // More lower-level change function, handling only a single document
  4878. // (not linked ones).
  4879. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4880. if (doc.cm && !doc.cm.curOp)
  4881. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4882. if (change.to.line < doc.first) {
  4883. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4884. return
  4885. }
  4886. if (change.from.line > doc.lastLine()) { return }
  4887. // Clip the change to the size of this doc
  4888. if (change.from.line < doc.first) {
  4889. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4890. shiftDoc(doc, shift);
  4891. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4892. text: [lst(change.text)], origin: change.origin};
  4893. }
  4894. var last = doc.lastLine();
  4895. if (change.to.line > last) {
  4896. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4897. text: [change.text[0]], origin: change.origin};
  4898. }
  4899. change.removed = getBetween(doc, change.from, change.to);
  4900. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4901. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4902. else { updateDoc(doc, change, spans); }
  4903. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4904. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  4905. { doc.cantEdit = false; }
  4906. }
  4907. // Handle the interaction of a change to a document with the editor
  4908. // that this document is part of.
  4909. function makeChangeSingleDocInEditor(cm, change, spans) {
  4910. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4911. var recomputeMaxLength = false, checkWidthStart = from.line;
  4912. if (!cm.options.lineWrapping) {
  4913. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4914. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4915. if (line == display.maxLine) {
  4916. recomputeMaxLength = true;
  4917. return true
  4918. }
  4919. });
  4920. }
  4921. if (doc.sel.contains(change.from, change.to) > -1)
  4922. { signalCursorActivity(cm); }
  4923. updateDoc(doc, change, spans, estimateHeight(cm));
  4924. if (!cm.options.lineWrapping) {
  4925. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4926. var len = lineLength(line);
  4927. if (len > display.maxLineLength) {
  4928. display.maxLine = line;
  4929. display.maxLineLength = len;
  4930. display.maxLineChanged = true;
  4931. recomputeMaxLength = false;
  4932. }
  4933. });
  4934. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4935. }
  4936. retreatFrontier(doc, from.line);
  4937. startWorker(cm, 400);
  4938. var lendiff = change.text.length - (to.line - from.line) - 1;
  4939. // Remember that these lines changed, for updating the display
  4940. if (change.full)
  4941. { regChange(cm); }
  4942. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4943. { regLineChange(cm, from.line, "text"); }
  4944. else
  4945. { regChange(cm, from.line, to.line + 1, lendiff); }
  4946. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4947. if (changeHandler || changesHandler) {
  4948. var obj = {
  4949. from: from, to: to,
  4950. text: change.text,
  4951. removed: change.removed,
  4952. origin: change.origin
  4953. };
  4954. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  4955. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  4956. }
  4957. cm.display.selForContextMenu = null;
  4958. }
  4959. function replaceRange(doc, code, from, to, origin) {
  4960. var assign;
  4961. if (!to) { to = from; }
  4962. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  4963. if (typeof code == "string") { code = doc.splitLines(code); }
  4964. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4965. }
  4966. // Rebasing/resetting history to deal with externally-sourced changes
  4967. function rebaseHistSelSingle(pos, from, to, diff) {
  4968. if (to < pos.line) {
  4969. pos.line += diff;
  4970. } else if (from < pos.line) {
  4971. pos.line = from;
  4972. pos.ch = 0;
  4973. }
  4974. }
  4975. // Tries to rebase an array of history events given a change in the
  4976. // document. If the change touches the same lines as the event, the
  4977. // event, and everything 'behind' it, is discarded. If the change is
  4978. // before the event, the event's positions are updated. Uses a
  4979. // copy-on-write scheme for the positions, to avoid having to
  4980. // reallocate them all on every rebase, but also avoid problems with
  4981. // shared position objects being unsafely updated.
  4982. function rebaseHistArray(array, from, to, diff) {
  4983. for (var i = 0; i < array.length; ++i) {
  4984. var sub = array[i], ok = true;
  4985. if (sub.ranges) {
  4986. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  4987. for (var j = 0; j < sub.ranges.length; j++) {
  4988. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  4989. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  4990. }
  4991. continue
  4992. }
  4993. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4994. var cur = sub.changes[j$1];
  4995. if (to < cur.from.line) {
  4996. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  4997. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  4998. } else if (from <= cur.to.line) {
  4999. ok = false;
  5000. break
  5001. }
  5002. }
  5003. if (!ok) {
  5004. array.splice(0, i + 1);
  5005. i = 0;
  5006. }
  5007. }
  5008. }
  5009. function rebaseHist(hist, change) {
  5010. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5011. rebaseHistArray(hist.done, from, to, diff);
  5012. rebaseHistArray(hist.undone, from, to, diff);
  5013. }
  5014. // Utility for applying a change to a line by handle or number,
  5015. // returning the number and optionally registering the line as
  5016. // changed.
  5017. function changeLine(doc, handle, changeType, op) {
  5018. var no = handle, line = handle;
  5019. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5020. else { no = lineNo(handle); }
  5021. if (no == null) { return null }
  5022. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5023. return line
  5024. }
  5025. // The document is represented as a BTree consisting of leaves, with
  5026. // chunk of lines in them, and branches, with up to ten leaves or
  5027. // other branch nodes below them. The top node is always a branch
  5028. // node, and is the document object itself (meaning it has
  5029. // additional methods and properties).
  5030. //
  5031. // All nodes have parent links. The tree is used both to go from
  5032. // line numbers to line objects, and to go from objects to numbers.
  5033. // It also indexes by height, and is used to convert between height
  5034. // and line object, and to find the total height of the document.
  5035. //
  5036. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5037. function LeafChunk(lines) {
  5038. this.lines = lines;
  5039. this.parent = null;
  5040. var height = 0;
  5041. for (var i = 0; i < lines.length; ++i) {
  5042. lines[i].parent = this;
  5043. height += lines[i].height;
  5044. }
  5045. this.height = height;
  5046. }
  5047. LeafChunk.prototype = {
  5048. chunkSize: function() { return this.lines.length },
  5049. // Remove the n lines at offset 'at'.
  5050. removeInner: function(at, n) {
  5051. for (var i = at, e = at + n; i < e; ++i) {
  5052. var line = this.lines[i];
  5053. this.height -= line.height;
  5054. cleanUpLine(line);
  5055. signalLater(line, "delete");
  5056. }
  5057. this.lines.splice(at, n);
  5058. },
  5059. // Helper used to collapse a small branch into a single leaf.
  5060. collapse: function(lines) {
  5061. lines.push.apply(lines, this.lines);
  5062. },
  5063. // Insert the given array of lines at offset 'at', count them as
  5064. // having the given height.
  5065. insertInner: function(at, lines, height) {
  5066. this.height += height;
  5067. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5068. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5069. },
  5070. // Used to iterate over a part of the tree.
  5071. iterN: function(at, n, op) {
  5072. for (var e = at + n; at < e; ++at)
  5073. { if (op(this.lines[at])) { return true } }
  5074. }
  5075. };
  5076. function BranchChunk(children) {
  5077. this.children = children;
  5078. var size = 0, height = 0;
  5079. for (var i = 0; i < children.length; ++i) {
  5080. var ch = children[i];
  5081. size += ch.chunkSize(); height += ch.height;
  5082. ch.parent = this;
  5083. }
  5084. this.size = size;
  5085. this.height = height;
  5086. this.parent = null;
  5087. }
  5088. BranchChunk.prototype = {
  5089. chunkSize: function() { return this.size },
  5090. removeInner: function(at, n) {
  5091. this.size -= n;
  5092. for (var i = 0; i < this.children.length; ++i) {
  5093. var child = this.children[i], sz = child.chunkSize();
  5094. if (at < sz) {
  5095. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5096. child.removeInner(at, rm);
  5097. this.height -= oldHeight - child.height;
  5098. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5099. if ((n -= rm) == 0) { break }
  5100. at = 0;
  5101. } else { at -= sz; }
  5102. }
  5103. // If the result is smaller than 25 lines, ensure that it is a
  5104. // single leaf node.
  5105. if (this.size - n < 25 &&
  5106. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5107. var lines = [];
  5108. this.collapse(lines);
  5109. this.children = [new LeafChunk(lines)];
  5110. this.children[0].parent = this;
  5111. }
  5112. },
  5113. collapse: function(lines) {
  5114. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5115. },
  5116. insertInner: function(at, lines, height) {
  5117. this.size += lines.length;
  5118. this.height += height;
  5119. for (var i = 0; i < this.children.length; ++i) {
  5120. var child = this.children[i], sz = child.chunkSize();
  5121. if (at <= sz) {
  5122. child.insertInner(at, lines, height);
  5123. if (child.lines && child.lines.length > 50) {
  5124. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5125. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5126. var remaining = child.lines.length % 25 + 25;
  5127. for (var pos = remaining; pos < child.lines.length;) {
  5128. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5129. child.height -= leaf.height;
  5130. this.children.splice(++i, 0, leaf);
  5131. leaf.parent = this;
  5132. }
  5133. child.lines = child.lines.slice(0, remaining);
  5134. this.maybeSpill();
  5135. }
  5136. break
  5137. }
  5138. at -= sz;
  5139. }
  5140. },
  5141. // When a node has grown, check whether it should be split.
  5142. maybeSpill: function() {
  5143. if (this.children.length <= 10) { return }
  5144. var me = this;
  5145. do {
  5146. var spilled = me.children.splice(me.children.length - 5, 5);
  5147. var sibling = new BranchChunk(spilled);
  5148. if (!me.parent) { // Become the parent node
  5149. var copy = new BranchChunk(me.children);
  5150. copy.parent = me;
  5151. me.children = [copy, sibling];
  5152. me = copy;
  5153. } else {
  5154. me.size -= sibling.size;
  5155. me.height -= sibling.height;
  5156. var myIndex = indexOf(me.parent.children, me);
  5157. me.parent.children.splice(myIndex + 1, 0, sibling);
  5158. }
  5159. sibling.parent = me.parent;
  5160. } while (me.children.length > 10)
  5161. me.parent.maybeSpill();
  5162. },
  5163. iterN: function(at, n, op) {
  5164. for (var i = 0; i < this.children.length; ++i) {
  5165. var child = this.children[i], sz = child.chunkSize();
  5166. if (at < sz) {
  5167. var used = Math.min(n, sz - at);
  5168. if (child.iterN(at, used, op)) { return true }
  5169. if ((n -= used) == 0) { break }
  5170. at = 0;
  5171. } else { at -= sz; }
  5172. }
  5173. }
  5174. };
  5175. // Line widgets are block elements displayed above or below a line.
  5176. var LineWidget = function(doc, node, options) {
  5177. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5178. { this[opt] = options[opt]; } } }
  5179. this.doc = doc;
  5180. this.node = node;
  5181. };
  5182. LineWidget.prototype.clear = function () {
  5183. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5184. if (no == null || !ws) { return }
  5185. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5186. if (!ws.length) { line.widgets = null; }
  5187. var height = widgetHeight(this);
  5188. updateLineHeight(line, Math.max(0, line.height - height));
  5189. if (cm) {
  5190. runInOp(cm, function () {
  5191. adjustScrollWhenAboveVisible(cm, line, -height);
  5192. regLineChange(cm, no, "widget");
  5193. });
  5194. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5195. }
  5196. };
  5197. LineWidget.prototype.changed = function () {
  5198. var this$1 = this;
  5199. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5200. this.height = null;
  5201. var diff = widgetHeight(this) - oldH;
  5202. if (!diff) { return }
  5203. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5204. if (cm) {
  5205. runInOp(cm, function () {
  5206. cm.curOp.forceUpdate = true;
  5207. adjustScrollWhenAboveVisible(cm, line, diff);
  5208. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5209. });
  5210. }
  5211. };
  5212. eventMixin(LineWidget);
  5213. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5214. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5215. { addToScrollTop(cm, diff); }
  5216. }
  5217. function addLineWidget(doc, handle, node, options) {
  5218. var widget = new LineWidget(doc, node, options);
  5219. var cm = doc.cm;
  5220. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5221. changeLine(doc, handle, "widget", function (line) {
  5222. var widgets = line.widgets || (line.widgets = []);
  5223. if (widget.insertAt == null) { widgets.push(widget); }
  5224. else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  5225. widget.line = line;
  5226. if (cm && !lineIsHidden(doc, line)) {
  5227. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5228. updateLineHeight(line, line.height + widgetHeight(widget));
  5229. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5230. cm.curOp.forceUpdate = true;
  5231. }
  5232. return true
  5233. });
  5234. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5235. return widget
  5236. }
  5237. // TEXTMARKERS
  5238. // Created with markText and setBookmark methods. A TextMarker is a
  5239. // handle that can be used to clear or find a marked position in the
  5240. // document. Line objects hold arrays (markedSpans) containing
  5241. // {from, to, marker} object pointing to such marker objects, and
  5242. // indicating that such a marker is present on that line. Multiple
  5243. // lines may point to the same marker when it spans across lines.
  5244. // The spans will have null for their from/to properties when the
  5245. // marker continues beyond the start/end of the line. Markers have
  5246. // links back to the lines they currently touch.
  5247. // Collapsed markers have unique ids, in order to be able to order
  5248. // them, which is needed for uniquely determining an outer marker
  5249. // when they overlap (they may nest, but not partially overlap).
  5250. var nextMarkerId = 0;
  5251. var TextMarker = function(doc, type) {
  5252. this.lines = [];
  5253. this.type = type;
  5254. this.doc = doc;
  5255. this.id = ++nextMarkerId;
  5256. };
  5257. // Clear the marker.
  5258. TextMarker.prototype.clear = function () {
  5259. if (this.explicitlyCleared) { return }
  5260. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5261. if (withOp) { startOperation(cm); }
  5262. if (hasHandler(this, "clear")) {
  5263. var found = this.find();
  5264. if (found) { signalLater(this, "clear", found.from, found.to); }
  5265. }
  5266. var min = null, max = null;
  5267. for (var i = 0; i < this.lines.length; ++i) {
  5268. var line = this.lines[i];
  5269. var span = getMarkedSpanFor(line.markedSpans, this);
  5270. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5271. else if (cm) {
  5272. if (span.to != null) { max = lineNo(line); }
  5273. if (span.from != null) { min = lineNo(line); }
  5274. }
  5275. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5276. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5277. { updateLineHeight(line, textHeight(cm.display)); }
  5278. }
  5279. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5280. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5281. if (len > cm.display.maxLineLength) {
  5282. cm.display.maxLine = visual;
  5283. cm.display.maxLineLength = len;
  5284. cm.display.maxLineChanged = true;
  5285. }
  5286. } }
  5287. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5288. this.lines.length = 0;
  5289. this.explicitlyCleared = true;
  5290. if (this.atomic && this.doc.cantEdit) {
  5291. this.doc.cantEdit = false;
  5292. if (cm) { reCheckSelection(cm.doc); }
  5293. }
  5294. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5295. if (withOp) { endOperation(cm); }
  5296. if (this.parent) { this.parent.clear(); }
  5297. };
  5298. // Find the position of the marker in the document. Returns a {from,
  5299. // to} object by default. Side can be passed to get a specific side
  5300. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5301. // Pos objects returned contain a line object, rather than a line
  5302. // number (used to prevent looking up the same line twice).
  5303. TextMarker.prototype.find = function (side, lineObj) {
  5304. if (side == null && this.type == "bookmark") { side = 1; }
  5305. var from, to;
  5306. for (var i = 0; i < this.lines.length; ++i) {
  5307. var line = this.lines[i];
  5308. var span = getMarkedSpanFor(line.markedSpans, this);
  5309. if (span.from != null) {
  5310. from = Pos(lineObj ? line : lineNo(line), span.from);
  5311. if (side == -1) { return from }
  5312. }
  5313. if (span.to != null) {
  5314. to = Pos(lineObj ? line : lineNo(line), span.to);
  5315. if (side == 1) { return to }
  5316. }
  5317. }
  5318. return from && {from: from, to: to}
  5319. };
  5320. // Signals that the marker's widget changed, and surrounding layout
  5321. // should be recomputed.
  5322. TextMarker.prototype.changed = function () {
  5323. var this$1 = this;
  5324. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5325. if (!pos || !cm) { return }
  5326. runInOp(cm, function () {
  5327. var line = pos.line, lineN = lineNo(pos.line);
  5328. var view = findViewForLine(cm, lineN);
  5329. if (view) {
  5330. clearLineMeasurementCacheFor(view);
  5331. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5332. }
  5333. cm.curOp.updateMaxLine = true;
  5334. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5335. var oldHeight = widget.height;
  5336. widget.height = null;
  5337. var dHeight = widgetHeight(widget) - oldHeight;
  5338. if (dHeight)
  5339. { updateLineHeight(line, line.height + dHeight); }
  5340. }
  5341. signalLater(cm, "markerChanged", cm, this$1);
  5342. });
  5343. };
  5344. TextMarker.prototype.attachLine = function (line) {
  5345. if (!this.lines.length && this.doc.cm) {
  5346. var op = this.doc.cm.curOp;
  5347. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5348. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5349. }
  5350. this.lines.push(line);
  5351. };
  5352. TextMarker.prototype.detachLine = function (line) {
  5353. this.lines.splice(indexOf(this.lines, line), 1);
  5354. if (!this.lines.length && this.doc.cm) {
  5355. var op = this.doc.cm.curOp
  5356. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5357. }
  5358. };
  5359. eventMixin(TextMarker);
  5360. // Create a marker, wire it up to the right lines, and
  5361. function markText(doc, from, to, options, type) {
  5362. // Shared markers (across linked documents) are handled separately
  5363. // (markTextShared will call out to this again, once per
  5364. // document).
  5365. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5366. // Ensure we are in an operation.
  5367. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5368. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5369. if (options) { copyObj(options, marker, false); }
  5370. // Don't connect empty markers unless clearWhenEmpty is false
  5371. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5372. { return marker }
  5373. if (marker.replacedWith) {
  5374. // Showing up as a widget implies collapsed (widget replaces text)
  5375. marker.collapsed = true;
  5376. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5377. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5378. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5379. }
  5380. if (marker.collapsed) {
  5381. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5382. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5383. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5384. seeCollapsedSpans();
  5385. }
  5386. if (marker.addToHistory)
  5387. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5388. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5389. doc.iter(curLine, to.line + 1, function (line) {
  5390. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5391. { updateMaxLine = true; }
  5392. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5393. addMarkedSpan(line, new MarkedSpan(marker,
  5394. curLine == from.line ? from.ch : null,
  5395. curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
  5396. ++curLine;
  5397. });
  5398. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5399. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5400. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5401. }); }
  5402. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5403. if (marker.readOnly) {
  5404. seeReadOnlySpans();
  5405. if (doc.history.done.length || doc.history.undone.length)
  5406. { doc.clearHistory(); }
  5407. }
  5408. if (marker.collapsed) {
  5409. marker.id = ++nextMarkerId;
  5410. marker.atomic = true;
  5411. }
  5412. if (cm) {
  5413. // Sync editor state
  5414. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5415. if (marker.collapsed)
  5416. { regChange(cm, from.line, to.line + 1); }
  5417. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5418. marker.attributes || marker.title)
  5419. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5420. if (marker.atomic) { reCheckSelection(cm.doc); }
  5421. signalLater(cm, "markerAdded", cm, marker);
  5422. }
  5423. return marker
  5424. }
  5425. // SHARED TEXTMARKERS
  5426. // A shared marker spans multiple linked documents. It is
  5427. // implemented as a meta-marker-object controlling multiple normal
  5428. // markers.
  5429. var SharedTextMarker = function(markers, primary) {
  5430. this.markers = markers;
  5431. this.primary = primary;
  5432. for (var i = 0; i < markers.length; ++i)
  5433. { markers[i].parent = this; }
  5434. };
  5435. SharedTextMarker.prototype.clear = function () {
  5436. if (this.explicitlyCleared) { return }
  5437. this.explicitlyCleared = true;
  5438. for (var i = 0; i < this.markers.length; ++i)
  5439. { this.markers[i].clear(); }
  5440. signalLater(this, "clear");
  5441. };
  5442. SharedTextMarker.prototype.find = function (side, lineObj) {
  5443. return this.primary.find(side, lineObj)
  5444. };
  5445. eventMixin(SharedTextMarker);
  5446. function markTextShared(doc, from, to, options, type) {
  5447. options = copyObj(options);
  5448. options.shared = false;
  5449. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5450. var widget = options.widgetNode;
  5451. linkedDocs(doc, function (doc) {
  5452. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5453. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5454. for (var i = 0; i < doc.linked.length; ++i)
  5455. { if (doc.linked[i].isParent) { return } }
  5456. primary = lst(markers);
  5457. });
  5458. return new SharedTextMarker(markers, primary)
  5459. }
  5460. function findSharedMarkers(doc) {
  5461. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5462. }
  5463. function copySharedMarkers(doc, markers) {
  5464. for (var i = 0; i < markers.length; i++) {
  5465. var marker = markers[i], pos = marker.find();
  5466. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5467. if (cmp(mFrom, mTo)) {
  5468. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5469. marker.markers.push(subMark);
  5470. subMark.parent = marker;
  5471. }
  5472. }
  5473. }
  5474. function detachSharedMarkers(markers) {
  5475. var loop = function ( i ) {
  5476. var marker = markers[i], linked = [marker.primary.doc];
  5477. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5478. for (var j = 0; j < marker.markers.length; j++) {
  5479. var subMarker = marker.markers[j];
  5480. if (indexOf(linked, subMarker.doc) == -1) {
  5481. subMarker.parent = null;
  5482. marker.markers.splice(j--, 1);
  5483. }
  5484. }
  5485. };
  5486. for (var i = 0; i < markers.length; i++) loop( i );
  5487. }
  5488. var nextDocId = 0;
  5489. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5490. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5491. if (firstLine == null) { firstLine = 0; }
  5492. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5493. this.first = firstLine;
  5494. this.scrollTop = this.scrollLeft = 0;
  5495. this.cantEdit = false;
  5496. this.cleanGeneration = 1;
  5497. this.modeFrontier = this.highlightFrontier = firstLine;
  5498. var start = Pos(firstLine, 0);
  5499. this.sel = simpleSelection(start);
  5500. this.history = new History(null);
  5501. this.id = ++nextDocId;
  5502. this.modeOption = mode;
  5503. this.lineSep = lineSep;
  5504. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5505. this.extend = false;
  5506. if (typeof text == "string") { text = this.splitLines(text); }
  5507. updateDoc(this, {from: start, to: start, text: text});
  5508. setSelection(this, simpleSelection(start), sel_dontScroll);
  5509. };
  5510. Doc.prototype = createObj(BranchChunk.prototype, {
  5511. constructor: Doc,
  5512. // Iterate over the document. Supports two forms -- with only one
  5513. // argument, it calls that for each line in the document. With
  5514. // three, it iterates over the range given by the first two (with
  5515. // the second being non-inclusive).
  5516. iter: function(from, to, op) {
  5517. if (op) { this.iterN(from - this.first, to - from, op); }
  5518. else { this.iterN(this.first, this.first + this.size, from); }
  5519. },
  5520. // Non-public interface for adding and removing lines.
  5521. insert: function(at, lines) {
  5522. var height = 0;
  5523. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5524. this.insertInner(at - this.first, lines, height);
  5525. },
  5526. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5527. // From here, the methods are part of the public interface. Most
  5528. // are also available from CodeMirror (editor) instances.
  5529. getValue: function(lineSep) {
  5530. var lines = getLines(this, this.first, this.first + this.size);
  5531. if (lineSep === false) { return lines }
  5532. return lines.join(lineSep || this.lineSeparator())
  5533. },
  5534. setValue: docMethodOp(function(code) {
  5535. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5536. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5537. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5538. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5539. setSelection(this, simpleSelection(top), sel_dontScroll);
  5540. }),
  5541. replaceRange: function(code, from, to, origin) {
  5542. from = clipPos(this, from);
  5543. to = to ? clipPos(this, to) : from;
  5544. replaceRange(this, code, from, to, origin);
  5545. },
  5546. getRange: function(from, to, lineSep) {
  5547. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5548. if (lineSep === false) { return lines }
  5549. if (lineSep === '') { return lines.join('') }
  5550. return lines.join(lineSep || this.lineSeparator())
  5551. },
  5552. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5553. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5554. getLineNumber: function(line) {return lineNo(line)},
  5555. getLineHandleVisualStart: function(line) {
  5556. if (typeof line == "number") { line = getLine(this, line); }
  5557. return visualLine(line)
  5558. },
  5559. lineCount: function() {return this.size},
  5560. firstLine: function() {return this.first},
  5561. lastLine: function() {return this.first + this.size - 1},
  5562. clipPos: function(pos) {return clipPos(this, pos)},
  5563. getCursor: function(start) {
  5564. var range = this.sel.primary(), pos;
  5565. if (start == null || start == "head") { pos = range.head; }
  5566. else if (start == "anchor") { pos = range.anchor; }
  5567. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  5568. else { pos = range.from(); }
  5569. return pos
  5570. },
  5571. listSelections: function() { return this.sel.ranges },
  5572. somethingSelected: function() {return this.sel.somethingSelected()},
  5573. setCursor: docMethodOp(function(line, ch, options) {
  5574. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5575. }),
  5576. setSelection: docMethodOp(function(anchor, head, options) {
  5577. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5578. }),
  5579. extendSelection: docMethodOp(function(head, other, options) {
  5580. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5581. }),
  5582. extendSelections: docMethodOp(function(heads, options) {
  5583. extendSelections(this, clipPosArray(this, heads), options);
  5584. }),
  5585. extendSelectionsBy: docMethodOp(function(f, options) {
  5586. var heads = map(this.sel.ranges, f);
  5587. extendSelections(this, clipPosArray(this, heads), options);
  5588. }),
  5589. setSelections: docMethodOp(function(ranges, primary, options) {
  5590. if (!ranges.length) { return }
  5591. var out = [];
  5592. for (var i = 0; i < ranges.length; i++)
  5593. { out[i] = new Range(clipPos(this, ranges[i].anchor),
  5594. clipPos(this, ranges[i].head || ranges[i].anchor)); }
  5595. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5596. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5597. }),
  5598. addSelection: docMethodOp(function(anchor, head, options) {
  5599. var ranges = this.sel.ranges.slice(0);
  5600. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5601. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5602. }),
  5603. getSelection: function(lineSep) {
  5604. var ranges = this.sel.ranges, lines;
  5605. for (var i = 0; i < ranges.length; i++) {
  5606. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5607. lines = lines ? lines.concat(sel) : sel;
  5608. }
  5609. if (lineSep === false) { return lines }
  5610. else { return lines.join(lineSep || this.lineSeparator()) }
  5611. },
  5612. getSelections: function(lineSep) {
  5613. var parts = [], ranges = this.sel.ranges;
  5614. for (var i = 0; i < ranges.length; i++) {
  5615. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5616. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  5617. parts[i] = sel;
  5618. }
  5619. return parts
  5620. },
  5621. replaceSelection: function(code, collapse, origin) {
  5622. var dup = [];
  5623. for (var i = 0; i < this.sel.ranges.length; i++)
  5624. { dup[i] = code; }
  5625. this.replaceSelections(dup, collapse, origin || "+input");
  5626. },
  5627. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5628. var changes = [], sel = this.sel;
  5629. for (var i = 0; i < sel.ranges.length; i++) {
  5630. var range = sel.ranges[i];
  5631. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  5632. }
  5633. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5634. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5635. { makeChange(this, changes[i$1]); }
  5636. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5637. else if (this.cm) { ensureCursorVisible(this.cm); }
  5638. }),
  5639. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5640. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5641. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5642. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5643. setExtending: function(val) {this.extend = val;},
  5644. getExtending: function() {return this.extend},
  5645. historySize: function() {
  5646. var hist = this.history, done = 0, undone = 0;
  5647. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5648. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5649. return {undo: done, redo: undone}
  5650. },
  5651. clearHistory: function() {
  5652. var this$1 = this;
  5653. this.history = new History(this.history);
  5654. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  5655. },
  5656. markClean: function() {
  5657. this.cleanGeneration = this.changeGeneration(true);
  5658. },
  5659. changeGeneration: function(forceSplit) {
  5660. if (forceSplit)
  5661. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5662. return this.history.generation
  5663. },
  5664. isClean: function (gen) {
  5665. return this.history.generation == (gen || this.cleanGeneration)
  5666. },
  5667. getHistory: function() {
  5668. return {done: copyHistoryArray(this.history.done),
  5669. undone: copyHistoryArray(this.history.undone)}
  5670. },
  5671. setHistory: function(histData) {
  5672. var hist = this.history = new History(this.history);
  5673. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5674. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5675. },
  5676. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5677. return changeLine(this, line, "gutter", function (line) {
  5678. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5679. markers[gutterID] = value;
  5680. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5681. return true
  5682. })
  5683. }),
  5684. clearGutter: docMethodOp(function(gutterID) {
  5685. var this$1 = this;
  5686. this.iter(function (line) {
  5687. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5688. changeLine(this$1, line, "gutter", function () {
  5689. line.gutterMarkers[gutterID] = null;
  5690. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5691. return true
  5692. });
  5693. }
  5694. });
  5695. }),
  5696. lineInfo: function(line) {
  5697. var n;
  5698. if (typeof line == "number") {
  5699. if (!isLine(this, line)) { return null }
  5700. n = line;
  5701. line = getLine(this, line);
  5702. if (!line) { return null }
  5703. } else {
  5704. n = lineNo(line);
  5705. if (n == null) { return null }
  5706. }
  5707. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5708. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5709. widgets: line.widgets}
  5710. },
  5711. addLineClass: docMethodOp(function(handle, where, cls) {
  5712. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5713. var prop = where == "text" ? "textClass"
  5714. : where == "background" ? "bgClass"
  5715. : where == "gutter" ? "gutterClass" : "wrapClass";
  5716. if (!line[prop]) { line[prop] = cls; }
  5717. else if (classTest(cls).test(line[prop])) { return false }
  5718. else { line[prop] += " " + cls; }
  5719. return true
  5720. })
  5721. }),
  5722. removeLineClass: docMethodOp(function(handle, where, cls) {
  5723. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5724. var prop = where == "text" ? "textClass"
  5725. : where == "background" ? "bgClass"
  5726. : where == "gutter" ? "gutterClass" : "wrapClass";
  5727. var cur = line[prop];
  5728. if (!cur) { return false }
  5729. else if (cls == null) { line[prop] = null; }
  5730. else {
  5731. var found = cur.match(classTest(cls));
  5732. if (!found) { return false }
  5733. var end = found.index + found[0].length;
  5734. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5735. }
  5736. return true
  5737. })
  5738. }),
  5739. addLineWidget: docMethodOp(function(handle, node, options) {
  5740. return addLineWidget(this, handle, node, options)
  5741. }),
  5742. removeLineWidget: function(widget) { widget.clear(); },
  5743. markText: function(from, to, options) {
  5744. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5745. },
  5746. setBookmark: function(pos, options) {
  5747. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5748. insertLeft: options && options.insertLeft,
  5749. clearWhenEmpty: false, shared: options && options.shared,
  5750. handleMouseEvents: options && options.handleMouseEvents};
  5751. pos = clipPos(this, pos);
  5752. return markText(this, pos, pos, realOpts, "bookmark")
  5753. },
  5754. findMarksAt: function(pos) {
  5755. pos = clipPos(this, pos);
  5756. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5757. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5758. var span = spans[i];
  5759. if ((span.from == null || span.from <= pos.ch) &&
  5760. (span.to == null || span.to >= pos.ch))
  5761. { markers.push(span.marker.parent || span.marker); }
  5762. } }
  5763. return markers
  5764. },
  5765. findMarks: function(from, to, filter) {
  5766. from = clipPos(this, from); to = clipPos(this, to);
  5767. var found = [], lineNo = from.line;
  5768. this.iter(from.line, to.line + 1, function (line) {
  5769. var spans = line.markedSpans;
  5770. if (spans) { for (var i = 0; i < spans.length; i++) {
  5771. var span = spans[i];
  5772. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5773. span.from == null && lineNo != from.line ||
  5774. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5775. (!filter || filter(span.marker)))
  5776. { found.push(span.marker.parent || span.marker); }
  5777. } }
  5778. ++lineNo;
  5779. });
  5780. return found
  5781. },
  5782. getAllMarks: function() {
  5783. var markers = [];
  5784. this.iter(function (line) {
  5785. var sps = line.markedSpans;
  5786. if (sps) { for (var i = 0; i < sps.length; ++i)
  5787. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5788. });
  5789. return markers
  5790. },
  5791. posFromIndex: function(off) {
  5792. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  5793. this.iter(function (line) {
  5794. var sz = line.text.length + sepSize;
  5795. if (sz > off) { ch = off; return true }
  5796. off -= sz;
  5797. ++lineNo;
  5798. });
  5799. return clipPos(this, Pos(lineNo, ch))
  5800. },
  5801. indexFromPos: function (coords) {
  5802. coords = clipPos(this, coords);
  5803. var index = coords.ch;
  5804. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5805. var sepSize = this.lineSeparator().length;
  5806. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5807. index += line.text.length + sepSize;
  5808. });
  5809. return index
  5810. },
  5811. copy: function(copyHistory) {
  5812. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5813. this.modeOption, this.first, this.lineSep, this.direction);
  5814. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5815. doc.sel = this.sel;
  5816. doc.extend = false;
  5817. if (copyHistory) {
  5818. doc.history.undoDepth = this.history.undoDepth;
  5819. doc.setHistory(this.getHistory());
  5820. }
  5821. return doc
  5822. },
  5823. linkedDoc: function(options) {
  5824. if (!options) { options = {}; }
  5825. var from = this.first, to = this.first + this.size;
  5826. if (options.from != null && options.from > from) { from = options.from; }
  5827. if (options.to != null && options.to < to) { to = options.to; }
  5828. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5829. if (options.sharedHist) { copy.history = this.history
  5830. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5831. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5832. copySharedMarkers(copy, findSharedMarkers(this));
  5833. return copy
  5834. },
  5835. unlinkDoc: function(other) {
  5836. if (other instanceof CodeMirror) { other = other.doc; }
  5837. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5838. var link = this.linked[i];
  5839. if (link.doc != other) { continue }
  5840. this.linked.splice(i, 1);
  5841. other.unlinkDoc(this);
  5842. detachSharedMarkers(findSharedMarkers(this));
  5843. break
  5844. } }
  5845. // If the histories were shared, split them again
  5846. if (other.history == this.history) {
  5847. var splitIds = [other.id];
  5848. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5849. other.history = new History(null);
  5850. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5851. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5852. }
  5853. },
  5854. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5855. getMode: function() {return this.mode},
  5856. getEditor: function() {return this.cm},
  5857. splitLines: function(str) {
  5858. if (this.lineSep) { return str.split(this.lineSep) }
  5859. return splitLinesAuto(str)
  5860. },
  5861. lineSeparator: function() { return this.lineSep || "\n" },
  5862. setDirection: docMethodOp(function (dir) {
  5863. if (dir != "rtl") { dir = "ltr"; }
  5864. if (dir == this.direction) { return }
  5865. this.direction = dir;
  5866. this.iter(function (line) { return line.order = null; });
  5867. if (this.cm) { directionChanged(this.cm); }
  5868. })
  5869. });
  5870. // Public alias.
  5871. Doc.prototype.eachLine = Doc.prototype.iter;
  5872. // Kludge to work around strange IE behavior where it'll sometimes
  5873. // re-fire a series of drag-related events right after the drop (#1551)
  5874. var lastDrop = 0;
  5875. function onDrop(e) {
  5876. var cm = this;
  5877. clearDragCursor(cm);
  5878. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5879. { return }
  5880. e_preventDefault(e);
  5881. if (ie) { lastDrop = +new Date; }
  5882. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5883. if (!pos || cm.isReadOnly()) { return }
  5884. // Might be a file drop, in which case we simply extract the text
  5885. // and insert it.
  5886. if (files && files.length && window.FileReader && window.File) {
  5887. var n = files.length, text = Array(n), read = 0;
  5888. var markAsReadAndPasteIfAllFilesAreRead = function () {
  5889. if (++read == n) {
  5890. operation(cm, function () {
  5891. pos = clipPos(cm.doc, pos);
  5892. var change = {from: pos, to: pos,
  5893. text: cm.doc.splitLines(
  5894. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  5895. origin: "paste"};
  5896. makeChange(cm.doc, change);
  5897. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  5898. })();
  5899. }
  5900. };
  5901. var readTextFromFile = function (file, i) {
  5902. if (cm.options.allowDropFileTypes &&
  5903. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  5904. markAsReadAndPasteIfAllFilesAreRead();
  5905. return
  5906. }
  5907. var reader = new FileReader;
  5908. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  5909. reader.onload = function () {
  5910. var content = reader.result;
  5911. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  5912. markAsReadAndPasteIfAllFilesAreRead();
  5913. return
  5914. }
  5915. text[i] = content;
  5916. markAsReadAndPasteIfAllFilesAreRead();
  5917. };
  5918. reader.readAsText(file);
  5919. };
  5920. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  5921. } else { // Normal drop
  5922. // Don't do a replace if the drop happened inside of the selected text.
  5923. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5924. cm.state.draggingText(e);
  5925. // Ensure the editor is re-focused
  5926. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5927. return
  5928. }
  5929. try {
  5930. var text$1 = e.dataTransfer.getData("Text");
  5931. if (text$1) {
  5932. var selected;
  5933. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5934. { selected = cm.listSelections(); }
  5935. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5936. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5937. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5938. cm.replaceSelection(text$1, "around", "paste");
  5939. cm.display.input.focus();
  5940. }
  5941. }
  5942. catch(e$1){}
  5943. }
  5944. }
  5945. function onDragStart(cm, e) {
  5946. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5947. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5948. e.dataTransfer.setData("Text", cm.getSelection());
  5949. e.dataTransfer.effectAllowed = "copyMove";
  5950. // Use dummy image instead of default browsers image.
  5951. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5952. if (e.dataTransfer.setDragImage && !safari) {
  5953. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5954. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5955. if (presto) {
  5956. img.width = img.height = 1;
  5957. cm.display.wrapper.appendChild(img);
  5958. // Force a relayout, or Opera won't use our image for some obscure reason
  5959. img._top = img.offsetTop;
  5960. }
  5961. e.dataTransfer.setDragImage(img, 0, 0);
  5962. if (presto) { img.parentNode.removeChild(img); }
  5963. }
  5964. }
  5965. function onDragOver(cm, e) {
  5966. var pos = posFromMouse(cm, e);
  5967. if (!pos) { return }
  5968. var frag = document.createDocumentFragment();
  5969. drawSelectionCursor(cm, pos, frag);
  5970. if (!cm.display.dragCursor) {
  5971. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5972. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5973. }
  5974. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5975. }
  5976. function clearDragCursor(cm) {
  5977. if (cm.display.dragCursor) {
  5978. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5979. cm.display.dragCursor = null;
  5980. }
  5981. }
  5982. // These must be handled carefully, because naively registering a
  5983. // handler for each editor will cause the editors to never be
  5984. // garbage collected.
  5985. function forEachCodeMirror(f) {
  5986. if (!document.getElementsByClassName) { return }
  5987. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  5988. for (var i = 0; i < byClass.length; i++) {
  5989. var cm = byClass[i].CodeMirror;
  5990. if (cm) { editors.push(cm); }
  5991. }
  5992. if (editors.length) { editors[0].operation(function () {
  5993. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  5994. }); }
  5995. }
  5996. var globalsRegistered = false;
  5997. function ensureGlobalHandlers() {
  5998. if (globalsRegistered) { return }
  5999. registerGlobalHandlers();
  6000. globalsRegistered = true;
  6001. }
  6002. function registerGlobalHandlers() {
  6003. // When the window resizes, we need to refresh active editors.
  6004. var resizeTimer;
  6005. on(window, "resize", function () {
  6006. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  6007. resizeTimer = null;
  6008. forEachCodeMirror(onResize);
  6009. }, 100); }
  6010. });
  6011. // When the window loses focus, we want to show the editor as blurred
  6012. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6013. }
  6014. // Called when the window resizes
  6015. function onResize(cm) {
  6016. var d = cm.display;
  6017. // Might be a text scaling operation, clear size caches.
  6018. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6019. d.scrollbarsClipped = false;
  6020. cm.setSize();
  6021. }
  6022. var keyNames = {
  6023. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6024. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6025. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6026. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6027. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6028. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6029. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6030. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6031. };
  6032. // Number keys
  6033. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6034. // Alphabetic keys
  6035. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6036. // Function keys
  6037. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6038. var keyMap = {};
  6039. keyMap.basic = {
  6040. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6041. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6042. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6043. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6044. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6045. "Esc": "singleSelection"
  6046. };
  6047. // Note that the save and find-related commands aren't defined by
  6048. // default. User code or addons can define them. Unknown commands
  6049. // are simply ignored.
  6050. keyMap.pcDefault = {
  6051. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6052. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6053. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6054. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6055. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6056. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6057. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6058. "fallthrough": "basic"
  6059. };
  6060. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6061. keyMap.emacsy = {
  6062. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6063. "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
  6064. "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
  6065. "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  6066. };
  6067. keyMap.macDefault = {
  6068. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6069. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6070. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6071. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6072. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6073. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6074. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6075. "fallthrough": ["basic", "emacsy"]
  6076. };
  6077. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6078. // KEYMAP DISPATCH
  6079. function normalizeKeyName(name) {
  6080. var parts = name.split(/-(?!$)/);
  6081. name = parts[parts.length - 1];
  6082. var alt, ctrl, shift, cmd;
  6083. for (var i = 0; i < parts.length - 1; i++) {
  6084. var mod = parts[i];
  6085. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6086. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6087. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6088. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6089. else { throw new Error("Unrecognized modifier name: " + mod) }
  6090. }
  6091. if (alt) { name = "Alt-" + name; }
  6092. if (ctrl) { name = "Ctrl-" + name; }
  6093. if (cmd) { name = "Cmd-" + name; }
  6094. if (shift) { name = "Shift-" + name; }
  6095. return name
  6096. }
  6097. // This is a kludge to keep keymaps mostly working as raw objects
  6098. // (backwards compatibility) while at the same time support features
  6099. // like normalization and multi-stroke key bindings. It compiles a
  6100. // new normalized keymap, and then updates the old object to reflect
  6101. // this.
  6102. function normalizeKeyMap(keymap) {
  6103. var copy = {};
  6104. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6105. var value = keymap[keyname];
  6106. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6107. if (value == "...") { delete keymap[keyname]; continue }
  6108. var keys = map(keyname.split(" "), normalizeKeyName);
  6109. for (var i = 0; i < keys.length; i++) {
  6110. var val = (void 0), name = (void 0);
  6111. if (i == keys.length - 1) {
  6112. name = keys.join(" ");
  6113. val = value;
  6114. } else {
  6115. name = keys.slice(0, i + 1).join(" ");
  6116. val = "...";
  6117. }
  6118. var prev = copy[name];
  6119. if (!prev) { copy[name] = val; }
  6120. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6121. }
  6122. delete keymap[keyname];
  6123. } }
  6124. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6125. return keymap
  6126. }
  6127. function lookupKey(key, map, handle, context) {
  6128. map = getKeyMap(map);
  6129. var found = map.call ? map.call(key, context) : map[key];
  6130. if (found === false) { return "nothing" }
  6131. if (found === "...") { return "multi" }
  6132. if (found != null && handle(found)) { return "handled" }
  6133. if (map.fallthrough) {
  6134. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6135. { return lookupKey(key, map.fallthrough, handle, context) }
  6136. for (var i = 0; i < map.fallthrough.length; i++) {
  6137. var result = lookupKey(key, map.fallthrough[i], handle, context);
  6138. if (result) { return result }
  6139. }
  6140. }
  6141. }
  6142. // Modifier key presses don't count as 'real' key presses for the
  6143. // purpose of keymap fallthrough.
  6144. function isModifierKey(value) {
  6145. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6146. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6147. }
  6148. function addModifierNames(name, event, noShift) {
  6149. var base = name;
  6150. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6151. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6152. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  6153. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6154. return name
  6155. }
  6156. // Look up the name of a key as indicated by an event object.
  6157. function keyName(event, noShift) {
  6158. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6159. var name = keyNames[event.keyCode];
  6160. if (name == null || event.altGraphKey) { return false }
  6161. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6162. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6163. if (event.keyCode == 3 && event.code) { name = event.code; }
  6164. return addModifierNames(name, event, noShift)
  6165. }
  6166. function getKeyMap(val) {
  6167. return typeof val == "string" ? keyMap[val] : val
  6168. }
  6169. // Helper for deleting text near the selection(s), used to implement
  6170. // backspace, delete, and similar functionality.
  6171. function deleteNearSelection(cm, compute) {
  6172. var ranges = cm.doc.sel.ranges, kill = [];
  6173. // Build up a set of ranges to kill first, merging overlapping
  6174. // ranges.
  6175. for (var i = 0; i < ranges.length; i++) {
  6176. var toKill = compute(ranges[i]);
  6177. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6178. var replaced = kill.pop();
  6179. if (cmp(replaced.from, toKill.from) < 0) {
  6180. toKill.from = replaced.from;
  6181. break
  6182. }
  6183. }
  6184. kill.push(toKill);
  6185. }
  6186. // Next, remove those actual ranges.
  6187. runInOp(cm, function () {
  6188. for (var i = kill.length - 1; i >= 0; i--)
  6189. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6190. ensureCursorVisible(cm);
  6191. });
  6192. }
  6193. function moveCharLogically(line, ch, dir) {
  6194. var target = skipExtendingChars(line.text, ch + dir, dir);
  6195. return target < 0 || target > line.text.length ? null : target
  6196. }
  6197. function moveLogically(line, start, dir) {
  6198. var ch = moveCharLogically(line, start.ch, dir);
  6199. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6200. }
  6201. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6202. if (visually) {
  6203. if (cm.doc.direction == "rtl") { dir = -dir; }
  6204. var order = getOrder(lineObj, cm.doc.direction);
  6205. if (order) {
  6206. var part = dir < 0 ? lst(order) : order[0];
  6207. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6208. var sticky = moveInStorageOrder ? "after" : "before";
  6209. var ch;
  6210. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6211. // it could be that the last bidi part is not on the last visual line,
  6212. // since visual lines contain content order-consecutive chunks.
  6213. // Thus, in rtl, we are looking for the first (content-order) character
  6214. // in the rtl chunk that is on the last line (that is, the same line
  6215. // as the last (content-order) character).
  6216. if (part.level > 0 || cm.doc.direction == "rtl") {
  6217. var prep = prepareMeasureForLine(cm, lineObj);
  6218. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6219. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6220. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6221. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6222. } else { ch = dir < 0 ? part.to : part.from; }
  6223. return new Pos(lineNo, ch, sticky)
  6224. }
  6225. }
  6226. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6227. }
  6228. function moveVisually(cm, line, start, dir) {
  6229. var bidi = getOrder(line, cm.doc.direction);
  6230. if (!bidi) { return moveLogically(line, start, dir) }
  6231. if (start.ch >= line.text.length) {
  6232. start.ch = line.text.length;
  6233. start.sticky = "before";
  6234. } else if (start.ch <= 0) {
  6235. start.ch = 0;
  6236. start.sticky = "after";
  6237. }
  6238. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6239. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6240. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6241. // nothing interesting happens.
  6242. return moveLogically(line, start, dir)
  6243. }
  6244. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6245. var prep;
  6246. var getWrappedLineExtent = function (ch) {
  6247. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6248. prep = prep || prepareMeasureForLine(cm, line);
  6249. return wrappedLineExtentChar(cm, line, prep, ch)
  6250. };
  6251. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6252. if (cm.doc.direction == "rtl" || part.level == 1) {
  6253. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6254. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6255. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6256. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6257. var sticky = moveInStorageOrder ? "before" : "after";
  6258. return new Pos(start.line, ch, sticky)
  6259. }
  6260. }
  6261. // Case 3: Could not move within this bidi part in this visual line, so leave
  6262. // the current bidi part
  6263. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6264. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6265. ? new Pos(start.line, mv(ch, 1), "before")
  6266. : new Pos(start.line, ch, "after"); };
  6267. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6268. var part = bidi[partPos];
  6269. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6270. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6271. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6272. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6273. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6274. }
  6275. };
  6276. // Case 3a: Look for other bidi parts on the same visual line
  6277. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6278. if (res) { return res }
  6279. // Case 3b: Look for other bidi parts on the next visual line
  6280. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6281. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6282. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6283. if (res) { return res }
  6284. }
  6285. // Case 4: Nowhere to move
  6286. return null
  6287. }
  6288. // Commands are parameter-less actions that can be performed on an
  6289. // editor, mostly used for keybindings.
  6290. var commands = {
  6291. selectAll: selectAll,
  6292. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6293. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6294. if (range.empty()) {
  6295. var len = getLine(cm.doc, range.head.line).text.length;
  6296. if (range.head.ch == len && range.head.line < cm.lastLine())
  6297. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6298. else
  6299. { return {from: range.head, to: Pos(range.head.line, len)} }
  6300. } else {
  6301. return {from: range.from(), to: range.to()}
  6302. }
  6303. }); },
  6304. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6305. from: Pos(range.from().line, 0),
  6306. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6307. }); }); },
  6308. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6309. from: Pos(range.from().line, 0), to: range.from()
  6310. }); }); },
  6311. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6312. var top = cm.charCoords(range.head, "div").top + 5;
  6313. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6314. return {from: leftPos, to: range.from()}
  6315. }); },
  6316. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6317. var top = cm.charCoords(range.head, "div").top + 5;
  6318. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6319. return {from: range.from(), to: rightPos }
  6320. }); },
  6321. undo: function (cm) { return cm.undo(); },
  6322. redo: function (cm) { return cm.redo(); },
  6323. undoSelection: function (cm) { return cm.undoSelection(); },
  6324. redoSelection: function (cm) { return cm.redoSelection(); },
  6325. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6326. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6327. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6328. {origin: "+move", bias: 1}
  6329. ); },
  6330. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6331. {origin: "+move", bias: 1}
  6332. ); },
  6333. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6334. {origin: "+move", bias: -1}
  6335. ); },
  6336. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6337. var top = cm.cursorCoords(range.head, "div").top + 5;
  6338. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6339. }, sel_move); },
  6340. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6341. var top = cm.cursorCoords(range.head, "div").top + 5;
  6342. return cm.coordsChar({left: 0, top: top}, "div")
  6343. }, sel_move); },
  6344. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6345. var top = cm.cursorCoords(range.head, "div").top + 5;
  6346. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6347. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6348. return pos
  6349. }, sel_move); },
  6350. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6351. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6352. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6353. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6354. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6355. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6356. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6357. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6358. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6359. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6360. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6361. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6362. delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  6363. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6364. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6365. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6366. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6367. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6368. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6369. indentMore: function (cm) { return cm.indentSelection("add"); },
  6370. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6371. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6372. insertSoftTab: function (cm) {
  6373. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6374. for (var i = 0; i < ranges.length; i++) {
  6375. var pos = ranges[i].from();
  6376. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6377. spaces.push(spaceStr(tabSize - col % tabSize));
  6378. }
  6379. cm.replaceSelections(spaces);
  6380. },
  6381. defaultTab: function (cm) {
  6382. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6383. else { cm.execCommand("insertTab"); }
  6384. },
  6385. // Swap the two chars left and right of each selection's head.
  6386. // Move cursor behind the two swapped characters afterwards.
  6387. //
  6388. // Doesn't consider line feeds a character.
  6389. // Doesn't scan more than one line above to find a character.
  6390. // Doesn't do anything on an empty line.
  6391. // Doesn't do anything with non-empty selections.
  6392. transposeChars: function (cm) { return runInOp(cm, function () {
  6393. var ranges = cm.listSelections(), newSel = [];
  6394. for (var i = 0; i < ranges.length; i++) {
  6395. if (!ranges[i].empty()) { continue }
  6396. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6397. if (line) {
  6398. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6399. if (cur.ch > 0) {
  6400. cur = new Pos(cur.line, cur.ch + 1);
  6401. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6402. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6403. } else if (cur.line > cm.doc.first) {
  6404. var prev = getLine(cm.doc, cur.line - 1).text;
  6405. if (prev) {
  6406. cur = new Pos(cur.line, 1);
  6407. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6408. prev.charAt(prev.length - 1),
  6409. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6410. }
  6411. }
  6412. }
  6413. newSel.push(new Range(cur, cur));
  6414. }
  6415. cm.setSelections(newSel);
  6416. }); },
  6417. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6418. var sels = cm.listSelections();
  6419. for (var i = sels.length - 1; i >= 0; i--)
  6420. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6421. sels = cm.listSelections();
  6422. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6423. { cm.indentLine(sels[i$1].from().line, null, true); }
  6424. ensureCursorVisible(cm);
  6425. }); },
  6426. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6427. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6428. };
  6429. function lineStart(cm, lineN) {
  6430. var line = getLine(cm.doc, lineN);
  6431. var visual = visualLine(line);
  6432. if (visual != line) { lineN = lineNo(visual); }
  6433. return endOfLine(true, cm, visual, lineN, 1)
  6434. }
  6435. function lineEnd(cm, lineN) {
  6436. var line = getLine(cm.doc, lineN);
  6437. var visual = visualLineEnd(line);
  6438. if (visual != line) { lineN = lineNo(visual); }
  6439. return endOfLine(true, cm, line, lineN, -1)
  6440. }
  6441. function lineStartSmart(cm, pos) {
  6442. var start = lineStart(cm, pos.line);
  6443. var line = getLine(cm.doc, start.line);
  6444. var order = getOrder(line, cm.doc.direction);
  6445. if (!order || order[0].level == 0) {
  6446. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  6447. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6448. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6449. }
  6450. return start
  6451. }
  6452. // Run a handler that was bound to a key.
  6453. function doHandleBinding(cm, bound, dropShift) {
  6454. if (typeof bound == "string") {
  6455. bound = commands[bound];
  6456. if (!bound) { return false }
  6457. }
  6458. // Ensure previous input has been read, so that the handler sees a
  6459. // consistent view of the document
  6460. cm.display.input.ensurePolled();
  6461. var prevShift = cm.display.shift, done = false;
  6462. try {
  6463. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6464. if (dropShift) { cm.display.shift = false; }
  6465. done = bound(cm) != Pass;
  6466. } finally {
  6467. cm.display.shift = prevShift;
  6468. cm.state.suppressEdits = false;
  6469. }
  6470. return done
  6471. }
  6472. function lookupKeyForEditor(cm, name, handle) {
  6473. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6474. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6475. if (result) { return result }
  6476. }
  6477. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6478. || lookupKey(name, cm.options.keyMap, handle, cm)
  6479. }
  6480. // Note that, despite the name, this function is also used to check
  6481. // for bound mouse clicks.
  6482. var stopSeq = new Delayed;
  6483. function dispatchKey(cm, name, e, handle) {
  6484. var seq = cm.state.keySeq;
  6485. if (seq) {
  6486. if (isModifierKey(name)) { return "handled" }
  6487. if (/\'$/.test(name))
  6488. { cm.state.keySeq = null; }
  6489. else
  6490. { stopSeq.set(50, function () {
  6491. if (cm.state.keySeq == seq) {
  6492. cm.state.keySeq = null;
  6493. cm.display.input.reset();
  6494. }
  6495. }); }
  6496. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6497. }
  6498. return dispatchKeyInner(cm, name, e, handle)
  6499. }
  6500. function dispatchKeyInner(cm, name, e, handle) {
  6501. var result = lookupKeyForEditor(cm, name, handle);
  6502. if (result == "multi")
  6503. { cm.state.keySeq = name; }
  6504. if (result == "handled")
  6505. { signalLater(cm, "keyHandled", cm, name, e); }
  6506. if (result == "handled" || result == "multi") {
  6507. e_preventDefault(e);
  6508. restartBlink(cm);
  6509. }
  6510. return !!result
  6511. }
  6512. // Handle a key from the keydown event.
  6513. function handleKeyBinding(cm, e) {
  6514. var name = keyName(e, true);
  6515. if (!name) { return false }
  6516. if (e.shiftKey && !cm.state.keySeq) {
  6517. // First try to resolve full name (including 'Shift-'). Failing
  6518. // that, see if there is a cursor-motion command (starting with
  6519. // 'go') bound to the keyname without 'Shift-'.
  6520. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6521. || dispatchKey(cm, name, e, function (b) {
  6522. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6523. { return doHandleBinding(cm, b) }
  6524. })
  6525. } else {
  6526. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6527. }
  6528. }
  6529. // Handle a key from the keypress event
  6530. function handleCharBinding(cm, e, ch) {
  6531. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6532. }
  6533. var lastStoppedKey = null;
  6534. function onKeyDown(e) {
  6535. var cm = this;
  6536. if (e.target && e.target != cm.display.input.getField()) { return }
  6537. cm.curOp.focus = activeElt();
  6538. if (signalDOMEvent(cm, e)) { return }
  6539. // IE does strange things with escape.
  6540. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6541. var code = e.keyCode;
  6542. cm.display.shift = code == 16 || e.shiftKey;
  6543. var handled = handleKeyBinding(cm, e);
  6544. if (presto) {
  6545. lastStoppedKey = handled ? code : null;
  6546. // Opera has no cut event... we try to at least catch the key combo
  6547. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6548. { cm.replaceSelection("", null, "cut"); }
  6549. }
  6550. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  6551. { document.execCommand("cut"); }
  6552. // Turn mouse into crosshair when Alt is held on Mac.
  6553. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6554. { showCrossHair(cm); }
  6555. }
  6556. function showCrossHair(cm) {
  6557. var lineDiv = cm.display.lineDiv;
  6558. addClass(lineDiv, "CodeMirror-crosshair");
  6559. function up(e) {
  6560. if (e.keyCode == 18 || !e.altKey) {
  6561. rmClass(lineDiv, "CodeMirror-crosshair");
  6562. off(document, "keyup", up);
  6563. off(document, "mouseover", up);
  6564. }
  6565. }
  6566. on(document, "keyup", up);
  6567. on(document, "mouseover", up);
  6568. }
  6569. function onKeyUp(e) {
  6570. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6571. signalDOMEvent(this, e);
  6572. }
  6573. function onKeyPress(e) {
  6574. var cm = this;
  6575. if (e.target && e.target != cm.display.input.getField()) { return }
  6576. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6577. var keyCode = e.keyCode, charCode = e.charCode;
  6578. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6579. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6580. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6581. // Some browsers fire keypress events for backspace
  6582. if (ch == "\x08") { return }
  6583. if (handleCharBinding(cm, e, ch)) { return }
  6584. cm.display.input.onKeyPress(e);
  6585. }
  6586. var DOUBLECLICK_DELAY = 400;
  6587. var PastClick = function(time, pos, button) {
  6588. this.time = time;
  6589. this.pos = pos;
  6590. this.button = button;
  6591. };
  6592. PastClick.prototype.compare = function (time, pos, button) {
  6593. return this.time + DOUBLECLICK_DELAY > time &&
  6594. cmp(pos, this.pos) == 0 && button == this.button
  6595. };
  6596. var lastClick, lastDoubleClick;
  6597. function clickRepeat(pos, button) {
  6598. var now = +new Date;
  6599. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6600. lastClick = lastDoubleClick = null;
  6601. return "triple"
  6602. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6603. lastDoubleClick = new PastClick(now, pos, button);
  6604. lastClick = null;
  6605. return "double"
  6606. } else {
  6607. lastClick = new PastClick(now, pos, button);
  6608. lastDoubleClick = null;
  6609. return "single"
  6610. }
  6611. }
  6612. // A mouse down can be a single click, double click, triple click,
  6613. // start of selection drag, start of text drag, new cursor
  6614. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6615. // middle-click-paste. Or it might be a click on something we should
  6616. // not interfere with, such as a scrollbar or widget.
  6617. function onMouseDown(e) {
  6618. var cm = this, display = cm.display;
  6619. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6620. display.input.ensurePolled();
  6621. display.shift = e.shiftKey;
  6622. if (eventInWidget(display, e)) {
  6623. if (!webkit) {
  6624. // Briefly turn off draggability, to allow widgets to do
  6625. // normal dragging things.
  6626. display.scroller.draggable = false;
  6627. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6628. }
  6629. return
  6630. }
  6631. if (clickInGutter(cm, e)) { return }
  6632. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6633. window.focus();
  6634. // #3261: make sure, that we're not starting a second selection
  6635. if (button == 1 && cm.state.selectingText)
  6636. { cm.state.selectingText(e); }
  6637. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6638. if (button == 1) {
  6639. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6640. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6641. } else if (button == 2) {
  6642. if (pos) { extendSelection(cm.doc, pos); }
  6643. setTimeout(function () { return display.input.focus(); }, 20);
  6644. } else if (button == 3) {
  6645. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6646. else { delayBlurEvent(cm); }
  6647. }
  6648. }
  6649. function handleMappedButton(cm, button, pos, repeat, event) {
  6650. var name = "Click";
  6651. if (repeat == "double") { name = "Double" + name; }
  6652. else if (repeat == "triple") { name = "Triple" + name; }
  6653. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6654. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6655. if (typeof bound == "string") { bound = commands[bound]; }
  6656. if (!bound) { return false }
  6657. var done = false;
  6658. try {
  6659. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6660. done = bound(cm, pos) != Pass;
  6661. } finally {
  6662. cm.state.suppressEdits = false;
  6663. }
  6664. return done
  6665. })
  6666. }
  6667. function configureMouse(cm, repeat, event) {
  6668. var option = cm.getOption("configureMouse");
  6669. var value = option ? option(cm, repeat, event) : {};
  6670. if (value.unit == null) {
  6671. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6672. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6673. }
  6674. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6675. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6676. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6677. return value
  6678. }
  6679. function leftButtonDown(cm, pos, repeat, event) {
  6680. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6681. else { cm.curOp.focus = activeElt(); }
  6682. var behavior = configureMouse(cm, repeat, event);
  6683. var sel = cm.doc.sel, contained;
  6684. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6685. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6686. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6687. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6688. { leftButtonStartDrag(cm, event, pos, behavior); }
  6689. else
  6690. { leftButtonSelect(cm, event, pos, behavior); }
  6691. }
  6692. // Start a text drag. When it ends, see if any dragging actually
  6693. // happen, and treat as a click if it didn't.
  6694. function leftButtonStartDrag(cm, event, pos, behavior) {
  6695. var display = cm.display, moved = false;
  6696. var dragEnd = operation(cm, function (e) {
  6697. if (webkit) { display.scroller.draggable = false; }
  6698. cm.state.draggingText = false;
  6699. if (cm.state.delayingBlurEvent) {
  6700. if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  6701. else { delayBlurEvent(cm); }
  6702. }
  6703. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6704. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6705. off(display.scroller, "dragstart", dragStart);
  6706. off(display.scroller, "drop", dragEnd);
  6707. if (!moved) {
  6708. e_preventDefault(e);
  6709. if (!behavior.addNew)
  6710. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6711. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6712. if ((webkit && !safari) || ie && ie_version == 9)
  6713. { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  6714. else
  6715. { display.input.focus(); }
  6716. }
  6717. });
  6718. var mouseMove = function(e2) {
  6719. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6720. };
  6721. var dragStart = function () { return moved = true; };
  6722. // Let the drag handler handle this.
  6723. if (webkit) { display.scroller.draggable = true; }
  6724. cm.state.draggingText = dragEnd;
  6725. dragEnd.copy = !behavior.moveOnDrag;
  6726. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6727. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6728. on(display.scroller, "dragstart", dragStart);
  6729. on(display.scroller, "drop", dragEnd);
  6730. cm.state.delayingBlurEvent = true;
  6731. setTimeout(function () { return display.input.focus(); }, 20);
  6732. // IE's approach to draggable
  6733. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6734. }
  6735. function rangeForUnit(cm, pos, unit) {
  6736. if (unit == "char") { return new Range(pos, pos) }
  6737. if (unit == "word") { return cm.findWordAt(pos) }
  6738. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6739. var result = unit(cm, pos);
  6740. return new Range(result.from, result.to)
  6741. }
  6742. // Normal selection, as opposed to text dragging.
  6743. function leftButtonSelect(cm, event, start, behavior) {
  6744. if (ie) { delayBlurEvent(cm); }
  6745. var display = cm.display, doc = cm.doc;
  6746. e_preventDefault(event);
  6747. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6748. if (behavior.addNew && !behavior.extend) {
  6749. ourIndex = doc.sel.contains(start);
  6750. if (ourIndex > -1)
  6751. { ourRange = ranges[ourIndex]; }
  6752. else
  6753. { ourRange = new Range(start, start); }
  6754. } else {
  6755. ourRange = doc.sel.primary();
  6756. ourIndex = doc.sel.primIndex;
  6757. }
  6758. if (behavior.unit == "rectangle") {
  6759. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6760. start = posFromMouse(cm, event, true, true);
  6761. ourIndex = -1;
  6762. } else {
  6763. var range = rangeForUnit(cm, start, behavior.unit);
  6764. if (behavior.extend)
  6765. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  6766. else
  6767. { ourRange = range; }
  6768. }
  6769. if (!behavior.addNew) {
  6770. ourIndex = 0;
  6771. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6772. startSel = doc.sel;
  6773. } else if (ourIndex == -1) {
  6774. ourIndex = ranges.length;
  6775. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  6776. {scroll: false, origin: "*mouse"});
  6777. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6778. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6779. {scroll: false, origin: "*mouse"});
  6780. startSel = doc.sel;
  6781. } else {
  6782. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6783. }
  6784. var lastPos = start;
  6785. function extendTo(pos) {
  6786. if (cmp(lastPos, pos) == 0) { return }
  6787. lastPos = pos;
  6788. if (behavior.unit == "rectangle") {
  6789. var ranges = [], tabSize = cm.options.tabSize;
  6790. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6791. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6792. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6793. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6794. line <= end; line++) {
  6795. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6796. if (left == right)
  6797. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6798. else if (text.length > leftPos)
  6799. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6800. }
  6801. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6802. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6803. {origin: "*mouse", scroll: false});
  6804. cm.scrollIntoView(pos);
  6805. } else {
  6806. var oldRange = ourRange;
  6807. var range = rangeForUnit(cm, pos, behavior.unit);
  6808. var anchor = oldRange.anchor, head;
  6809. if (cmp(range.anchor, anchor) > 0) {
  6810. head = range.head;
  6811. anchor = minPos(oldRange.from(), range.anchor);
  6812. } else {
  6813. head = range.anchor;
  6814. anchor = maxPos(oldRange.to(), range.head);
  6815. }
  6816. var ranges$1 = startSel.ranges.slice(0);
  6817. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  6818. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  6819. }
  6820. }
  6821. var editorSize = display.wrapper.getBoundingClientRect();
  6822. // Used to ensure timeout re-tries don't fire when another extend
  6823. // happened in the meantime (clearTimeout isn't reliable -- at
  6824. // least on Chrome, the timeouts still happen even when cleared,
  6825. // if the clear happens after their scheduled firing time).
  6826. var counter = 0;
  6827. function extend(e) {
  6828. var curCount = ++counter;
  6829. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6830. if (!cur) { return }
  6831. if (cmp(cur, lastPos) != 0) {
  6832. cm.curOp.focus = activeElt();
  6833. extendTo(cur);
  6834. var visible = visibleLines(display, doc);
  6835. if (cur.line >= visible.to || cur.line < visible.from)
  6836. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6837. } else {
  6838. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6839. if (outside) { setTimeout(operation(cm, function () {
  6840. if (counter != curCount) { return }
  6841. display.scroller.scrollTop += outside;
  6842. extend(e);
  6843. }), 50); }
  6844. }
  6845. }
  6846. function done(e) {
  6847. cm.state.selectingText = false;
  6848. counter = Infinity;
  6849. // If e is null or undefined we interpret this as someone trying
  6850. // to explicitly cancel the selection rather than the user
  6851. // letting go of the mouse button.
  6852. if (e) {
  6853. e_preventDefault(e);
  6854. display.input.focus();
  6855. }
  6856. off(display.wrapper.ownerDocument, "mousemove", move);
  6857. off(display.wrapper.ownerDocument, "mouseup", up);
  6858. doc.history.lastSelOrigin = null;
  6859. }
  6860. var move = operation(cm, function (e) {
  6861. if (e.buttons === 0 || !e_button(e)) { done(e); }
  6862. else { extend(e); }
  6863. });
  6864. var up = operation(cm, done);
  6865. cm.state.selectingText = up;
  6866. on(display.wrapper.ownerDocument, "mousemove", move);
  6867. on(display.wrapper.ownerDocument, "mouseup", up);
  6868. }
  6869. // Used when mouse-selecting to adjust the anchor to the proper side
  6870. // of a bidi jump depending on the visual position of the head.
  6871. function bidiSimplify(cm, range) {
  6872. var anchor = range.anchor;
  6873. var head = range.head;
  6874. var anchorLine = getLine(cm.doc, anchor.line);
  6875. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6876. var order = getOrder(anchorLine);
  6877. if (!order) { return range }
  6878. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6879. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6880. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6881. if (boundary == 0 || boundary == order.length) { return range }
  6882. // Compute the relative visual position of the head compared to the
  6883. // anchor (<0 is to the left, >0 to the right)
  6884. var leftSide;
  6885. if (head.line != anchor.line) {
  6886. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6887. } else {
  6888. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6889. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6890. if (headIndex == boundary - 1 || headIndex == boundary)
  6891. { leftSide = dir < 0; }
  6892. else
  6893. { leftSide = dir > 0; }
  6894. }
  6895. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6896. var from = leftSide == (usePart.level == 1);
  6897. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6898. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6899. }
  6900. // Determines whether an event happened in the gutter, and fires the
  6901. // handlers for the corresponding event.
  6902. function gutterEvent(cm, e, type, prevent) {
  6903. var mX, mY;
  6904. if (e.touches) {
  6905. mX = e.touches[0].clientX;
  6906. mY = e.touches[0].clientY;
  6907. } else {
  6908. try { mX = e.clientX; mY = e.clientY; }
  6909. catch(e$1) { return false }
  6910. }
  6911. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6912. if (prevent) { e_preventDefault(e); }
  6913. var display = cm.display;
  6914. var lineBox = display.lineDiv.getBoundingClientRect();
  6915. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6916. mY -= lineBox.top - display.viewOffset;
  6917. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  6918. var g = display.gutters.childNodes[i];
  6919. if (g && g.getBoundingClientRect().right >= mX) {
  6920. var line = lineAtHeight(cm.doc, mY);
  6921. var gutter = cm.display.gutterSpecs[i];
  6922. signal(cm, type, cm, line, gutter.className, e);
  6923. return e_defaultPrevented(e)
  6924. }
  6925. }
  6926. }
  6927. function clickInGutter(cm, e) {
  6928. return gutterEvent(cm, e, "gutterClick", true)
  6929. }
  6930. // CONTEXT MENU HANDLING
  6931. // To make the context menu work, we need to briefly unhide the
  6932. // textarea (making it as unobtrusive as possible) to let the
  6933. // right-click take effect on it.
  6934. function onContextMenu(cm, e) {
  6935. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6936. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6937. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  6938. }
  6939. function contextMenuInGutter(cm, e) {
  6940. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6941. return gutterEvent(cm, e, "gutterContextMenu", false)
  6942. }
  6943. function themeChanged(cm) {
  6944. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6945. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6946. clearCaches(cm);
  6947. }
  6948. var Init = {toString: function(){return "CodeMirror.Init"}};
  6949. var defaults = {};
  6950. var optionHandlers = {};
  6951. function defineOptions(CodeMirror) {
  6952. var optionHandlers = CodeMirror.optionHandlers;
  6953. function option(name, deflt, handle, notOnInit) {
  6954. CodeMirror.defaults[name] = deflt;
  6955. if (handle) { optionHandlers[name] =
  6956. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  6957. }
  6958. CodeMirror.defineOption = option;
  6959. // Passed to option handlers when there is no old value.
  6960. CodeMirror.Init = Init;
  6961. // These two are, on init, called from the constructor because they
  6962. // have to be initialized before the editor can start at all.
  6963. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  6964. option("mode", null, function (cm, val) {
  6965. cm.doc.modeOption = val;
  6966. loadMode(cm);
  6967. }, true);
  6968. option("indentUnit", 2, loadMode, true);
  6969. option("indentWithTabs", false);
  6970. option("smartIndent", true);
  6971. option("tabSize", 4, function (cm) {
  6972. resetModeState(cm);
  6973. clearCaches(cm);
  6974. regChange(cm);
  6975. }, true);
  6976. option("lineSeparator", null, function (cm, val) {
  6977. cm.doc.lineSep = val;
  6978. if (!val) { return }
  6979. var newBreaks = [], lineNo = cm.doc.first;
  6980. cm.doc.iter(function (line) {
  6981. for (var pos = 0;;) {
  6982. var found = line.text.indexOf(val, pos);
  6983. if (found == -1) { break }
  6984. pos = found + val.length;
  6985. newBreaks.push(Pos(lineNo, found));
  6986. }
  6987. lineNo++;
  6988. });
  6989. for (var i = newBreaks.length - 1; i >= 0; i--)
  6990. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  6991. });
  6992. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  6993. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6994. if (old != Init) { cm.refresh(); }
  6995. });
  6996. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  6997. option("electricChars", true);
  6998. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6999. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  7000. }, true);
  7001. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  7002. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  7003. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  7004. option("rtlMoveVisually", !windows);
  7005. option("wholeLineUpdateBefore", true);
  7006. option("theme", "default", function (cm) {
  7007. themeChanged(cm);
  7008. updateGutters(cm);
  7009. }, true);
  7010. option("keyMap", "default", function (cm, val, old) {
  7011. var next = getKeyMap(val);
  7012. var prev = old != Init && getKeyMap(old);
  7013. if (prev && prev.detach) { prev.detach(cm, next); }
  7014. if (next.attach) { next.attach(cm, prev || null); }
  7015. });
  7016. option("extraKeys", null);
  7017. option("configureMouse", null);
  7018. option("lineWrapping", false, wrappingChanged, true);
  7019. option("gutters", [], function (cm, val) {
  7020. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7021. updateGutters(cm);
  7022. }, true);
  7023. option("fixedGutter", true, function (cm, val) {
  7024. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7025. cm.refresh();
  7026. }, true);
  7027. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7028. option("scrollbarStyle", "native", function (cm) {
  7029. initScrollbars(cm);
  7030. updateScrollbars(cm);
  7031. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7032. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7033. }, true);
  7034. option("lineNumbers", false, function (cm, val) {
  7035. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7036. updateGutters(cm);
  7037. }, true);
  7038. option("firstLineNumber", 1, updateGutters, true);
  7039. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7040. option("showCursorWhenSelecting", false, updateSelection, true);
  7041. option("resetSelectionOnContextMenu", true);
  7042. option("lineWiseCopyCut", true);
  7043. option("pasteLinesPerSelection", true);
  7044. option("selectionsMayTouch", false);
  7045. option("readOnly", false, function (cm, val) {
  7046. if (val == "nocursor") {
  7047. onBlur(cm);
  7048. cm.display.input.blur();
  7049. }
  7050. cm.display.input.readOnlyChanged(val);
  7051. });
  7052. option("screenReaderLabel", null, function (cm, val) {
  7053. val = (val === '') ? null : val;
  7054. cm.display.input.screenReaderLabelChanged(val);
  7055. });
  7056. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7057. option("dragDrop", true, dragDropChanged);
  7058. option("allowDropFileTypes", null);
  7059. option("cursorBlinkRate", 530);
  7060. option("cursorScrollMargin", 0);
  7061. option("cursorHeight", 1, updateSelection, true);
  7062. option("singleCursorHeightPerLine", true, updateSelection, true);
  7063. option("workTime", 100);
  7064. option("workDelay", 100);
  7065. option("flattenSpans", true, resetModeState, true);
  7066. option("addModeClass", false, resetModeState, true);
  7067. option("pollInterval", 100);
  7068. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7069. option("historyEventDelay", 1250);
  7070. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7071. option("maxHighlightLength", 10000, resetModeState, true);
  7072. option("moveInputWithCursor", true, function (cm, val) {
  7073. if (!val) { cm.display.input.resetPosition(); }
  7074. });
  7075. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7076. option("autofocus", null);
  7077. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7078. option("phrases", null);
  7079. }
  7080. function dragDropChanged(cm, value, old) {
  7081. var wasOn = old && old != Init;
  7082. if (!value != !wasOn) {
  7083. var funcs = cm.display.dragFunctions;
  7084. var toggle = value ? on : off;
  7085. toggle(cm.display.scroller, "dragstart", funcs.start);
  7086. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7087. toggle(cm.display.scroller, "dragover", funcs.over);
  7088. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7089. toggle(cm.display.scroller, "drop", funcs.drop);
  7090. }
  7091. }
  7092. function wrappingChanged(cm) {
  7093. if (cm.options.lineWrapping) {
  7094. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7095. cm.display.sizer.style.minWidth = "";
  7096. cm.display.sizerWidth = null;
  7097. } else {
  7098. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7099. findMaxLine(cm);
  7100. }
  7101. estimateLineHeights(cm);
  7102. regChange(cm);
  7103. clearCaches(cm);
  7104. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7105. }
  7106. // A CodeMirror instance represents an editor. This is the object
  7107. // that user code is usually dealing with.
  7108. function CodeMirror(place, options) {
  7109. var this$1 = this;
  7110. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7111. this.options = options = options ? copyObj(options) : {};
  7112. // Determine effective options based on given values and defaults.
  7113. copyObj(defaults, options, false);
  7114. var doc = options.value;
  7115. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7116. else if (options.mode) { doc.modeOption = options.mode; }
  7117. this.doc = doc;
  7118. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7119. var display = this.display = new Display(place, doc, input, options);
  7120. display.wrapper.CodeMirror = this;
  7121. themeChanged(this);
  7122. if (options.lineWrapping)
  7123. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7124. initScrollbars(this);
  7125. this.state = {
  7126. keyMaps: [], // stores maps added by addKeyMap
  7127. overlays: [], // highlighting overlays, as added by addOverlay
  7128. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7129. overwrite: false,
  7130. delayingBlurEvent: false,
  7131. focused: false,
  7132. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7133. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7134. selectingText: false,
  7135. draggingText: false,
  7136. highlight: new Delayed(), // stores highlight worker timeout
  7137. keySeq: null, // Unfinished key sequence
  7138. specialChars: null
  7139. };
  7140. if (options.autofocus && !mobile) { display.input.focus(); }
  7141. // Override magic textarea content restore that IE sometimes does
  7142. // on our hidden textarea on reload
  7143. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7144. registerEventHandlers(this);
  7145. ensureGlobalHandlers();
  7146. startOperation(this);
  7147. this.curOp.forceUpdate = true;
  7148. attachDoc(this, doc);
  7149. if ((options.autofocus && !mobile) || this.hasFocus())
  7150. { setTimeout(function () {
  7151. if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  7152. }, 20); }
  7153. else
  7154. { onBlur(this); }
  7155. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7156. { optionHandlers[opt](this, options[opt], Init); } }
  7157. maybeUpdateLineNumberWidth(this);
  7158. if (options.finishInit) { options.finishInit(this); }
  7159. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7160. endOperation(this);
  7161. // Suppress optimizelegibility in Webkit, since it breaks text
  7162. // measuring on line wrapping boundaries.
  7163. if (webkit && options.lineWrapping &&
  7164. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7165. { display.lineDiv.style.textRendering = "auto"; }
  7166. }
  7167. // The default configuration options.
  7168. CodeMirror.defaults = defaults;
  7169. // Functions to run when options are changed.
  7170. CodeMirror.optionHandlers = optionHandlers;
  7171. // Attach the necessary event handlers when initializing the editor
  7172. function registerEventHandlers(cm) {
  7173. var d = cm.display;
  7174. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7175. // Older IE's will not fire a second mousedown for a double click
  7176. if (ie && ie_version < 11)
  7177. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7178. if (signalDOMEvent(cm, e)) { return }
  7179. var pos = posFromMouse(cm, e);
  7180. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7181. e_preventDefault(e);
  7182. var word = cm.findWordAt(pos);
  7183. extendSelection(cm.doc, word.anchor, word.head);
  7184. })); }
  7185. else
  7186. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7187. // Some browsers fire contextmenu *after* opening the menu, at
  7188. // which point we can't mess with it anymore. Context menu is
  7189. // handled in onMouseDown for these browsers.
  7190. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7191. on(d.input.getField(), "contextmenu", function (e) {
  7192. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7193. });
  7194. // Used to suppress mouse event handling when a touch happens
  7195. var touchFinished, prevTouch = {end: 0};
  7196. function finishTouch() {
  7197. if (d.activeTouch) {
  7198. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7199. prevTouch = d.activeTouch;
  7200. prevTouch.end = +new Date;
  7201. }
  7202. }
  7203. function isMouseLikeTouchEvent(e) {
  7204. if (e.touches.length != 1) { return false }
  7205. var touch = e.touches[0];
  7206. return touch.radiusX <= 1 && touch.radiusY <= 1
  7207. }
  7208. function farAway(touch, other) {
  7209. if (other.left == null) { return true }
  7210. var dx = other.left - touch.left, dy = other.top - touch.top;
  7211. return dx * dx + dy * dy > 20 * 20
  7212. }
  7213. on(d.scroller, "touchstart", function (e) {
  7214. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7215. d.input.ensurePolled();
  7216. clearTimeout(touchFinished);
  7217. var now = +new Date;
  7218. d.activeTouch = {start: now, moved: false,
  7219. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7220. if (e.touches.length == 1) {
  7221. d.activeTouch.left = e.touches[0].pageX;
  7222. d.activeTouch.top = e.touches[0].pageY;
  7223. }
  7224. }
  7225. });
  7226. on(d.scroller, "touchmove", function () {
  7227. if (d.activeTouch) { d.activeTouch.moved = true; }
  7228. });
  7229. on(d.scroller, "touchend", function (e) {
  7230. var touch = d.activeTouch;
  7231. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7232. !touch.moved && new Date - touch.start < 300) {
  7233. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7234. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7235. { range = new Range(pos, pos); }
  7236. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7237. { range = cm.findWordAt(pos); }
  7238. else // Triple tap
  7239. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7240. cm.setSelection(range.anchor, range.head);
  7241. cm.focus();
  7242. e_preventDefault(e);
  7243. }
  7244. finishTouch();
  7245. });
  7246. on(d.scroller, "touchcancel", finishTouch);
  7247. // Sync scrolling between fake scrollbars and real scrollable
  7248. // area, ensure viewport is updated when scrolling.
  7249. on(d.scroller, "scroll", function () {
  7250. if (d.scroller.clientHeight) {
  7251. updateScrollTop(cm, d.scroller.scrollTop);
  7252. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7253. signal(cm, "scroll", cm);
  7254. }
  7255. });
  7256. // Listen to wheel events in order to try and update the viewport on time.
  7257. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7258. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7259. // Prevent wrapper from ever scrolling
  7260. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7261. d.dragFunctions = {
  7262. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7263. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7264. start: function (e) { return onDragStart(cm, e); },
  7265. drop: operation(cm, onDrop),
  7266. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7267. };
  7268. var inp = d.input.getField();
  7269. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7270. on(inp, "keydown", operation(cm, onKeyDown));
  7271. on(inp, "keypress", operation(cm, onKeyPress));
  7272. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7273. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7274. }
  7275. var initHooks = [];
  7276. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7277. // Indent the given line. The how parameter can be "smart",
  7278. // "add"/null, "subtract", or "prev". When aggressive is false
  7279. // (typically set to true for forced single-line indents), empty
  7280. // lines are not indented, and places where the mode returns Pass
  7281. // are left alone.
  7282. function indentLine(cm, n, how, aggressive) {
  7283. var doc = cm.doc, state;
  7284. if (how == null) { how = "add"; }
  7285. if (how == "smart") {
  7286. // Fall back to "prev" when the mode doesn't have an indentation
  7287. // method.
  7288. if (!doc.mode.indent) { how = "prev"; }
  7289. else { state = getContextBefore(cm, n).state; }
  7290. }
  7291. var tabSize = cm.options.tabSize;
  7292. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7293. if (line.stateAfter) { line.stateAfter = null; }
  7294. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7295. if (!aggressive && !/\S/.test(line.text)) {
  7296. indentation = 0;
  7297. how = "not";
  7298. } else if (how == "smart") {
  7299. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7300. if (indentation == Pass || indentation > 150) {
  7301. if (!aggressive) { return }
  7302. how = "prev";
  7303. }
  7304. }
  7305. if (how == "prev") {
  7306. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7307. else { indentation = 0; }
  7308. } else if (how == "add") {
  7309. indentation = curSpace + cm.options.indentUnit;
  7310. } else if (how == "subtract") {
  7311. indentation = curSpace - cm.options.indentUnit;
  7312. } else if (typeof how == "number") {
  7313. indentation = curSpace + how;
  7314. }
  7315. indentation = Math.max(0, indentation);
  7316. var indentString = "", pos = 0;
  7317. if (cm.options.indentWithTabs)
  7318. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7319. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7320. if (indentString != curSpaceString) {
  7321. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7322. line.stateAfter = null;
  7323. return true
  7324. } else {
  7325. // Ensure that, if the cursor was in the whitespace at the start
  7326. // of the line, it is moved to the end of that space.
  7327. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7328. var range = doc.sel.ranges[i$1];
  7329. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7330. var pos$1 = Pos(n, curSpaceString.length);
  7331. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7332. break
  7333. }
  7334. }
  7335. }
  7336. }
  7337. // This will be set to a {lineWise: bool, text: [string]} object, so
  7338. // that, when pasting, we know what kind of selections the copied
  7339. // text was made out of.
  7340. var lastCopied = null;
  7341. function setLastCopied(newLastCopied) {
  7342. lastCopied = newLastCopied;
  7343. }
  7344. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7345. var doc = cm.doc;
  7346. cm.display.shift = false;
  7347. if (!sel) { sel = doc.sel; }
  7348. var recent = +new Date - 200;
  7349. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7350. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7351. // When pasting N lines into N selections, insert one line per selection
  7352. if (paste && sel.ranges.length > 1) {
  7353. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7354. if (sel.ranges.length % lastCopied.text.length == 0) {
  7355. multiPaste = [];
  7356. for (var i = 0; i < lastCopied.text.length; i++)
  7357. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7358. }
  7359. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7360. multiPaste = map(textLines, function (l) { return [l]; });
  7361. }
  7362. }
  7363. var updateInput = cm.curOp.updateInput;
  7364. // Normal behavior is to insert the new text into every selection
  7365. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7366. var range = sel.ranges[i$1];
  7367. var from = range.from(), to = range.to();
  7368. if (range.empty()) {
  7369. if (deleted && deleted > 0) // Handle deletion
  7370. { from = Pos(from.line, from.ch - deleted); }
  7371. else if (cm.state.overwrite && !paste) // Handle overwrite
  7372. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7373. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  7374. { from = to = Pos(from.line, 0); }
  7375. }
  7376. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7377. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  7378. makeChange(cm.doc, changeEvent);
  7379. signalLater(cm, "inputRead", cm, changeEvent);
  7380. }
  7381. if (inserted && !paste)
  7382. { triggerElectric(cm, inserted); }
  7383. ensureCursorVisible(cm);
  7384. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7385. cm.curOp.typing = true;
  7386. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7387. }
  7388. function handlePaste(e, cm) {
  7389. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7390. if (pasted) {
  7391. e.preventDefault();
  7392. if (!cm.isReadOnly() && !cm.options.disableInput)
  7393. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7394. return true
  7395. }
  7396. }
  7397. function triggerElectric(cm, inserted) {
  7398. // When an 'electric' character is inserted, immediately trigger a reindent
  7399. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7400. var sel = cm.doc.sel;
  7401. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7402. var range = sel.ranges[i];
  7403. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7404. var mode = cm.getModeAt(range.head);
  7405. var indented = false;
  7406. if (mode.electricChars) {
  7407. for (var j = 0; j < mode.electricChars.length; j++)
  7408. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7409. indented = indentLine(cm, range.head.line, "smart");
  7410. break
  7411. } }
  7412. } else if (mode.electricInput) {
  7413. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7414. { indented = indentLine(cm, range.head.line, "smart"); }
  7415. }
  7416. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  7417. }
  7418. }
  7419. function copyableRanges(cm) {
  7420. var text = [], ranges = [];
  7421. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7422. var line = cm.doc.sel.ranges[i].head.line;
  7423. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7424. ranges.push(lineRange);
  7425. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7426. }
  7427. return {text: text, ranges: ranges}
  7428. }
  7429. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7430. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  7431. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  7432. field.setAttribute("spellcheck", !!spellcheck);
  7433. }
  7434. function hiddenTextarea() {
  7435. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  7436. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7437. // The textarea is kept positioned near the cursor to prevent the
  7438. // fact that it'll be scrolled into view on input from scrolling
  7439. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7440. // very slow. So make the area wide instead.
  7441. if (webkit) { te.style.width = "1000px"; }
  7442. else { te.setAttribute("wrap", "off"); }
  7443. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7444. if (ios) { te.style.border = "1px solid black"; }
  7445. disableBrowserMagic(te);
  7446. return div
  7447. }
  7448. // The publicly visible API. Note that methodOp(f) means
  7449. // 'wrap f in an operation, performed on its `this` parameter'.
  7450. // This is not the complete set of editor methods. Most of the
  7451. // methods defined on the Doc type are also injected into
  7452. // CodeMirror.prototype, for backwards compatibility and
  7453. // convenience.
  7454. function addEditorMethods(CodeMirror) {
  7455. var optionHandlers = CodeMirror.optionHandlers;
  7456. var helpers = CodeMirror.helpers = {};
  7457. CodeMirror.prototype = {
  7458. constructor: CodeMirror,
  7459. focus: function(){window.focus(); this.display.input.focus();},
  7460. setOption: function(option, value) {
  7461. var options = this.options, old = options[option];
  7462. if (options[option] == value && option != "mode") { return }
  7463. options[option] = value;
  7464. if (optionHandlers.hasOwnProperty(option))
  7465. { operation(this, optionHandlers[option])(this, value, old); }
  7466. signal(this, "optionChange", this, option);
  7467. },
  7468. getOption: function(option) {return this.options[option]},
  7469. getDoc: function() {return this.doc},
  7470. addKeyMap: function(map, bottom) {
  7471. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  7472. },
  7473. removeKeyMap: function(map) {
  7474. var maps = this.state.keyMaps;
  7475. for (var i = 0; i < maps.length; ++i)
  7476. { if (maps[i] == map || maps[i].name == map) {
  7477. maps.splice(i, 1);
  7478. return true
  7479. } }
  7480. },
  7481. addOverlay: methodOp(function(spec, options) {
  7482. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7483. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7484. insertSorted(this.state.overlays,
  7485. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7486. priority: (options && options.priority) || 0},
  7487. function (overlay) { return overlay.priority; });
  7488. this.state.modeGen++;
  7489. regChange(this);
  7490. }),
  7491. removeOverlay: methodOp(function(spec) {
  7492. var overlays = this.state.overlays;
  7493. for (var i = 0; i < overlays.length; ++i) {
  7494. var cur = overlays[i].modeSpec;
  7495. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7496. overlays.splice(i, 1);
  7497. this.state.modeGen++;
  7498. regChange(this);
  7499. return
  7500. }
  7501. }
  7502. }),
  7503. indentLine: methodOp(function(n, dir, aggressive) {
  7504. if (typeof dir != "string" && typeof dir != "number") {
  7505. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7506. else { dir = dir ? "add" : "subtract"; }
  7507. }
  7508. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7509. }),
  7510. indentSelection: methodOp(function(how) {
  7511. var ranges = this.doc.sel.ranges, end = -1;
  7512. for (var i = 0; i < ranges.length; i++) {
  7513. var range = ranges[i];
  7514. if (!range.empty()) {
  7515. var from = range.from(), to = range.to();
  7516. var start = Math.max(end, from.line);
  7517. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7518. for (var j = start; j < end; ++j)
  7519. { indentLine(this, j, how); }
  7520. var newRanges = this.doc.sel.ranges;
  7521. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7522. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7523. } else if (range.head.line > end) {
  7524. indentLine(this, range.head.line, how, true);
  7525. end = range.head.line;
  7526. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  7527. }
  7528. }
  7529. }),
  7530. // Fetch the parser token for a given character. Useful for hacks
  7531. // that want to inspect the mode state (say, for completion).
  7532. getTokenAt: function(pos, precise) {
  7533. return takeToken(this, pos, precise)
  7534. },
  7535. getLineTokens: function(line, precise) {
  7536. return takeToken(this, Pos(line), precise, true)
  7537. },
  7538. getTokenTypeAt: function(pos) {
  7539. pos = clipPos(this.doc, pos);
  7540. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7541. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7542. var type;
  7543. if (ch == 0) { type = styles[2]; }
  7544. else { for (;;) {
  7545. var mid = (before + after) >> 1;
  7546. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7547. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7548. else { type = styles[mid * 2 + 2]; break }
  7549. } }
  7550. var cut = type ? type.indexOf("overlay ") : -1;
  7551. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7552. },
  7553. getModeAt: function(pos) {
  7554. var mode = this.doc.mode;
  7555. if (!mode.innerMode) { return mode }
  7556. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7557. },
  7558. getHelper: function(pos, type) {
  7559. return this.getHelpers(pos, type)[0]
  7560. },
  7561. getHelpers: function(pos, type) {
  7562. var found = [];
  7563. if (!helpers.hasOwnProperty(type)) { return found }
  7564. var help = helpers[type], mode = this.getModeAt(pos);
  7565. if (typeof mode[type] == "string") {
  7566. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7567. } else if (mode[type]) {
  7568. for (var i = 0; i < mode[type].length; i++) {
  7569. var val = help[mode[type][i]];
  7570. if (val) { found.push(val); }
  7571. }
  7572. } else if (mode.helperType && help[mode.helperType]) {
  7573. found.push(help[mode.helperType]);
  7574. } else if (help[mode.name]) {
  7575. found.push(help[mode.name]);
  7576. }
  7577. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7578. var cur = help._global[i$1];
  7579. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  7580. { found.push(cur.val); }
  7581. }
  7582. return found
  7583. },
  7584. getStateAfter: function(line, precise) {
  7585. var doc = this.doc;
  7586. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7587. return getContextBefore(this, line + 1, precise).state
  7588. },
  7589. cursorCoords: function(start, mode) {
  7590. var pos, range = this.doc.sel.primary();
  7591. if (start == null) { pos = range.head; }
  7592. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7593. else { pos = start ? range.from() : range.to(); }
  7594. return cursorCoords(this, pos, mode || "page")
  7595. },
  7596. charCoords: function(pos, mode) {
  7597. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7598. },
  7599. coordsChar: function(coords, mode) {
  7600. coords = fromCoordSystem(this, coords, mode || "page");
  7601. return coordsChar(this, coords.left, coords.top)
  7602. },
  7603. lineAtHeight: function(height, mode) {
  7604. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7605. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7606. },
  7607. heightAtLine: function(line, mode, includeWidgets) {
  7608. var end = false, lineObj;
  7609. if (typeof line == "number") {
  7610. var last = this.doc.first + this.doc.size - 1;
  7611. if (line < this.doc.first) { line = this.doc.first; }
  7612. else if (line > last) { line = last; end = true; }
  7613. lineObj = getLine(this.doc, line);
  7614. } else {
  7615. lineObj = line;
  7616. }
  7617. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7618. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7619. },
  7620. defaultTextHeight: function() { return textHeight(this.display) },
  7621. defaultCharWidth: function() { return charWidth(this.display) },
  7622. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7623. addWidget: function(pos, node, scroll, vert, horiz) {
  7624. var display = this.display;
  7625. pos = cursorCoords(this, clipPos(this.doc, pos));
  7626. var top = pos.bottom, left = pos.left;
  7627. node.style.position = "absolute";
  7628. node.setAttribute("cm-ignore-events", "true");
  7629. this.display.input.setUneditable(node);
  7630. display.sizer.appendChild(node);
  7631. if (vert == "over") {
  7632. top = pos.top;
  7633. } else if (vert == "above" || vert == "near") {
  7634. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7635. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7636. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7637. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7638. { top = pos.top - node.offsetHeight; }
  7639. else if (pos.bottom + node.offsetHeight <= vspace)
  7640. { top = pos.bottom; }
  7641. if (left + node.offsetWidth > hspace)
  7642. { left = hspace - node.offsetWidth; }
  7643. }
  7644. node.style.top = top + "px";
  7645. node.style.left = node.style.right = "";
  7646. if (horiz == "right") {
  7647. left = display.sizer.clientWidth - node.offsetWidth;
  7648. node.style.right = "0px";
  7649. } else {
  7650. if (horiz == "left") { left = 0; }
  7651. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7652. node.style.left = left + "px";
  7653. }
  7654. if (scroll)
  7655. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7656. },
  7657. triggerOnKeyDown: methodOp(onKeyDown),
  7658. triggerOnKeyPress: methodOp(onKeyPress),
  7659. triggerOnKeyUp: onKeyUp,
  7660. triggerOnMouseDown: methodOp(onMouseDown),
  7661. execCommand: function(cmd) {
  7662. if (commands.hasOwnProperty(cmd))
  7663. { return commands[cmd].call(null, this) }
  7664. },
  7665. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7666. findPosH: function(from, amount, unit, visually) {
  7667. var dir = 1;
  7668. if (amount < 0) { dir = -1; amount = -amount; }
  7669. var cur = clipPos(this.doc, from);
  7670. for (var i = 0; i < amount; ++i) {
  7671. cur = findPosH(this.doc, cur, dir, unit, visually);
  7672. if (cur.hitSide) { break }
  7673. }
  7674. return cur
  7675. },
  7676. moveH: methodOp(function(dir, unit) {
  7677. var this$1 = this;
  7678. this.extendSelectionsBy(function (range) {
  7679. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7680. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7681. else
  7682. { return dir < 0 ? range.from() : range.to() }
  7683. }, sel_move);
  7684. }),
  7685. deleteH: methodOp(function(dir, unit) {
  7686. var sel = this.doc.sel, doc = this.doc;
  7687. if (sel.somethingSelected())
  7688. { doc.replaceSelection("", null, "+delete"); }
  7689. else
  7690. { deleteNearSelection(this, function (range) {
  7691. var other = findPosH(doc, range.head, dir, unit, false);
  7692. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7693. }); }
  7694. }),
  7695. findPosV: function(from, amount, unit, goalColumn) {
  7696. var dir = 1, x = goalColumn;
  7697. if (amount < 0) { dir = -1; amount = -amount; }
  7698. var cur = clipPos(this.doc, from);
  7699. for (var i = 0; i < amount; ++i) {
  7700. var coords = cursorCoords(this, cur, "div");
  7701. if (x == null) { x = coords.left; }
  7702. else { coords.left = x; }
  7703. cur = findPosV(this, coords, dir, unit);
  7704. if (cur.hitSide) { break }
  7705. }
  7706. return cur
  7707. },
  7708. moveV: methodOp(function(dir, unit) {
  7709. var this$1 = this;
  7710. var doc = this.doc, goals = [];
  7711. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7712. doc.extendSelectionsBy(function (range) {
  7713. if (collapse)
  7714. { return dir < 0 ? range.from() : range.to() }
  7715. var headPos = cursorCoords(this$1, range.head, "div");
  7716. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  7717. goals.push(headPos.left);
  7718. var pos = findPosV(this$1, headPos, dir, unit);
  7719. if (unit == "page" && range == doc.sel.primary())
  7720. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7721. return pos
  7722. }, sel_move);
  7723. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7724. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7725. }),
  7726. // Find the word at the given position (as returned by coordsChar).
  7727. findWordAt: function(pos) {
  7728. var doc = this.doc, line = getLine(doc, pos.line).text;
  7729. var start = pos.ch, end = pos.ch;
  7730. if (line) {
  7731. var helper = this.getHelper(pos, "wordChars");
  7732. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7733. var startChar = line.charAt(start);
  7734. var check = isWordChar(startChar, helper)
  7735. ? function (ch) { return isWordChar(ch, helper); }
  7736. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7737. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7738. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7739. while (end < line.length && check(line.charAt(end))) { ++end; }
  7740. }
  7741. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7742. },
  7743. toggleOverwrite: function(value) {
  7744. if (value != null && value == this.state.overwrite) { return }
  7745. if (this.state.overwrite = !this.state.overwrite)
  7746. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7747. else
  7748. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7749. signal(this, "overwriteToggle", this, this.state.overwrite);
  7750. },
  7751. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7752. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7753. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7754. getScrollInfo: function() {
  7755. var scroller = this.display.scroller;
  7756. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7757. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7758. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7759. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7760. },
  7761. scrollIntoView: methodOp(function(range, margin) {
  7762. if (range == null) {
  7763. range = {from: this.doc.sel.primary().head, to: null};
  7764. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7765. } else if (typeof range == "number") {
  7766. range = {from: Pos(range, 0), to: null};
  7767. } else if (range.from == null) {
  7768. range = {from: range, to: null};
  7769. }
  7770. if (!range.to) { range.to = range.from; }
  7771. range.margin = margin || 0;
  7772. if (range.from.line != null) {
  7773. scrollToRange(this, range);
  7774. } else {
  7775. scrollToCoordsRange(this, range.from, range.to, range.margin);
  7776. }
  7777. }),
  7778. setSize: methodOp(function(width, height) {
  7779. var this$1 = this;
  7780. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7781. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7782. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7783. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7784. var lineNo = this.display.viewFrom;
  7785. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7786. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7787. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7788. ++lineNo;
  7789. });
  7790. this.curOp.forceUpdate = true;
  7791. signal(this, "refresh", this);
  7792. }),
  7793. operation: function(f){return runInOp(this, f)},
  7794. startOperation: function(){return startOperation(this)},
  7795. endOperation: function(){return endOperation(this)},
  7796. refresh: methodOp(function() {
  7797. var oldHeight = this.display.cachedTextHeight;
  7798. regChange(this);
  7799. this.curOp.forceUpdate = true;
  7800. clearCaches(this);
  7801. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7802. updateGutterSpace(this.display);
  7803. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  7804. { estimateLineHeights(this); }
  7805. signal(this, "refresh", this);
  7806. }),
  7807. swapDoc: methodOp(function(doc) {
  7808. var old = this.doc;
  7809. old.cm = null;
  7810. // Cancel the current text selection if any (#5821)
  7811. if (this.state.selectingText) { this.state.selectingText(); }
  7812. attachDoc(this, doc);
  7813. clearCaches(this);
  7814. this.display.input.reset();
  7815. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7816. this.curOp.forceScroll = true;
  7817. signalLater(this, "swapDoc", this, old);
  7818. return old
  7819. }),
  7820. phrase: function(phraseText) {
  7821. var phrases = this.options.phrases;
  7822. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7823. },
  7824. getInputField: function(){return this.display.input.getField()},
  7825. getWrapperElement: function(){return this.display.wrapper},
  7826. getScrollerElement: function(){return this.display.scroller},
  7827. getGutterElement: function(){return this.display.gutters}
  7828. };
  7829. eventMixin(CodeMirror);
  7830. CodeMirror.registerHelper = function(type, name, value) {
  7831. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7832. helpers[type][name] = value;
  7833. };
  7834. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7835. CodeMirror.registerHelper(type, name, value);
  7836. helpers[type]._global.push({pred: predicate, val: value});
  7837. };
  7838. }
  7839. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7840. // right), unit can be "codepoint", "char", "column" (like char, but
  7841. // doesn't cross line boundaries), "word" (across next word), or
  7842. // "group" (to the start of next group of word or
  7843. // non-word-non-whitespace chars). The visually param controls
  7844. // whether, in right-to-left text, direction 1 means to move towards
  7845. // the next index in the string, or towards the character to the right
  7846. // of the current position. The resulting position will have a
  7847. // hitSide=true property if it reached the end of the document.
  7848. function findPosH(doc, pos, dir, unit, visually) {
  7849. var oldPos = pos;
  7850. var origDir = dir;
  7851. var lineObj = getLine(doc, pos.line);
  7852. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  7853. function findNextLine() {
  7854. var l = pos.line + lineDir;
  7855. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7856. pos = new Pos(l, pos.ch, pos.sticky);
  7857. return lineObj = getLine(doc, l)
  7858. }
  7859. function moveOnce(boundToLine) {
  7860. var next;
  7861. if (unit == "codepoint") {
  7862. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  7863. if (isNaN(ch)) {
  7864. next = null;
  7865. } else {
  7866. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  7867. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  7868. }
  7869. } else if (visually) {
  7870. next = moveVisually(doc.cm, lineObj, pos, dir);
  7871. } else {
  7872. next = moveLogically(lineObj, pos, dir);
  7873. }
  7874. if (next == null) {
  7875. if (!boundToLine && findNextLine())
  7876. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  7877. else
  7878. { return false }
  7879. } else {
  7880. pos = next;
  7881. }
  7882. return true
  7883. }
  7884. if (unit == "char" || unit == "codepoint") {
  7885. moveOnce();
  7886. } else if (unit == "column") {
  7887. moveOnce(true);
  7888. } else if (unit == "word" || unit == "group") {
  7889. var sawType = null, group = unit == "group";
  7890. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7891. for (var first = true;; first = false) {
  7892. if (dir < 0 && !moveOnce(!first)) { break }
  7893. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7894. var type = isWordChar(cur, helper) ? "w"
  7895. : group && cur == "\n" ? "n"
  7896. : !group || /\s/.test(cur) ? null
  7897. : "p";
  7898. if (group && !first && !type) { type = "s"; }
  7899. if (sawType && sawType != type) {
  7900. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7901. break
  7902. }
  7903. if (type) { sawType = type; }
  7904. if (dir > 0 && !moveOnce(!first)) { break }
  7905. }
  7906. }
  7907. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7908. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7909. return result
  7910. }
  7911. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7912. // "page" or "line". The resulting position will have a hitSide=true
  7913. // property if it reached the end of the document.
  7914. function findPosV(cm, pos, dir, unit) {
  7915. var doc = cm.doc, x = pos.left, y;
  7916. if (unit == "page") {
  7917. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  7918. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7919. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7920. } else if (unit == "line") {
  7921. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7922. }
  7923. var target;
  7924. for (;;) {
  7925. target = coordsChar(cm, x, y);
  7926. if (!target.outside) { break }
  7927. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7928. y += dir * 5;
  7929. }
  7930. return target
  7931. }
  7932. // CONTENTEDITABLE INPUT STYLE
  7933. var ContentEditableInput = function(cm) {
  7934. this.cm = cm;
  7935. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7936. this.polling = new Delayed();
  7937. this.composing = null;
  7938. this.gracePeriod = false;
  7939. this.readDOMTimeout = null;
  7940. };
  7941. ContentEditableInput.prototype.init = function (display) {
  7942. var this$1 = this;
  7943. var input = this, cm = input.cm;
  7944. var div = input.div = display.lineDiv;
  7945. div.contentEditable = true;
  7946. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  7947. function belongsToInput(e) {
  7948. for (var t = e.target; t; t = t.parentNode) {
  7949. if (t == div) { return true }
  7950. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  7951. }
  7952. return false
  7953. }
  7954. on(div, "paste", function (e) {
  7955. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7956. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7957. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  7958. });
  7959. on(div, "compositionstart", function (e) {
  7960. this$1.composing = {data: e.data, done: false};
  7961. });
  7962. on(div, "compositionupdate", function (e) {
  7963. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  7964. });
  7965. on(div, "compositionend", function (e) {
  7966. if (this$1.composing) {
  7967. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  7968. this$1.composing.done = true;
  7969. }
  7970. });
  7971. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  7972. on(div, "input", function () {
  7973. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  7974. });
  7975. function onCopyCut(e) {
  7976. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  7977. if (cm.somethingSelected()) {
  7978. setLastCopied({lineWise: false, text: cm.getSelections()});
  7979. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  7980. } else if (!cm.options.lineWiseCopyCut) {
  7981. return
  7982. } else {
  7983. var ranges = copyableRanges(cm);
  7984. setLastCopied({lineWise: true, text: ranges.text});
  7985. if (e.type == "cut") {
  7986. cm.operation(function () {
  7987. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  7988. cm.replaceSelection("", null, "cut");
  7989. });
  7990. }
  7991. }
  7992. if (e.clipboardData) {
  7993. e.clipboardData.clearData();
  7994. var content = lastCopied.text.join("\n");
  7995. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7996. e.clipboardData.setData("Text", content);
  7997. if (e.clipboardData.getData("Text") == content) {
  7998. e.preventDefault();
  7999. return
  8000. }
  8001. }
  8002. // Old-fashioned briefly-focus-a-textarea hack
  8003. var kludge = hiddenTextarea(), te = kludge.firstChild;
  8004. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  8005. te.value = lastCopied.text.join("\n");
  8006. var hadFocus = activeElt();
  8007. selectInput(te);
  8008. setTimeout(function () {
  8009. cm.display.lineSpace.removeChild(kludge);
  8010. hadFocus.focus();
  8011. if (hadFocus == div) { input.showPrimarySelection(); }
  8012. }, 50);
  8013. }
  8014. on(div, "copy", onCopyCut);
  8015. on(div, "cut", onCopyCut);
  8016. };
  8017. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8018. // Label for screenreaders, accessibility
  8019. if(label) {
  8020. this.div.setAttribute('aria-label', label);
  8021. } else {
  8022. this.div.removeAttribute('aria-label');
  8023. }
  8024. };
  8025. ContentEditableInput.prototype.prepareSelection = function () {
  8026. var result = prepareSelection(this.cm, false);
  8027. result.focus = activeElt() == this.div;
  8028. return result
  8029. };
  8030. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8031. if (!info || !this.cm.display.view.length) { return }
  8032. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8033. this.showMultipleSelections(info);
  8034. };
  8035. ContentEditableInput.prototype.getSelection = function () {
  8036. return this.cm.display.wrapper.ownerDocument.getSelection()
  8037. };
  8038. ContentEditableInput.prototype.showPrimarySelection = function () {
  8039. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8040. var from = prim.from(), to = prim.to();
  8041. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8042. sel.removeAllRanges();
  8043. return
  8044. }
  8045. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8046. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8047. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8048. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8049. cmp(maxPos(curAnchor, curFocus), to) == 0)
  8050. { return }
  8051. var view = cm.display.view;
  8052. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8053. {node: view[0].measure.map[2], offset: 0};
  8054. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8055. if (!end) {
  8056. var measure = view[view.length - 1].measure;
  8057. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8058. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  8059. }
  8060. if (!start || !end) {
  8061. sel.removeAllRanges();
  8062. return
  8063. }
  8064. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8065. try { rng = range(start.node, start.offset, end.offset, end.node); }
  8066. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8067. if (rng) {
  8068. if (!gecko && cm.state.focused) {
  8069. sel.collapse(start.node, start.offset);
  8070. if (!rng.collapsed) {
  8071. sel.removeAllRanges();
  8072. sel.addRange(rng);
  8073. }
  8074. } else {
  8075. sel.removeAllRanges();
  8076. sel.addRange(rng);
  8077. }
  8078. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8079. else if (gecko) { this.startGracePeriod(); }
  8080. }
  8081. this.rememberSelection();
  8082. };
  8083. ContentEditableInput.prototype.startGracePeriod = function () {
  8084. var this$1 = this;
  8085. clearTimeout(this.gracePeriod);
  8086. this.gracePeriod = setTimeout(function () {
  8087. this$1.gracePeriod = false;
  8088. if (this$1.selectionChanged())
  8089. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8090. }, 20);
  8091. };
  8092. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8093. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8094. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8095. };
  8096. ContentEditableInput.prototype.rememberSelection = function () {
  8097. var sel = this.getSelection();
  8098. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8099. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8100. };
  8101. ContentEditableInput.prototype.selectionInEditor = function () {
  8102. var sel = this.getSelection();
  8103. if (!sel.rangeCount) { return false }
  8104. var node = sel.getRangeAt(0).commonAncestorContainer;
  8105. return contains(this.div, node)
  8106. };
  8107. ContentEditableInput.prototype.focus = function () {
  8108. if (this.cm.options.readOnly != "nocursor") {
  8109. if (!this.selectionInEditor() || activeElt() != this.div)
  8110. { this.showSelection(this.prepareSelection(), true); }
  8111. this.div.focus();
  8112. }
  8113. };
  8114. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8115. ContentEditableInput.prototype.getField = function () { return this.div };
  8116. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8117. ContentEditableInput.prototype.receivedFocus = function () {
  8118. var input = this;
  8119. if (this.selectionInEditor())
  8120. { this.pollSelection(); }
  8121. else
  8122. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8123. function poll() {
  8124. if (input.cm.state.focused) {
  8125. input.pollSelection();
  8126. input.polling.set(input.cm.options.pollInterval, poll);
  8127. }
  8128. }
  8129. this.polling.set(this.cm.options.pollInterval, poll);
  8130. };
  8131. ContentEditableInput.prototype.selectionChanged = function () {
  8132. var sel = this.getSelection();
  8133. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8134. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8135. };
  8136. ContentEditableInput.prototype.pollSelection = function () {
  8137. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8138. var sel = this.getSelection(), cm = this.cm;
  8139. // On Android Chrome (version 56, at least), backspacing into an
  8140. // uneditable block element will put the cursor in that element,
  8141. // and then, because it's not editable, hide the virtual keyboard.
  8142. // Because Android doesn't allow us to actually detect backspace
  8143. // presses in a sane way, this code checks for when that happens
  8144. // and simulates a backspace press in this case.
  8145. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8146. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8147. this.blur();
  8148. this.focus();
  8149. return
  8150. }
  8151. if (this.composing) { return }
  8152. this.rememberSelection();
  8153. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8154. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8155. if (anchor && head) { runInOp(cm, function () {
  8156. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8157. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8158. }); }
  8159. };
  8160. ContentEditableInput.prototype.pollContent = function () {
  8161. if (this.readDOMTimeout != null) {
  8162. clearTimeout(this.readDOMTimeout);
  8163. this.readDOMTimeout = null;
  8164. }
  8165. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8166. var from = sel.from(), to = sel.to();
  8167. if (from.ch == 0 && from.line > cm.firstLine())
  8168. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8169. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8170. { to = Pos(to.line + 1, 0); }
  8171. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8172. var fromIndex, fromLine, fromNode;
  8173. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8174. fromLine = lineNo(display.view[0].line);
  8175. fromNode = display.view[0].node;
  8176. } else {
  8177. fromLine = lineNo(display.view[fromIndex].line);
  8178. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8179. }
  8180. var toIndex = findViewIndex(cm, to.line);
  8181. var toLine, toNode;
  8182. if (toIndex == display.view.length - 1) {
  8183. toLine = display.viewTo - 1;
  8184. toNode = display.lineDiv.lastChild;
  8185. } else {
  8186. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8187. toNode = display.view[toIndex + 1].node.previousSibling;
  8188. }
  8189. if (!fromNode) { return false }
  8190. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8191. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8192. while (newText.length > 1 && oldText.length > 1) {
  8193. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8194. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8195. else { break }
  8196. }
  8197. var cutFront = 0, cutEnd = 0;
  8198. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8199. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8200. { ++cutFront; }
  8201. var newBot = lst(newText), oldBot = lst(oldText);
  8202. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8203. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8204. while (cutEnd < maxCutEnd &&
  8205. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8206. { ++cutEnd; }
  8207. // Try to move start of change to start of selection if ambiguous
  8208. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8209. while (cutFront && cutFront > from.ch &&
  8210. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8211. cutFront--;
  8212. cutEnd++;
  8213. }
  8214. }
  8215. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8216. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8217. var chFrom = Pos(fromLine, cutFront);
  8218. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8219. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8220. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8221. return true
  8222. }
  8223. };
  8224. ContentEditableInput.prototype.ensurePolled = function () {
  8225. this.forceCompositionEnd();
  8226. };
  8227. ContentEditableInput.prototype.reset = function () {
  8228. this.forceCompositionEnd();
  8229. };
  8230. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8231. if (!this.composing) { return }
  8232. clearTimeout(this.readDOMTimeout);
  8233. this.composing = null;
  8234. this.updateFromDOM();
  8235. this.div.blur();
  8236. this.div.focus();
  8237. };
  8238. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8239. var this$1 = this;
  8240. if (this.readDOMTimeout != null) { return }
  8241. this.readDOMTimeout = setTimeout(function () {
  8242. this$1.readDOMTimeout = null;
  8243. if (this$1.composing) {
  8244. if (this$1.composing.done) { this$1.composing = null; }
  8245. else { return }
  8246. }
  8247. this$1.updateFromDOM();
  8248. }, 80);
  8249. };
  8250. ContentEditableInput.prototype.updateFromDOM = function () {
  8251. var this$1 = this;
  8252. if (this.cm.isReadOnly() || !this.pollContent())
  8253. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8254. };
  8255. ContentEditableInput.prototype.setUneditable = function (node) {
  8256. node.contentEditable = "false";
  8257. };
  8258. ContentEditableInput.prototype.onKeyPress = function (e) {
  8259. if (e.charCode == 0 || this.composing) { return }
  8260. e.preventDefault();
  8261. if (!this.cm.isReadOnly())
  8262. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8263. };
  8264. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8265. this.div.contentEditable = String(val != "nocursor");
  8266. };
  8267. ContentEditableInput.prototype.onContextMenu = function () {};
  8268. ContentEditableInput.prototype.resetPosition = function () {};
  8269. ContentEditableInput.prototype.needsContentAttribute = true;
  8270. function posToDOM(cm, pos) {
  8271. var view = findViewForLine(cm, pos.line);
  8272. if (!view || view.hidden) { return null }
  8273. var line = getLine(cm.doc, pos.line);
  8274. var info = mapFromLineView(view, line, pos.line);
  8275. var order = getOrder(line, cm.doc.direction), side = "left";
  8276. if (order) {
  8277. var partPos = getBidiPartAt(order, pos.ch);
  8278. side = partPos % 2 ? "right" : "left";
  8279. }
  8280. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8281. result.offset = result.collapse == "right" ? result.end : result.start;
  8282. return result
  8283. }
  8284. function isInGutter(node) {
  8285. for (var scan = node; scan; scan = scan.parentNode)
  8286. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8287. return false
  8288. }
  8289. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8290. function domTextBetween(cm, from, to, fromLine, toLine) {
  8291. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8292. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8293. function close() {
  8294. if (closing) {
  8295. text += lineSep;
  8296. if (extraLinebreak) { text += lineSep; }
  8297. closing = extraLinebreak = false;
  8298. }
  8299. }
  8300. function addText(str) {
  8301. if (str) {
  8302. close();
  8303. text += str;
  8304. }
  8305. }
  8306. function walk(node) {
  8307. if (node.nodeType == 1) {
  8308. var cmText = node.getAttribute("cm-text");
  8309. if (cmText) {
  8310. addText(cmText);
  8311. return
  8312. }
  8313. var markerID = node.getAttribute("cm-marker"), range;
  8314. if (markerID) {
  8315. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8316. if (found.length && (range = found[0].find(0)))
  8317. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  8318. return
  8319. }
  8320. if (node.getAttribute("contenteditable") == "false") { return }
  8321. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8322. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8323. if (isBlock) { close(); }
  8324. for (var i = 0; i < node.childNodes.length; i++)
  8325. { walk(node.childNodes[i]); }
  8326. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8327. if (isBlock) { closing = true; }
  8328. } else if (node.nodeType == 3) {
  8329. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8330. }
  8331. }
  8332. for (;;) {
  8333. walk(from);
  8334. if (from == to) { break }
  8335. from = from.nextSibling;
  8336. extraLinebreak = false;
  8337. }
  8338. return text
  8339. }
  8340. function domToPos(cm, node, offset) {
  8341. var lineNode;
  8342. if (node == cm.display.lineDiv) {
  8343. lineNode = cm.display.lineDiv.childNodes[offset];
  8344. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8345. node = null; offset = 0;
  8346. } else {
  8347. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8348. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8349. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8350. }
  8351. }
  8352. for (var i = 0; i < cm.display.view.length; i++) {
  8353. var lineView = cm.display.view[i];
  8354. if (lineView.node == lineNode)
  8355. { return locateNodeInLineView(lineView, node, offset) }
  8356. }
  8357. }
  8358. function locateNodeInLineView(lineView, node, offset) {
  8359. var wrapper = lineView.text.firstChild, bad = false;
  8360. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8361. if (node == wrapper) {
  8362. bad = true;
  8363. node = wrapper.childNodes[offset];
  8364. offset = 0;
  8365. if (!node) {
  8366. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8367. return badPos(Pos(lineNo(line), line.text.length), bad)
  8368. }
  8369. }
  8370. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8371. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8372. textNode = node.firstChild;
  8373. if (offset) { offset = textNode.nodeValue.length; }
  8374. }
  8375. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8376. var measure = lineView.measure, maps = measure.maps;
  8377. function find(textNode, topNode, offset) {
  8378. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8379. var map = i < 0 ? measure.map : maps[i];
  8380. for (var j = 0; j < map.length; j += 3) {
  8381. var curNode = map[j + 2];
  8382. if (curNode == textNode || curNode == topNode) {
  8383. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8384. var ch = map[j] + offset;
  8385. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  8386. return Pos(line, ch)
  8387. }
  8388. }
  8389. }
  8390. }
  8391. var found = find(textNode, topNode, offset);
  8392. if (found) { return badPos(found, bad) }
  8393. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8394. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8395. found = find(after, after.firstChild, 0);
  8396. if (found)
  8397. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8398. else
  8399. { dist += after.textContent.length; }
  8400. }
  8401. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8402. found = find(before, before.firstChild, -1);
  8403. if (found)
  8404. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8405. else
  8406. { dist$1 += before.textContent.length; }
  8407. }
  8408. }
  8409. // TEXTAREA INPUT STYLE
  8410. var TextareaInput = function(cm) {
  8411. this.cm = cm;
  8412. // See input.poll and input.reset
  8413. this.prevInput = "";
  8414. // Flag that indicates whether we expect input to appear real soon
  8415. // now (after some event like 'keypress' or 'input') and are
  8416. // polling intensively.
  8417. this.pollingFast = false;
  8418. // Self-resetting timeout for the poller
  8419. this.polling = new Delayed();
  8420. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8421. this.hasSelection = false;
  8422. this.composing = null;
  8423. };
  8424. TextareaInput.prototype.init = function (display) {
  8425. var this$1 = this;
  8426. var input = this, cm = this.cm;
  8427. this.createField(display);
  8428. var te = this.textarea;
  8429. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8430. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8431. if (ios) { te.style.width = "0px"; }
  8432. on(te, "input", function () {
  8433. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8434. input.poll();
  8435. });
  8436. on(te, "paste", function (e) {
  8437. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8438. cm.state.pasteIncoming = +new Date;
  8439. input.fastPoll();
  8440. });
  8441. function prepareCopyCut(e) {
  8442. if (signalDOMEvent(cm, e)) { return }
  8443. if (cm.somethingSelected()) {
  8444. setLastCopied({lineWise: false, text: cm.getSelections()});
  8445. } else if (!cm.options.lineWiseCopyCut) {
  8446. return
  8447. } else {
  8448. var ranges = copyableRanges(cm);
  8449. setLastCopied({lineWise: true, text: ranges.text});
  8450. if (e.type == "cut") {
  8451. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8452. } else {
  8453. input.prevInput = "";
  8454. te.value = ranges.text.join("\n");
  8455. selectInput(te);
  8456. }
  8457. }
  8458. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8459. }
  8460. on(te, "cut", prepareCopyCut);
  8461. on(te, "copy", prepareCopyCut);
  8462. on(display.scroller, "paste", function (e) {
  8463. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8464. if (!te.dispatchEvent) {
  8465. cm.state.pasteIncoming = +new Date;
  8466. input.focus();
  8467. return
  8468. }
  8469. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8470. var event = new Event("paste");
  8471. event.clipboardData = e.clipboardData;
  8472. te.dispatchEvent(event);
  8473. });
  8474. // Prevent normal selection in the editor (we handle our own)
  8475. on(display.lineSpace, "selectstart", function (e) {
  8476. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8477. });
  8478. on(te, "compositionstart", function () {
  8479. var start = cm.getCursor("from");
  8480. if (input.composing) { input.composing.range.clear(); }
  8481. input.composing = {
  8482. start: start,
  8483. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8484. };
  8485. });
  8486. on(te, "compositionend", function () {
  8487. if (input.composing) {
  8488. input.poll();
  8489. input.composing.range.clear();
  8490. input.composing = null;
  8491. }
  8492. });
  8493. };
  8494. TextareaInput.prototype.createField = function (_display) {
  8495. // Wraps and hides input textarea
  8496. this.wrapper = hiddenTextarea();
  8497. // The semihidden textarea that is focused when the editor is
  8498. // focused, and receives input.
  8499. this.textarea = this.wrapper.firstChild;
  8500. };
  8501. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  8502. // Label for screenreaders, accessibility
  8503. if(label) {
  8504. this.textarea.setAttribute('aria-label', label);
  8505. } else {
  8506. this.textarea.removeAttribute('aria-label');
  8507. }
  8508. };
  8509. TextareaInput.prototype.prepareSelection = function () {
  8510. // Redraw the selection and/or cursor
  8511. var cm = this.cm, display = cm.display, doc = cm.doc;
  8512. var result = prepareSelection(cm);
  8513. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8514. if (cm.options.moveInputWithCursor) {
  8515. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8516. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8517. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8518. headPos.top + lineOff.top - wrapOff.top));
  8519. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8520. headPos.left + lineOff.left - wrapOff.left));
  8521. }
  8522. return result
  8523. };
  8524. TextareaInput.prototype.showSelection = function (drawn) {
  8525. var cm = this.cm, display = cm.display;
  8526. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8527. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8528. if (drawn.teTop != null) {
  8529. this.wrapper.style.top = drawn.teTop + "px";
  8530. this.wrapper.style.left = drawn.teLeft + "px";
  8531. }
  8532. };
  8533. // Reset the input to correspond to the selection (or to be empty,
  8534. // when not typing and nothing is selected)
  8535. TextareaInput.prototype.reset = function (typing) {
  8536. if (this.contextMenuPending || this.composing) { return }
  8537. var cm = this.cm;
  8538. if (cm.somethingSelected()) {
  8539. this.prevInput = "";
  8540. var content = cm.getSelection();
  8541. this.textarea.value = content;
  8542. if (cm.state.focused) { selectInput(this.textarea); }
  8543. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8544. } else if (!typing) {
  8545. this.prevInput = this.textarea.value = "";
  8546. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8547. }
  8548. };
  8549. TextareaInput.prototype.getField = function () { return this.textarea };
  8550. TextareaInput.prototype.supportsTouch = function () { return false };
  8551. TextareaInput.prototype.focus = function () {
  8552. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8553. try { this.textarea.focus(); }
  8554. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8555. }
  8556. };
  8557. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8558. TextareaInput.prototype.resetPosition = function () {
  8559. this.wrapper.style.top = this.wrapper.style.left = 0;
  8560. };
  8561. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8562. // Poll for input changes, using the normal rate of polling. This
  8563. // runs as long as the editor is focused.
  8564. TextareaInput.prototype.slowPoll = function () {
  8565. var this$1 = this;
  8566. if (this.pollingFast) { return }
  8567. this.polling.set(this.cm.options.pollInterval, function () {
  8568. this$1.poll();
  8569. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8570. });
  8571. };
  8572. // When an event has just come in that is likely to add or change
  8573. // something in the input textarea, we poll faster, to ensure that
  8574. // the change appears on the screen quickly.
  8575. TextareaInput.prototype.fastPoll = function () {
  8576. var missed = false, input = this;
  8577. input.pollingFast = true;
  8578. function p() {
  8579. var changed = input.poll();
  8580. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8581. else {input.pollingFast = false; input.slowPoll();}
  8582. }
  8583. input.polling.set(20, p);
  8584. };
  8585. // Read input from the textarea, and update the document to match.
  8586. // When something is selected, it is present in the textarea, and
  8587. // selected (unless it is huge, in which case a placeholder is
  8588. // used). When nothing is selected, the cursor sits after previously
  8589. // seen text (can be empty), which is stored in prevInput (we must
  8590. // not reset the textarea when typing, because that breaks IME).
  8591. TextareaInput.prototype.poll = function () {
  8592. var this$1 = this;
  8593. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8594. // Since this is called a *lot*, try to bail out as cheaply as
  8595. // possible when it is clear that nothing happened. hasSelection
  8596. // will be the case when there is a lot of text in the textarea,
  8597. // in which case reading its value would be expensive.
  8598. if (this.contextMenuPending || !cm.state.focused ||
  8599. (hasSelection(input) && !prevInput && !this.composing) ||
  8600. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8601. { return false }
  8602. var text = input.value;
  8603. // If nothing changed, bail.
  8604. if (text == prevInput && !cm.somethingSelected()) { return false }
  8605. // Work around nonsensical selection resetting in IE9/10, and
  8606. // inexplicable appearance of private area unicode characters on
  8607. // some key combos in Mac (#2689).
  8608. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8609. mac && /[\uf700-\uf7ff]/.test(text)) {
  8610. cm.display.input.reset();
  8611. return false
  8612. }
  8613. if (cm.doc.sel == cm.display.selForContextMenu) {
  8614. var first = text.charCodeAt(0);
  8615. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8616. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8617. }
  8618. // Find the part of the input that is actually new
  8619. var same = 0, l = Math.min(prevInput.length, text.length);
  8620. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8621. runInOp(cm, function () {
  8622. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8623. null, this$1.composing ? "*compose" : null);
  8624. // Don't leave long text in the textarea, since it makes further polling slow
  8625. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8626. else { this$1.prevInput = text; }
  8627. if (this$1.composing) {
  8628. this$1.composing.range.clear();
  8629. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8630. {className: "CodeMirror-composing"});
  8631. }
  8632. });
  8633. return true
  8634. };
  8635. TextareaInput.prototype.ensurePolled = function () {
  8636. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8637. };
  8638. TextareaInput.prototype.onKeyPress = function () {
  8639. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8640. this.fastPoll();
  8641. };
  8642. TextareaInput.prototype.onContextMenu = function (e) {
  8643. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8644. if (input.contextMenuPending) { input.contextMenuPending(); }
  8645. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8646. if (!pos || presto) { return } // Opera is difficult.
  8647. // Reset the current text selection only if the click is done outside of the selection
  8648. // and 'resetSelectionOnContextMenu' option is true.
  8649. var reset = cm.options.resetSelectionOnContextMenu;
  8650. if (reset && cm.doc.sel.contains(pos) == -1)
  8651. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8652. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8653. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8654. input.wrapper.style.cssText = "position: static";
  8655. 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);";
  8656. var oldScrollY;
  8657. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  8658. display.input.focus();
  8659. if (webkit) { window.scrollTo(null, oldScrollY); }
  8660. display.input.reset();
  8661. // Adds "Select all" to context menu in FF
  8662. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8663. input.contextMenuPending = rehide;
  8664. display.selForContextMenu = cm.doc.sel;
  8665. clearTimeout(display.detectingSelectAll);
  8666. // Select-all will be greyed out if there's nothing to select, so
  8667. // this adds a zero-width space so that we can later check whether
  8668. // it got selected.
  8669. function prepareSelectAllHack() {
  8670. if (te.selectionStart != null) {
  8671. var selected = cm.somethingSelected();
  8672. var extval = "\u200b" + (selected ? te.value : "");
  8673. te.value = "\u21da"; // Used to catch context-menu undo
  8674. te.value = extval;
  8675. input.prevInput = selected ? "" : "\u200b";
  8676. te.selectionStart = 1; te.selectionEnd = extval.length;
  8677. // Re-set this, in case some other handler touched the
  8678. // selection in the meantime.
  8679. display.selForContextMenu = cm.doc.sel;
  8680. }
  8681. }
  8682. function rehide() {
  8683. if (input.contextMenuPending != rehide) { return }
  8684. input.contextMenuPending = false;
  8685. input.wrapper.style.cssText = oldWrapperCSS;
  8686. te.style.cssText = oldCSS;
  8687. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8688. // Try to detect the user choosing select-all
  8689. if (te.selectionStart != null) {
  8690. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8691. var i = 0, poll = function () {
  8692. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8693. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8694. operation(cm, selectAll)(cm);
  8695. } else if (i++ < 10) {
  8696. display.detectingSelectAll = setTimeout(poll, 500);
  8697. } else {
  8698. display.selForContextMenu = null;
  8699. display.input.reset();
  8700. }
  8701. };
  8702. display.detectingSelectAll = setTimeout(poll, 200);
  8703. }
  8704. }
  8705. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8706. if (captureRightClick) {
  8707. e_stop(e);
  8708. var mouseup = function () {
  8709. off(window, "mouseup", mouseup);
  8710. setTimeout(rehide, 20);
  8711. };
  8712. on(window, "mouseup", mouseup);
  8713. } else {
  8714. setTimeout(rehide, 50);
  8715. }
  8716. };
  8717. TextareaInput.prototype.readOnlyChanged = function (val) {
  8718. if (!val) { this.reset(); }
  8719. this.textarea.disabled = val == "nocursor";
  8720. this.textarea.readOnly = !!val;
  8721. };
  8722. TextareaInput.prototype.setUneditable = function () {};
  8723. TextareaInput.prototype.needsContentAttribute = false;
  8724. function fromTextArea(textarea, options) {
  8725. options = options ? copyObj(options) : {};
  8726. options.value = textarea.value;
  8727. if (!options.tabindex && textarea.tabIndex)
  8728. { options.tabindex = textarea.tabIndex; }
  8729. if (!options.placeholder && textarea.placeholder)
  8730. { options.placeholder = textarea.placeholder; }
  8731. // Set autofocus to true if this textarea is focused, or if it has
  8732. // autofocus and no other element is focused.
  8733. if (options.autofocus == null) {
  8734. var hasFocus = activeElt();
  8735. options.autofocus = hasFocus == textarea ||
  8736. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8737. }
  8738. function save() {textarea.value = cm.getValue();}
  8739. var realSubmit;
  8740. if (textarea.form) {
  8741. on(textarea.form, "submit", save);
  8742. // Deplorable hack to make the submit method do the right thing.
  8743. if (!options.leaveSubmitMethodAlone) {
  8744. var form = textarea.form;
  8745. realSubmit = form.submit;
  8746. try {
  8747. var wrappedSubmit = form.submit = function () {
  8748. save();
  8749. form.submit = realSubmit;
  8750. form.submit();
  8751. form.submit = wrappedSubmit;
  8752. };
  8753. } catch(e) {}
  8754. }
  8755. }
  8756. options.finishInit = function (cm) {
  8757. cm.save = save;
  8758. cm.getTextArea = function () { return textarea; };
  8759. cm.toTextArea = function () {
  8760. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8761. save();
  8762. textarea.parentNode.removeChild(cm.getWrapperElement());
  8763. textarea.style.display = "";
  8764. if (textarea.form) {
  8765. off(textarea.form, "submit", save);
  8766. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  8767. { textarea.form.submit = realSubmit; }
  8768. }
  8769. };
  8770. };
  8771. textarea.style.display = "none";
  8772. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8773. options);
  8774. return cm
  8775. }
  8776. function addLegacyProps(CodeMirror) {
  8777. CodeMirror.off = off;
  8778. CodeMirror.on = on;
  8779. CodeMirror.wheelEventPixels = wheelEventPixels;
  8780. CodeMirror.Doc = Doc;
  8781. CodeMirror.splitLines = splitLinesAuto;
  8782. CodeMirror.countColumn = countColumn;
  8783. CodeMirror.findColumn = findColumn;
  8784. CodeMirror.isWordChar = isWordCharBasic;
  8785. CodeMirror.Pass = Pass;
  8786. CodeMirror.signal = signal;
  8787. CodeMirror.Line = Line;
  8788. CodeMirror.changeEnd = changeEnd;
  8789. CodeMirror.scrollbarModel = scrollbarModel;
  8790. CodeMirror.Pos = Pos;
  8791. CodeMirror.cmpPos = cmp;
  8792. CodeMirror.modes = modes;
  8793. CodeMirror.mimeModes = mimeModes;
  8794. CodeMirror.resolveMode = resolveMode;
  8795. CodeMirror.getMode = getMode;
  8796. CodeMirror.modeExtensions = modeExtensions;
  8797. CodeMirror.extendMode = extendMode;
  8798. CodeMirror.copyState = copyState;
  8799. CodeMirror.startState = startState;
  8800. CodeMirror.innerMode = innerMode;
  8801. CodeMirror.commands = commands;
  8802. CodeMirror.keyMap = keyMap;
  8803. CodeMirror.keyName = keyName;
  8804. CodeMirror.isModifierKey = isModifierKey;
  8805. CodeMirror.lookupKey = lookupKey;
  8806. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8807. CodeMirror.StringStream = StringStream;
  8808. CodeMirror.SharedTextMarker = SharedTextMarker;
  8809. CodeMirror.TextMarker = TextMarker;
  8810. CodeMirror.LineWidget = LineWidget;
  8811. CodeMirror.e_preventDefault = e_preventDefault;
  8812. CodeMirror.e_stopPropagation = e_stopPropagation;
  8813. CodeMirror.e_stop = e_stop;
  8814. CodeMirror.addClass = addClass;
  8815. CodeMirror.contains = contains;
  8816. CodeMirror.rmClass = rmClass;
  8817. CodeMirror.keyNames = keyNames;
  8818. }
  8819. // EDITOR CONSTRUCTOR
  8820. defineOptions(CodeMirror);
  8821. addEditorMethods(CodeMirror);
  8822. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8823. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8824. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8825. { CodeMirror.prototype[prop] = (function(method) {
  8826. return function() {return method.apply(this.doc, arguments)}
  8827. })(Doc.prototype[prop]); } }
  8828. eventMixin(Doc);
  8829. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8830. // Extra arguments are stored as the mode's dependencies, which is
  8831. // used by (legacy) mechanisms like loadmode.js to automatically
  8832. // load a mode. (Preferred mechanism is the require/define calls.)
  8833. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8834. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  8835. defineMode.apply(this, arguments);
  8836. };
  8837. CodeMirror.defineMIME = defineMIME;
  8838. // Minimal default mode.
  8839. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8840. CodeMirror.defineMIME("text/plain", "null");
  8841. // EXTENSIONS
  8842. CodeMirror.defineExtension = function (name, func) {
  8843. CodeMirror.prototype[name] = func;
  8844. };
  8845. CodeMirror.defineDocExtension = function (name, func) {
  8846. Doc.prototype[name] = func;
  8847. };
  8848. CodeMirror.fromTextArea = fromTextArea;
  8849. addLegacyProps(CodeMirror);
  8850. CodeMirror.version = "5.62.0";
  8851. return CodeMirror;
  8852. })));