codemirror.js 314 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function(mod) {
  9. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10. module.exports = mod();
  11. else if (typeof define == "function" && define.amd) // AMD
  12. return define([], mod);
  13. else // Plain browser env
  14. this.CodeMirror = mod();
  15. })(function() {
  16. "use strict";
  17. // BROWSER SNIFFING
  18. // Kludges for bugs and behavior differences that can't be feature
  19. // detected are enabled based on userAgent etc sniffing.
  20. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  21. // ie_uptoN means Internet Explorer version N or lower
  22. var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
  23. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
  24. var ie = ie_upto10 || ie_11up;
  25. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  26. var webkit = /WebKit\//.test(navigator.userAgent);
  27. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  28. var chrome = /Chrome\//.test(navigator.userAgent);
  29. var presto = /Opera\//.test(navigator.userAgent);
  30. var safari = /Apple Computer/.test(navigator.vendor);
  31. var khtml = /KHTML\//.test(navigator.userAgent);
  32. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  33. var phantom = /PhantomJS/.test(navigator.userAgent);
  34. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  35. // This is woefully incomplete. Suggestions for alternative methods welcome.
  36. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
  37. var mac = ios || /Mac/.test(navigator.platform);
  38. var windows = /win/i.test(navigator.platform);
  39. var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
  40. if (presto_version) presto_version = Number(presto_version[1]);
  41. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  42. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  43. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  44. var captureRightClick = gecko || (ie && ie_version >= 9);
  45. // Optimize some code when these features are not used.
  46. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  47. // EDITOR CONSTRUCTOR
  48. // A CodeMirror instance represents an editor. This is the object
  49. // that user code is usually dealing with.
  50. function CodeMirror(place, options) {
  51. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  52. this.options = options = options ? copyObj(options) : {};
  53. // Determine effective options based on given values and defaults.
  54. copyObj(defaults, options, false);
  55. setGuttersForLineNumbers(options);
  56. var doc = options.value;
  57. if (typeof doc == "string") doc = new Doc(doc, options.mode);
  58. this.doc = doc;
  59. var display = this.display = new Display(place, doc);
  60. display.wrapper.CodeMirror = this;
  61. updateGutters(this);
  62. themeChanged(this);
  63. if (options.lineWrapping)
  64. this.display.wrapper.className += " CodeMirror-wrap";
  65. if (options.autofocus && !mobile) focusInput(this);
  66. initScrollbars(this);
  67. this.state = {
  68. keyMaps: [], // stores maps added by addKeyMap
  69. overlays: [], // highlighting overlays, as added by addOverlay
  70. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  71. overwrite: false, focused: false,
  72. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  73. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
  74. draggingText: false,
  75. highlight: new Delayed(), // stores highlight worker timeout
  76. keySeq: null // Unfinished key sequence
  77. };
  78. // Override magic textarea content restore that IE sometimes does
  79. // on our hidden textarea on reload
  80. if (ie && ie_version < 11) setTimeout(bind(resetInput, this, true), 20);
  81. registerEventHandlers(this);
  82. ensureGlobalHandlers();
  83. startOperation(this);
  84. this.curOp.forceUpdate = true;
  85. attachDoc(this, doc);
  86. if ((options.autofocus && !mobile) || activeElt() == display.input)
  87. setTimeout(bind(onFocus, this), 20);
  88. else
  89. onBlur(this);
  90. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  91. optionHandlers[opt](this, options[opt], Init);
  92. maybeUpdateLineNumberWidth(this);
  93. if (options.finishInit) options.finishInit(this);
  94. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  95. endOperation(this);
  96. // Suppress optimizelegibility in Webkit, since it breaks text
  97. // measuring on line wrapping boundaries.
  98. if (webkit && options.lineWrapping &&
  99. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  100. display.lineDiv.style.textRendering = "auto";
  101. }
  102. // DISPLAY CONSTRUCTOR
  103. // The display handles the DOM integration, both for input reading
  104. // and content drawing. It holds references to DOM nodes and
  105. // display-related state.
  106. function Display(place, doc) {
  107. var d = this;
  108. // The semihidden textarea that is focused when the editor is
  109. // focused, and receives input.
  110. var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  111. // The textarea is kept positioned near the cursor to prevent the
  112. // fact that it'll be scrolled into view on input from scrolling
  113. // our fake cursor out of view. On webkit, when wrap=off, paste is
  114. // very slow. So make the area wide instead.
  115. if (webkit) input.style.width = "1000px";
  116. else input.setAttribute("wrap", "off");
  117. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  118. if (ios) input.style.border = "1px solid black";
  119. input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
  120. // Wraps and hides input textarea
  121. d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  122. // Covers bottom-right square when both scrollbars are present.
  123. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  124. d.scrollbarFiller.setAttribute("not-content", "true");
  125. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  126. // and h scrollbar is present.
  127. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  128. d.gutterFiller.setAttribute("not-content", "true");
  129. // Will contain the actual code, positioned to cover the viewport.
  130. d.lineDiv = elt("div", null, "CodeMirror-code");
  131. // Elements are added to these to represent selection and cursors.
  132. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  133. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  134. // A visibility: hidden element used to find the size of things.
  135. d.measure = elt("div", null, "CodeMirror-measure");
  136. // When lines outside of the viewport are measured, they are drawn in this.
  137. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  138. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  139. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  140. null, "position: relative; outline: none");
  141. // Moved around its parent to cover visible view.
  142. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  143. // Set to the height of the document, allowing scrolling.
  144. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  145. d.sizerWidth = null;
  146. // Behavior of elts with overflow: auto and padding is
  147. // inconsistent across browsers. This is used to ensure the
  148. // scrollable area is big enough.
  149. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  150. // Will contain the gutters, if any.
  151. d.gutters = elt("div", null, "CodeMirror-gutters");
  152. d.lineGutter = null;
  153. // Actual scrollable element.
  154. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  155. d.scroller.setAttribute("tabIndex", "-1");
  156. // The element in which the editor lives.
  157. d.wrapper = elt("div", [d.inputDiv, d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  158. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  159. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  160. // Needed to hide big blue blinking cursor on Mobile Safari
  161. if (ios) input.style.width = "0px";
  162. if (!webkit) d.scroller.draggable = true;
  163. // Needed to handle Tab key in KHTML
  164. if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
  165. if (place) {
  166. if (place.appendChild) place.appendChild(d.wrapper);
  167. else place(d.wrapper);
  168. }
  169. // Current rendered range (may be bigger than the view window).
  170. d.viewFrom = d.viewTo = doc.first;
  171. d.reportedViewFrom = d.reportedViewTo = doc.first;
  172. // Information about the rendered lines.
  173. d.view = [];
  174. d.renderedView = null;
  175. // Holds info about a single rendered line when it was rendered
  176. // for measurement, while not in view.
  177. d.externalMeasured = null;
  178. // Empty space (in pixels) above the view
  179. d.viewOffset = 0;
  180. d.lastWrapHeight = d.lastWrapWidth = 0;
  181. d.updateLineNumbers = null;
  182. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  183. d.scrollbarsClipped = false;
  184. // Used to only resize the line number gutter when necessary (when
  185. // the amount of lines crosses a boundary that makes its width change)
  186. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  187. // See readInput and resetInput
  188. d.prevInput = "";
  189. // Set to true when a non-horizontal-scrolling line widget is
  190. // added. As an optimization, line widget aligning is skipped when
  191. // this is false.
  192. d.alignWidgets = false;
  193. // Flag that indicates whether we expect input to appear real soon
  194. // now (after some event like 'keypress' or 'input') and are
  195. // polling intensively.
  196. d.pollingFast = false;
  197. // Self-resetting timeout for the poller
  198. d.poll = new Delayed();
  199. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  200. // Tracks when resetInput has punted to just putting a short
  201. // string into the textarea instead of the full selection.
  202. d.inaccurateSelection = false;
  203. // Tracks the maximum line length so that the horizontal scrollbar
  204. // can be kept static when scrolling.
  205. d.maxLine = null;
  206. d.maxLineLength = 0;
  207. d.maxLineChanged = false;
  208. // Used for measuring wheel scrolling granularity
  209. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  210. // True when shift is held down.
  211. d.shift = false;
  212. // Used to track whether anything happened since the context menu
  213. // was opened.
  214. d.selForContextMenu = null;
  215. }
  216. // STATE UPDATES
  217. // Used to get the editor into a consistent state again when options change.
  218. function loadMode(cm) {
  219. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  220. resetModeState(cm);
  221. }
  222. function resetModeState(cm) {
  223. cm.doc.iter(function(line) {
  224. if (line.stateAfter) line.stateAfter = null;
  225. if (line.styles) line.styles = null;
  226. });
  227. cm.doc.frontier = cm.doc.first;
  228. startWorker(cm, 100);
  229. cm.state.modeGen++;
  230. if (cm.curOp) regChange(cm);
  231. }
  232. function wrappingChanged(cm) {
  233. if (cm.options.lineWrapping) {
  234. addClass(cm.display.wrapper, "CodeMirror-wrap");
  235. cm.display.sizer.style.minWidth = "";
  236. cm.display.sizerWidth = null;
  237. } else {
  238. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  239. findMaxLine(cm);
  240. }
  241. estimateLineHeights(cm);
  242. regChange(cm);
  243. clearCaches(cm);
  244. setTimeout(function(){updateScrollbars(cm);}, 100);
  245. }
  246. // Returns a function that estimates the height of a line, to use as
  247. // first approximation until the line becomes visible (and is thus
  248. // properly measurable).
  249. function estimateHeight(cm) {
  250. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  251. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  252. return function(line) {
  253. if (lineIsHidden(cm.doc, line)) return 0;
  254. var widgetsHeight = 0;
  255. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  256. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  257. }
  258. if (wrapping)
  259. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  260. else
  261. return widgetsHeight + th;
  262. };
  263. }
  264. function estimateLineHeights(cm) {
  265. var doc = cm.doc, est = estimateHeight(cm);
  266. doc.iter(function(line) {
  267. var estHeight = est(line);
  268. if (estHeight != line.height) updateLineHeight(line, estHeight);
  269. });
  270. }
  271. function themeChanged(cm) {
  272. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  273. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  274. clearCaches(cm);
  275. }
  276. function guttersChanged(cm) {
  277. updateGutters(cm);
  278. regChange(cm);
  279. setTimeout(function(){alignHorizontally(cm);}, 20);
  280. }
  281. // Rebuild the gutter elements, ensure the margin to the left of the
  282. // code matches their width.
  283. function updateGutters(cm) {
  284. var gutters = cm.display.gutters, specs = cm.options.gutters;
  285. removeChildren(gutters);
  286. for (var i = 0; i < specs.length; ++i) {
  287. var gutterClass = specs[i];
  288. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  289. if (gutterClass == "CodeMirror-linenumbers") {
  290. cm.display.lineGutter = gElt;
  291. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  292. }
  293. }
  294. gutters.style.display = i ? "" : "none";
  295. updateGutterSpace(cm);
  296. }
  297. function updateGutterSpace(cm) {
  298. var width = cm.display.gutters.offsetWidth;
  299. cm.display.sizer.style.marginLeft = width + "px";
  300. }
  301. // Compute the character length of a line, taking into account
  302. // collapsed ranges (see markText) that might hide parts, and join
  303. // other lines onto it.
  304. function lineLength(line) {
  305. if (line.height == 0) return 0;
  306. var len = line.text.length, merged, cur = line;
  307. while (merged = collapsedSpanAtStart(cur)) {
  308. var found = merged.find(0, true);
  309. cur = found.from.line;
  310. len += found.from.ch - found.to.ch;
  311. }
  312. cur = line;
  313. while (merged = collapsedSpanAtEnd(cur)) {
  314. var found = merged.find(0, true);
  315. len -= cur.text.length - found.from.ch;
  316. cur = found.to.line;
  317. len += cur.text.length - found.to.ch;
  318. }
  319. return len;
  320. }
  321. // Find the longest line in the document.
  322. function findMaxLine(cm) {
  323. var d = cm.display, doc = cm.doc;
  324. d.maxLine = getLine(doc, doc.first);
  325. d.maxLineLength = lineLength(d.maxLine);
  326. d.maxLineChanged = true;
  327. doc.iter(function(line) {
  328. var len = lineLength(line);
  329. if (len > d.maxLineLength) {
  330. d.maxLineLength = len;
  331. d.maxLine = line;
  332. }
  333. });
  334. }
  335. // Make sure the gutters options contains the element
  336. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  337. function setGuttersForLineNumbers(options) {
  338. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  339. if (found == -1 && options.lineNumbers) {
  340. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  341. } else if (found > -1 && !options.lineNumbers) {
  342. options.gutters = options.gutters.slice(0);
  343. options.gutters.splice(found, 1);
  344. }
  345. }
  346. // SCROLLBARS
  347. // Prepare DOM reads needed to update the scrollbars. Done in one
  348. // shot to minimize update/measure roundtrips.
  349. function measureForScrollbars(cm) {
  350. var d = cm.display, gutterW = d.gutters.offsetWidth;
  351. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  352. return {
  353. clientHeight: d.scroller.clientHeight,
  354. viewHeight: d.wrapper.clientHeight,
  355. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  356. viewWidth: d.wrapper.clientWidth,
  357. barLeft: cm.options.fixedGutter ? gutterW : 0,
  358. docHeight: docH,
  359. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  360. nativeBarWidth: d.nativeBarWidth,
  361. gutterWidth: gutterW
  362. };
  363. }
  364. function NativeScrollbars(place, scroll, cm) {
  365. this.cm = cm;
  366. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  367. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  368. place(vert); place(horiz);
  369. on(vert, "scroll", function() {
  370. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  371. });
  372. on(horiz, "scroll", function() {
  373. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  374. });
  375. this.checkedOverlay = false;
  376. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  377. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  378. }
  379. NativeScrollbars.prototype = copyObj({
  380. update: function(measure) {
  381. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  382. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  383. var sWidth = measure.nativeBarWidth;
  384. if (needsV) {
  385. this.vert.style.display = "block";
  386. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  387. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  388. // A bug in IE8 can cause this value to be negative, so guard it.
  389. this.vert.firstChild.style.height =
  390. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  391. } else {
  392. this.vert.style.display = "";
  393. this.vert.firstChild.style.height = "0";
  394. }
  395. if (needsH) {
  396. this.horiz.style.display = "block";
  397. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  398. this.horiz.style.left = measure.barLeft + "px";
  399. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  400. this.horiz.firstChild.style.width =
  401. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  402. } else {
  403. this.horiz.style.display = "";
  404. this.horiz.firstChild.style.width = "0";
  405. }
  406. if (!this.checkedOverlay && measure.clientHeight > 0) {
  407. if (sWidth == 0) this.overlayHack();
  408. this.checkedOverlay = true;
  409. }
  410. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  411. },
  412. setScrollLeft: function(pos) {
  413. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  414. },
  415. setScrollTop: function(pos) {
  416. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  417. },
  418. overlayHack: function() {
  419. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  420. this.horiz.style.minHeight = this.vert.style.minWidth = w;
  421. var self = this;
  422. var barMouseDown = function(e) {
  423. if (e_target(e) != self.vert && e_target(e) != self.horiz)
  424. operation(self.cm, onMouseDown)(e);
  425. };
  426. on(this.vert, "mousedown", barMouseDown);
  427. on(this.horiz, "mousedown", barMouseDown);
  428. },
  429. clear: function() {
  430. var parent = this.horiz.parentNode;
  431. parent.removeChild(this.horiz);
  432. parent.removeChild(this.vert);
  433. }
  434. }, NativeScrollbars.prototype);
  435. function NullScrollbars() {}
  436. NullScrollbars.prototype = copyObj({
  437. update: function() { return {bottom: 0, right: 0}; },
  438. setScrollLeft: function() {},
  439. setScrollTop: function() {},
  440. clear: function() {}
  441. }, NullScrollbars.prototype);
  442. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  443. function initScrollbars(cm) {
  444. if (cm.display.scrollbars) {
  445. cm.display.scrollbars.clear();
  446. if (cm.display.scrollbars.addClass)
  447. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  448. }
  449. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  450. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  451. on(node, "mousedown", function() {
  452. if (cm.state.focused) setTimeout(bind(focusInput, cm), 0);
  453. });
  454. node.setAttribute("not-content", "true");
  455. }, function(pos, axis) {
  456. if (axis == "horizontal") setScrollLeft(cm, pos);
  457. else setScrollTop(cm, pos);
  458. }, cm);
  459. if (cm.display.scrollbars.addClass)
  460. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  461. }
  462. function updateScrollbars(cm, measure) {
  463. if (!measure) measure = measureForScrollbars(cm);
  464. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  465. updateScrollbarsInner(cm, measure);
  466. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  467. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  468. updateHeightsInViewport(cm);
  469. updateScrollbarsInner(cm, measureForScrollbars(cm));
  470. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  471. }
  472. }
  473. // Re-synchronize the fake scrollbars with the actual size of the
  474. // content.
  475. function updateScrollbarsInner(cm, measure) {
  476. var d = cm.display;
  477. var sizes = d.scrollbars.update(measure);
  478. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  479. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  480. if (sizes.right && sizes.bottom) {
  481. d.scrollbarFiller.style.display = "block";
  482. d.scrollbarFiller.style.height = sizes.bottom + "px";
  483. d.scrollbarFiller.style.width = sizes.right + "px";
  484. } else d.scrollbarFiller.style.display = "";
  485. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  486. d.gutterFiller.style.display = "block";
  487. d.gutterFiller.style.height = sizes.bottom + "px";
  488. d.gutterFiller.style.width = measure.gutterWidth + "px";
  489. } else d.gutterFiller.style.display = "";
  490. }
  491. // Compute the lines that are visible in a given viewport (defaults
  492. // the the current scroll position). viewport may contain top,
  493. // height, and ensure (see op.scrollToPos) properties.
  494. function visibleLines(display, doc, viewport) {
  495. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  496. top = Math.floor(top - paddingTop(display));
  497. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  498. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  499. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  500. // forces those lines into the viewport (if possible).
  501. if (viewport && viewport.ensure) {
  502. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  503. if (ensureFrom < from) {
  504. from = ensureFrom;
  505. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  506. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  507. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  508. to = ensureTo;
  509. }
  510. }
  511. return {from: from, to: Math.max(to, from + 1)};
  512. }
  513. // LINE NUMBERS
  514. // Re-align line numbers and gutter marks to compensate for
  515. // horizontal scrolling.
  516. function alignHorizontally(cm) {
  517. var display = cm.display, view = display.view;
  518. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  519. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  520. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  521. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  522. if (cm.options.fixedGutter && view[i].gutter)
  523. view[i].gutter.style.left = left;
  524. var align = view[i].alignable;
  525. if (align) for (var j = 0; j < align.length; j++)
  526. align[j].style.left = left;
  527. }
  528. if (cm.options.fixedGutter)
  529. display.gutters.style.left = (comp + gutterW) + "px";
  530. }
  531. // Used to ensure that the line number gutter is still the right
  532. // size for the current document size. Returns true when an update
  533. // is needed.
  534. function maybeUpdateLineNumberWidth(cm) {
  535. if (!cm.options.lineNumbers) return false;
  536. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  537. if (last.length != display.lineNumChars) {
  538. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  539. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  540. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  541. display.lineGutter.style.width = "";
  542. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
  543. display.lineNumWidth = display.lineNumInnerWidth + padding;
  544. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  545. display.lineGutter.style.width = display.lineNumWidth + "px";
  546. updateGutterSpace(cm);
  547. return true;
  548. }
  549. return false;
  550. }
  551. function lineNumberFor(options, i) {
  552. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  553. }
  554. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  555. // but using getBoundingClientRect to get a sub-pixel-accurate
  556. // result.
  557. function compensateForHScroll(display) {
  558. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  559. }
  560. // DISPLAY DRAWING
  561. function DisplayUpdate(cm, viewport, force) {
  562. var display = cm.display;
  563. this.viewport = viewport;
  564. // Store some values that we'll need later (but don't want to force a relayout for)
  565. this.visible = visibleLines(display, cm.doc, viewport);
  566. this.editorIsHidden = !display.wrapper.offsetWidth;
  567. this.wrapperHeight = display.wrapper.clientHeight;
  568. this.wrapperWidth = display.wrapper.clientWidth;
  569. this.oldDisplayWidth = displayWidth(cm);
  570. this.force = force;
  571. this.dims = getDimensions(cm);
  572. this.events = [];
  573. }
  574. DisplayUpdate.prototype.signal = function(emitter, type) {
  575. if (hasHandler(emitter, type))
  576. this.events.push(arguments);
  577. };
  578. DisplayUpdate.prototype.finish = function() {
  579. for (var i = 0; i < this.events.length; i++)
  580. signal.apply(null, this.events[i]);
  581. };
  582. function maybeClipScrollbars(cm) {
  583. var display = cm.display;
  584. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  585. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  586. display.heightForcer.style.height = scrollGap(cm) + "px";
  587. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  588. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  589. display.scrollbarsClipped = true;
  590. }
  591. }
  592. // Does the actual updating of the line display. Bails out
  593. // (returning false) when there is nothing to be done and forced is
  594. // false.
  595. function updateDisplayIfNeeded(cm, update) {
  596. var display = cm.display, doc = cm.doc;
  597. if (update.editorIsHidden) {
  598. resetView(cm);
  599. return false;
  600. }
  601. // Bail out if the visible area is already rendered and nothing changed.
  602. if (!update.force &&
  603. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  604. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  605. display.renderedView == display.view && countDirtyView(cm) == 0)
  606. return false;
  607. if (maybeUpdateLineNumberWidth(cm)) {
  608. resetView(cm);
  609. update.dims = getDimensions(cm);
  610. }
  611. // Compute a suitable new viewport (from & to)
  612. var end = doc.first + doc.size;
  613. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  614. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  615. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  616. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  617. if (sawCollapsedSpans) {
  618. from = visualLineNo(cm.doc, from);
  619. to = visualLineEndNo(cm.doc, to);
  620. }
  621. var different = from != display.viewFrom || to != display.viewTo ||
  622. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  623. adjustView(cm, from, to);
  624. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  625. // Position the mover div to align with the current scroll position
  626. cm.display.mover.style.top = display.viewOffset + "px";
  627. var toUpdate = countDirtyView(cm);
  628. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  629. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  630. return false;
  631. // For big changes, we hide the enclosing element during the
  632. // update, since that speeds up the operations on most browsers.
  633. var focused = activeElt();
  634. if (toUpdate > 4) display.lineDiv.style.display = "none";
  635. patchDisplay(cm, display.updateLineNumbers, update.dims);
  636. if (toUpdate > 4) display.lineDiv.style.display = "";
  637. display.renderedView = display.view;
  638. // There might have been a widget with a focused element that got
  639. // hidden or updated, if so re-focus it.
  640. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  641. // Prevent selection and cursors from interfering with the scroll
  642. // width and height.
  643. removeChildren(display.cursorDiv);
  644. removeChildren(display.selectionDiv);
  645. display.gutters.style.height = 0;
  646. if (different) {
  647. display.lastWrapHeight = update.wrapperHeight;
  648. display.lastWrapWidth = update.wrapperWidth;
  649. startWorker(cm, 400);
  650. }
  651. display.updateLineNumbers = null;
  652. return true;
  653. }
  654. function postUpdateDisplay(cm, update) {
  655. var force = update.force, viewport = update.viewport;
  656. for (var first = true;; first = false) {
  657. if (first && cm.options.lineWrapping && update.oldDisplayWidth != displayWidth(cm)) {
  658. force = true;
  659. } else {
  660. force = false;
  661. // Clip forced viewport to actual scrollable area.
  662. if (viewport && viewport.top != null)
  663. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  664. // Updated line heights might result in the drawn area not
  665. // actually covering the viewport. Keep looping until it does.
  666. update.visible = visibleLines(cm.display, cm.doc, viewport);
  667. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  668. break;
  669. }
  670. if (!updateDisplayIfNeeded(cm, update)) break;
  671. updateHeightsInViewport(cm);
  672. var barMeasure = measureForScrollbars(cm);
  673. updateSelection(cm);
  674. setDocumentHeight(cm, barMeasure);
  675. updateScrollbars(cm, barMeasure);
  676. }
  677. update.signal(cm, "update", cm);
  678. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  679. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  680. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  681. }
  682. }
  683. function updateDisplaySimple(cm, viewport) {
  684. var update = new DisplayUpdate(cm, viewport);
  685. if (updateDisplayIfNeeded(cm, update)) {
  686. updateHeightsInViewport(cm);
  687. postUpdateDisplay(cm, update);
  688. var barMeasure = measureForScrollbars(cm);
  689. updateSelection(cm);
  690. setDocumentHeight(cm, barMeasure);
  691. updateScrollbars(cm, barMeasure);
  692. update.finish();
  693. }
  694. }
  695. function setDocumentHeight(cm, measure) {
  696. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  697. var total = measure.docHeight + cm.display.barHeight;
  698. cm.display.heightForcer.style.top = total + "px";
  699. cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
  700. }
  701. // Read the actual heights of the rendered lines, and update their
  702. // stored heights to match.
  703. function updateHeightsInViewport(cm) {
  704. var display = cm.display;
  705. var prevBottom = display.lineDiv.offsetTop;
  706. for (var i = 0; i < display.view.length; i++) {
  707. var cur = display.view[i], height;
  708. if (cur.hidden) continue;
  709. if (ie && ie_version < 8) {
  710. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  711. height = bot - prevBottom;
  712. prevBottom = bot;
  713. } else {
  714. var box = cur.node.getBoundingClientRect();
  715. height = box.bottom - box.top;
  716. }
  717. var diff = cur.line.height - height;
  718. if (height < 2) height = textHeight(display);
  719. if (diff > .001 || diff < -.001) {
  720. updateLineHeight(cur.line, height);
  721. updateWidgetHeight(cur.line);
  722. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  723. updateWidgetHeight(cur.rest[j]);
  724. }
  725. }
  726. }
  727. // Read and store the height of line widgets associated with the
  728. // given line.
  729. function updateWidgetHeight(line) {
  730. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  731. line.widgets[i].height = line.widgets[i].node.offsetHeight;
  732. }
  733. // Do a bulk-read of the DOM positions and sizes needed to draw the
  734. // view, so that we don't interleave reading and writing to the DOM.
  735. function getDimensions(cm) {
  736. var d = cm.display, left = {}, width = {};
  737. var gutterLeft = d.gutters.clientLeft;
  738. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  739. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  740. width[cm.options.gutters[i]] = n.clientWidth;
  741. }
  742. return {fixedPos: compensateForHScroll(d),
  743. gutterTotalWidth: d.gutters.offsetWidth,
  744. gutterLeft: left,
  745. gutterWidth: width,
  746. wrapperWidth: d.wrapper.clientWidth};
  747. }
  748. // Sync the actual display DOM structure with display.view, removing
  749. // nodes for lines that are no longer in view, and creating the ones
  750. // that are not there yet, and updating the ones that are out of
  751. // date.
  752. function patchDisplay(cm, updateNumbersFrom, dims) {
  753. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  754. var container = display.lineDiv, cur = container.firstChild;
  755. function rm(node) {
  756. var next = node.nextSibling;
  757. // Works around a throw-scroll bug in OS X Webkit
  758. if (webkit && mac && cm.display.currentWheelTarget == node)
  759. node.style.display = "none";
  760. else
  761. node.parentNode.removeChild(node);
  762. return next;
  763. }
  764. var view = display.view, lineN = display.viewFrom;
  765. // Loop over the elements in the view, syncing cur (the DOM nodes
  766. // in display.lineDiv) with the view as we go.
  767. for (var i = 0; i < view.length; i++) {
  768. var lineView = view[i];
  769. if (lineView.hidden) {
  770. } else if (!lineView.node) { // Not drawn yet
  771. var node = buildLineElement(cm, lineView, lineN, dims);
  772. container.insertBefore(node, cur);
  773. } else { // Already drawn
  774. while (cur != lineView.node) cur = rm(cur);
  775. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  776. updateNumbersFrom <= lineN && lineView.lineNumber;
  777. if (lineView.changes) {
  778. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  779. updateLineForChanges(cm, lineView, lineN, dims);
  780. }
  781. if (updateNumber) {
  782. removeChildren(lineView.lineNumber);
  783. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  784. }
  785. cur = lineView.node.nextSibling;
  786. }
  787. lineN += lineView.size;
  788. }
  789. while (cur) cur = rm(cur);
  790. }
  791. // When an aspect of a line changes, a string is added to
  792. // lineView.changes. This updates the relevant part of the line's
  793. // DOM structure.
  794. function updateLineForChanges(cm, lineView, lineN, dims) {
  795. for (var j = 0; j < lineView.changes.length; j++) {
  796. var type = lineView.changes[j];
  797. if (type == "text") updateLineText(cm, lineView);
  798. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  799. else if (type == "class") updateLineClasses(lineView);
  800. else if (type == "widget") updateLineWidgets(lineView, dims);
  801. }
  802. lineView.changes = null;
  803. }
  804. // Lines with gutter elements, widgets or a background class need to
  805. // be wrapped, and have the extra elements added to the wrapper div
  806. function ensureLineWrapped(lineView) {
  807. if (lineView.node == lineView.text) {
  808. lineView.node = elt("div", null, null, "position: relative");
  809. if (lineView.text.parentNode)
  810. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  811. lineView.node.appendChild(lineView.text);
  812. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  813. }
  814. return lineView.node;
  815. }
  816. function updateLineBackground(lineView) {
  817. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  818. if (cls) cls += " CodeMirror-linebackground";
  819. if (lineView.background) {
  820. if (cls) lineView.background.className = cls;
  821. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  822. } else if (cls) {
  823. var wrap = ensureLineWrapped(lineView);
  824. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  825. }
  826. }
  827. // Wrapper around buildLineContent which will reuse the structure
  828. // in display.externalMeasured when possible.
  829. function getLineContent(cm, lineView) {
  830. var ext = cm.display.externalMeasured;
  831. if (ext && ext.line == lineView.line) {
  832. cm.display.externalMeasured = null;
  833. lineView.measure = ext.measure;
  834. return ext.built;
  835. }
  836. return buildLineContent(cm, lineView);
  837. }
  838. // Redraw the line's text. Interacts with the background and text
  839. // classes because the mode may output tokens that influence these
  840. // classes.
  841. function updateLineText(cm, lineView) {
  842. var cls = lineView.text.className;
  843. var built = getLineContent(cm, lineView);
  844. if (lineView.text == lineView.node) lineView.node = built.pre;
  845. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  846. lineView.text = built.pre;
  847. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  848. lineView.bgClass = built.bgClass;
  849. lineView.textClass = built.textClass;
  850. updateLineClasses(lineView);
  851. } else if (cls) {
  852. lineView.text.className = cls;
  853. }
  854. }
  855. function updateLineClasses(lineView) {
  856. updateLineBackground(lineView);
  857. if (lineView.line.wrapClass)
  858. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  859. else if (lineView.node != lineView.text)
  860. lineView.node.className = "";
  861. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  862. lineView.text.className = textClass || "";
  863. }
  864. function updateLineGutter(cm, lineView, lineN, dims) {
  865. if (lineView.gutter) {
  866. lineView.node.removeChild(lineView.gutter);
  867. lineView.gutter = null;
  868. }
  869. var markers = lineView.line.gutterMarkers;
  870. if (cm.options.lineNumbers || markers) {
  871. var wrap = ensureLineWrapped(lineView);
  872. var gutterWrap = lineView.gutter =
  873. wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  874. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  875. "px; width: " + dims.gutterTotalWidth + "px"),
  876. lineView.text);
  877. if (lineView.line.gutterClass)
  878. gutterWrap.className += " " + lineView.line.gutterClass;
  879. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  880. lineView.lineNumber = gutterWrap.appendChild(
  881. elt("div", lineNumberFor(cm.options, lineN),
  882. "CodeMirror-linenumber CodeMirror-gutter-elt",
  883. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  884. + cm.display.lineNumInnerWidth + "px"));
  885. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  886. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  887. if (found)
  888. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  889. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  890. }
  891. }
  892. }
  893. function updateLineWidgets(lineView, dims) {
  894. if (lineView.alignable) lineView.alignable = null;
  895. for (var node = lineView.node.firstChild, next; node; node = next) {
  896. var next = node.nextSibling;
  897. if (node.className == "CodeMirror-linewidget")
  898. lineView.node.removeChild(node);
  899. }
  900. insertLineWidgets(lineView, dims);
  901. }
  902. // Build a line's DOM representation from scratch
  903. function buildLineElement(cm, lineView, lineN, dims) {
  904. var built = getLineContent(cm, lineView);
  905. lineView.text = lineView.node = built.pre;
  906. if (built.bgClass) lineView.bgClass = built.bgClass;
  907. if (built.textClass) lineView.textClass = built.textClass;
  908. updateLineClasses(lineView);
  909. updateLineGutter(cm, lineView, lineN, dims);
  910. insertLineWidgets(lineView, dims);
  911. return lineView.node;
  912. }
  913. // A lineView may contain multiple logical lines (when merged by
  914. // collapsed spans). The widgets for all of them need to be drawn.
  915. function insertLineWidgets(lineView, dims) {
  916. insertLineWidgetsFor(lineView.line, lineView, dims, true);
  917. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  918. insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);
  919. }
  920. function insertLineWidgetsFor(line, lineView, dims, allowAbove) {
  921. if (!line.widgets) return;
  922. var wrap = ensureLineWrapped(lineView);
  923. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  924. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  925. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  926. positionLineWidget(widget, node, lineView, dims);
  927. if (allowAbove && widget.above)
  928. wrap.insertBefore(node, lineView.gutter || lineView.text);
  929. else
  930. wrap.appendChild(node);
  931. signalLater(widget, "redraw");
  932. }
  933. }
  934. function positionLineWidget(widget, node, lineView, dims) {
  935. if (widget.noHScroll) {
  936. (lineView.alignable || (lineView.alignable = [])).push(node);
  937. var width = dims.wrapperWidth;
  938. node.style.left = dims.fixedPos + "px";
  939. if (!widget.coverGutter) {
  940. width -= dims.gutterTotalWidth;
  941. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  942. }
  943. node.style.width = width + "px";
  944. }
  945. if (widget.coverGutter) {
  946. node.style.zIndex = 5;
  947. node.style.position = "relative";
  948. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  949. }
  950. }
  951. // POSITION OBJECT
  952. // A Pos instance represents a position within the text.
  953. var Pos = CodeMirror.Pos = function(line, ch) {
  954. if (!(this instanceof Pos)) return new Pos(line, ch);
  955. this.line = line; this.ch = ch;
  956. };
  957. // Compare two positions, return 0 if they are the same, a negative
  958. // number when a is less, and a positive number otherwise.
  959. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  960. function copyPos(x) {return Pos(x.line, x.ch);}
  961. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  962. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  963. // SELECTION / CURSOR
  964. // Selection objects are immutable. A new one is created every time
  965. // the selection changes. A selection is one or more non-overlapping
  966. // (and non-touching) ranges, sorted, and an integer that indicates
  967. // which one is the primary selection (the one that's scrolled into
  968. // view, that getCursor returns, etc).
  969. function Selection(ranges, primIndex) {
  970. this.ranges = ranges;
  971. this.primIndex = primIndex;
  972. }
  973. Selection.prototype = {
  974. primary: function() { return this.ranges[this.primIndex]; },
  975. equals: function(other) {
  976. if (other == this) return true;
  977. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  978. for (var i = 0; i < this.ranges.length; i++) {
  979. var here = this.ranges[i], there = other.ranges[i];
  980. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  981. }
  982. return true;
  983. },
  984. deepCopy: function() {
  985. for (var out = [], i = 0; i < this.ranges.length; i++)
  986. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  987. return new Selection(out, this.primIndex);
  988. },
  989. somethingSelected: function() {
  990. for (var i = 0; i < this.ranges.length; i++)
  991. if (!this.ranges[i].empty()) return true;
  992. return false;
  993. },
  994. contains: function(pos, end) {
  995. if (!end) end = pos;
  996. for (var i = 0; i < this.ranges.length; i++) {
  997. var range = this.ranges[i];
  998. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  999. return i;
  1000. }
  1001. return -1;
  1002. }
  1003. };
  1004. function Range(anchor, head) {
  1005. this.anchor = anchor; this.head = head;
  1006. }
  1007. Range.prototype = {
  1008. from: function() { return minPos(this.anchor, this.head); },
  1009. to: function() { return maxPos(this.anchor, this.head); },
  1010. empty: function() {
  1011. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1012. }
  1013. };
  1014. // Take an unsorted, potentially overlapping set of ranges, and
  1015. // build a selection out of it. 'Consumes' ranges array (modifying
  1016. // it).
  1017. function normalizeSelection(ranges, primIndex) {
  1018. var prim = ranges[primIndex];
  1019. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1020. primIndex = indexOf(ranges, prim);
  1021. for (var i = 1; i < ranges.length; i++) {
  1022. var cur = ranges[i], prev = ranges[i - 1];
  1023. if (cmp(prev.to(), cur.from()) >= 0) {
  1024. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1025. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1026. if (i <= primIndex) --primIndex;
  1027. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1028. }
  1029. }
  1030. return new Selection(ranges, primIndex);
  1031. }
  1032. function simpleSelection(anchor, head) {
  1033. return new Selection([new Range(anchor, head || anchor)], 0);
  1034. }
  1035. // Most of the external API clips given positions to make sure they
  1036. // actually exist within the document.
  1037. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1038. function clipPos(doc, pos) {
  1039. if (pos.line < doc.first) return Pos(doc.first, 0);
  1040. var last = doc.first + doc.size - 1;
  1041. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1042. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1043. }
  1044. function clipToLen(pos, linelen) {
  1045. var ch = pos.ch;
  1046. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1047. else if (ch < 0) return Pos(pos.line, 0);
  1048. else return pos;
  1049. }
  1050. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1051. function clipPosArray(doc, array) {
  1052. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1053. return out;
  1054. }
  1055. // SELECTION UPDATES
  1056. // The 'scroll' parameter given to many of these indicated whether
  1057. // the new cursor position should be scrolled into view after
  1058. // modifying the selection.
  1059. // If shift is held or the extend flag is set, extends a range to
  1060. // include a given position (and optionally a second position).
  1061. // Otherwise, simply returns the range between the given positions.
  1062. // Used for cursor motion and such.
  1063. function extendRange(doc, range, head, other) {
  1064. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1065. var anchor = range.anchor;
  1066. if (other) {
  1067. var posBefore = cmp(head, anchor) < 0;
  1068. if (posBefore != (cmp(other, anchor) < 0)) {
  1069. anchor = head;
  1070. head = other;
  1071. } else if (posBefore != (cmp(head, other) < 0)) {
  1072. head = other;
  1073. }
  1074. }
  1075. return new Range(anchor, head);
  1076. } else {
  1077. return new Range(other || head, head);
  1078. }
  1079. }
  1080. // Extend the primary selection range, discard the rest.
  1081. function extendSelection(doc, head, other, options) {
  1082. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1083. }
  1084. // Extend all selections (pos is an array of selections with length
  1085. // equal the number of selections)
  1086. function extendSelections(doc, heads, options) {
  1087. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1088. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1089. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1090. setSelection(doc, newSel, options);
  1091. }
  1092. // Updates a single range in the selection.
  1093. function replaceOneSelection(doc, i, range, options) {
  1094. var ranges = doc.sel.ranges.slice(0);
  1095. ranges[i] = range;
  1096. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1097. }
  1098. // Reset the selection to a single range.
  1099. function setSimpleSelection(doc, anchor, head, options) {
  1100. setSelection(doc, simpleSelection(anchor, head), options);
  1101. }
  1102. // Give beforeSelectionChange handlers a change to influence a
  1103. // selection update.
  1104. function filterSelectionChange(doc, sel) {
  1105. var obj = {
  1106. ranges: sel.ranges,
  1107. update: function(ranges) {
  1108. this.ranges = [];
  1109. for (var i = 0; i < ranges.length; i++)
  1110. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1111. clipPos(doc, ranges[i].head));
  1112. }
  1113. };
  1114. signal(doc, "beforeSelectionChange", doc, obj);
  1115. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1116. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1117. else return sel;
  1118. }
  1119. function setSelectionReplaceHistory(doc, sel, options) {
  1120. var done = doc.history.done, last = lst(done);
  1121. if (last && last.ranges) {
  1122. done[done.length - 1] = sel;
  1123. setSelectionNoUndo(doc, sel, options);
  1124. } else {
  1125. setSelection(doc, sel, options);
  1126. }
  1127. }
  1128. // Set a new selection.
  1129. function setSelection(doc, sel, options) {
  1130. setSelectionNoUndo(doc, sel, options);
  1131. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1132. }
  1133. function setSelectionNoUndo(doc, sel, options) {
  1134. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1135. sel = filterSelectionChange(doc, sel);
  1136. var bias = options && options.bias ||
  1137. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1138. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1139. if (!(options && options.scroll === false) && doc.cm)
  1140. ensureCursorVisible(doc.cm);
  1141. }
  1142. function setSelectionInner(doc, sel) {
  1143. if (sel.equals(doc.sel)) return;
  1144. doc.sel = sel;
  1145. if (doc.cm) {
  1146. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1147. signalCursorActivity(doc.cm);
  1148. }
  1149. signalLater(doc, "cursorActivity", doc);
  1150. }
  1151. // Verify that the selection does not partially select any atomic
  1152. // marked ranges.
  1153. function reCheckSelection(doc) {
  1154. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1155. }
  1156. // Return a selection that does not partially select any atomic
  1157. // ranges.
  1158. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1159. var out;
  1160. for (var i = 0; i < sel.ranges.length; i++) {
  1161. var range = sel.ranges[i];
  1162. var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
  1163. var newHead = skipAtomic(doc, range.head, bias, mayClear);
  1164. if (out || newAnchor != range.anchor || newHead != range.head) {
  1165. if (!out) out = sel.ranges.slice(0, i);
  1166. out[i] = new Range(newAnchor, newHead);
  1167. }
  1168. }
  1169. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1170. }
  1171. // Ensure a given position is not inside an atomic range.
  1172. function skipAtomic(doc, pos, bias, mayClear) {
  1173. var flipped = false, curPos = pos;
  1174. var dir = bias || 1;
  1175. doc.cantEdit = false;
  1176. search: for (;;) {
  1177. var line = getLine(doc, curPos.line);
  1178. if (line.markedSpans) {
  1179. for (var i = 0; i < line.markedSpans.length; ++i) {
  1180. var sp = line.markedSpans[i], m = sp.marker;
  1181. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  1182. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  1183. if (mayClear) {
  1184. signal(m, "beforeCursorEnter");
  1185. if (m.explicitlyCleared) {
  1186. if (!line.markedSpans) break;
  1187. else {--i; continue;}
  1188. }
  1189. }
  1190. if (!m.atomic) continue;
  1191. var newPos = m.find(dir < 0 ? -1 : 1);
  1192. if (cmp(newPos, curPos) == 0) {
  1193. newPos.ch += dir;
  1194. if (newPos.ch < 0) {
  1195. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  1196. else newPos = null;
  1197. } else if (newPos.ch > line.text.length) {
  1198. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  1199. else newPos = null;
  1200. }
  1201. if (!newPos) {
  1202. if (flipped) {
  1203. // Driven in a corner -- no valid cursor position found at all
  1204. // -- try again *with* clearing, if we didn't already
  1205. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  1206. // Otherwise, turn off editing until further notice, and return the start of the doc
  1207. doc.cantEdit = true;
  1208. return Pos(doc.first, 0);
  1209. }
  1210. flipped = true; newPos = pos; dir = -dir;
  1211. }
  1212. }
  1213. curPos = newPos;
  1214. continue search;
  1215. }
  1216. }
  1217. }
  1218. return curPos;
  1219. }
  1220. }
  1221. // SELECTION DRAWING
  1222. // Redraw the selection and/or cursor
  1223. function drawSelection(cm) {
  1224. var display = cm.display, doc = cm.doc, result = {};
  1225. var curFragment = result.cursors = document.createDocumentFragment();
  1226. var selFragment = result.selection = document.createDocumentFragment();
  1227. for (var i = 0; i < doc.sel.ranges.length; i++) {
  1228. var range = doc.sel.ranges[i];
  1229. var collapsed = range.empty();
  1230. if (collapsed || cm.options.showCursorWhenSelecting)
  1231. drawSelectionCursor(cm, range, curFragment);
  1232. if (!collapsed)
  1233. drawSelectionRange(cm, range, selFragment);
  1234. }
  1235. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1236. if (cm.options.moveInputWithCursor) {
  1237. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1238. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1239. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1240. headPos.top + lineOff.top - wrapOff.top));
  1241. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1242. headPos.left + lineOff.left - wrapOff.left));
  1243. }
  1244. return result;
  1245. }
  1246. function showSelection(cm, drawn) {
  1247. removeChildrenAndAdd(cm.display.cursorDiv, drawn.cursors);
  1248. removeChildrenAndAdd(cm.display.selectionDiv, drawn.selection);
  1249. if (drawn.teTop != null) {
  1250. cm.display.inputDiv.style.top = drawn.teTop + "px";
  1251. cm.display.inputDiv.style.left = drawn.teLeft + "px";
  1252. }
  1253. }
  1254. function updateSelection(cm) {
  1255. showSelection(cm, drawSelection(cm));
  1256. }
  1257. // Draws a cursor for the given range
  1258. function drawSelectionCursor(cm, range, output) {
  1259. var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  1260. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  1261. cursor.style.left = pos.left + "px";
  1262. cursor.style.top = pos.top + "px";
  1263. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  1264. if (pos.other) {
  1265. // Secondary cursor, shown when on a 'jump' in bi-directional text
  1266. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  1267. otherCursor.style.display = "";
  1268. otherCursor.style.left = pos.other.left + "px";
  1269. otherCursor.style.top = pos.other.top + "px";
  1270. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  1271. }
  1272. }
  1273. // Draws the given range as a highlighted selection
  1274. function drawSelectionRange(cm, range, output) {
  1275. var display = cm.display, doc = cm.doc;
  1276. var fragment = document.createDocumentFragment();
  1277. var padding = paddingH(cm.display), leftSide = padding.left;
  1278. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  1279. function add(left, top, width, bottom) {
  1280. if (top < 0) top = 0;
  1281. top = Math.round(top);
  1282. bottom = Math.round(bottom);
  1283. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  1284. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  1285. "px; height: " + (bottom - top) + "px"));
  1286. }
  1287. function drawForLine(line, fromArg, toArg) {
  1288. var lineObj = getLine(doc, line);
  1289. var lineLen = lineObj.text.length;
  1290. var start, end;
  1291. function coords(ch, bias) {
  1292. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  1293. }
  1294. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  1295. var leftPos = coords(from, "left"), rightPos, left, right;
  1296. if (from == to) {
  1297. rightPos = leftPos;
  1298. left = right = leftPos.left;
  1299. } else {
  1300. rightPos = coords(to - 1, "right");
  1301. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  1302. left = leftPos.left;
  1303. right = rightPos.right;
  1304. }
  1305. if (fromArg == null && from == 0) left = leftSide;
  1306. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  1307. add(left, leftPos.top, null, leftPos.bottom);
  1308. left = leftSide;
  1309. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  1310. }
  1311. if (toArg == null && to == lineLen) right = rightSide;
  1312. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  1313. start = leftPos;
  1314. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  1315. end = rightPos;
  1316. if (left < leftSide + 1) left = leftSide;
  1317. add(left, rightPos.top, right - left, rightPos.bottom);
  1318. });
  1319. return {start: start, end: end};
  1320. }
  1321. var sFrom = range.from(), sTo = range.to();
  1322. if (sFrom.line == sTo.line) {
  1323. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  1324. } else {
  1325. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  1326. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  1327. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  1328. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  1329. if (singleVLine) {
  1330. if (leftEnd.top < rightStart.top - 2) {
  1331. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  1332. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  1333. } else {
  1334. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  1335. }
  1336. }
  1337. if (leftEnd.bottom < rightStart.top)
  1338. add(leftSide, leftEnd.bottom, null, rightStart.top);
  1339. }
  1340. output.appendChild(fragment);
  1341. }
  1342. // Cursor-blinking
  1343. function restartBlink(cm) {
  1344. if (!cm.state.focused) return;
  1345. var display = cm.display;
  1346. clearInterval(display.blinker);
  1347. var on = true;
  1348. display.cursorDiv.style.visibility = "";
  1349. if (cm.options.cursorBlinkRate > 0)
  1350. display.blinker = setInterval(function() {
  1351. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  1352. }, cm.options.cursorBlinkRate);
  1353. else if (cm.options.cursorBlinkRate < 0)
  1354. display.cursorDiv.style.visibility = "hidden";
  1355. }
  1356. // HIGHLIGHT WORKER
  1357. function startWorker(cm, time) {
  1358. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  1359. cm.state.highlight.set(time, bind(highlightWorker, cm));
  1360. }
  1361. function highlightWorker(cm) {
  1362. var doc = cm.doc;
  1363. if (doc.frontier < doc.first) doc.frontier = doc.first;
  1364. if (doc.frontier >= cm.display.viewTo) return;
  1365. var end = +new Date + cm.options.workTime;
  1366. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  1367. var changedLines = [];
  1368. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  1369. if (doc.frontier >= cm.display.viewFrom) { // Visible
  1370. var oldStyles = line.styles;
  1371. var highlighted = highlightLine(cm, line, state, true);
  1372. line.styles = highlighted.styles;
  1373. var oldCls = line.styleClasses, newCls = highlighted.classes;
  1374. if (newCls) line.styleClasses = newCls;
  1375. else if (oldCls) line.styleClasses = null;
  1376. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  1377. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  1378. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  1379. if (ischange) changedLines.push(doc.frontier);
  1380. line.stateAfter = copyState(doc.mode, state);
  1381. } else {
  1382. processLine(cm, line.text, state);
  1383. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  1384. }
  1385. ++doc.frontier;
  1386. if (+new Date > end) {
  1387. startWorker(cm, cm.options.workDelay);
  1388. return true;
  1389. }
  1390. });
  1391. if (changedLines.length) runInOp(cm, function() {
  1392. for (var i = 0; i < changedLines.length; i++)
  1393. regLineChange(cm, changedLines[i], "text");
  1394. });
  1395. }
  1396. // Finds the line to start with when starting a parse. Tries to
  1397. // find a line with a stateAfter, so that it can start with a
  1398. // valid state. If that fails, it returns the line with the
  1399. // smallest indentation, which tends to need the least context to
  1400. // parse correctly.
  1401. function findStartLine(cm, n, precise) {
  1402. var minindent, minline, doc = cm.doc;
  1403. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1404. for (var search = n; search > lim; --search) {
  1405. if (search <= doc.first) return doc.first;
  1406. var line = getLine(doc, search - 1);
  1407. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  1408. var indented = countColumn(line.text, null, cm.options.tabSize);
  1409. if (minline == null || minindent > indented) {
  1410. minline = search - 1;
  1411. minindent = indented;
  1412. }
  1413. }
  1414. return minline;
  1415. }
  1416. function getStateBefore(cm, n, precise) {
  1417. var doc = cm.doc, display = cm.display;
  1418. if (!doc.mode.startState) return true;
  1419. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  1420. if (!state) state = startState(doc.mode);
  1421. else state = copyState(doc.mode, state);
  1422. doc.iter(pos, n, function(line) {
  1423. processLine(cm, line.text, state);
  1424. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  1425. line.stateAfter = save ? copyState(doc.mode, state) : null;
  1426. ++pos;
  1427. });
  1428. if (precise) doc.frontier = pos;
  1429. return state;
  1430. }
  1431. // POSITION MEASUREMENT
  1432. function paddingTop(display) {return display.lineSpace.offsetTop;}
  1433. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  1434. function paddingH(display) {
  1435. if (display.cachedPaddingH) return display.cachedPaddingH;
  1436. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  1437. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  1438. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  1439. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  1440. return data;
  1441. }
  1442. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  1443. function displayWidth(cm) {
  1444. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  1445. }
  1446. function displayHeight(cm) {
  1447. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  1448. }
  1449. // Ensure the lineView.wrapping.heights array is populated. This is
  1450. // an array of bottom offsets for the lines that make up a drawn
  1451. // line. When lineWrapping is on, there might be more than one
  1452. // height.
  1453. function ensureLineHeights(cm, lineView, rect) {
  1454. var wrapping = cm.options.lineWrapping;
  1455. var curWidth = wrapping && displayWidth(cm);
  1456. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  1457. var heights = lineView.measure.heights = [];
  1458. if (wrapping) {
  1459. lineView.measure.width = curWidth;
  1460. var rects = lineView.text.firstChild.getClientRects();
  1461. for (var i = 0; i < rects.length - 1; i++) {
  1462. var cur = rects[i], next = rects[i + 1];
  1463. if (Math.abs(cur.bottom - next.bottom) > 2)
  1464. heights.push((cur.bottom + next.top) / 2 - rect.top);
  1465. }
  1466. }
  1467. heights.push(rect.bottom - rect.top);
  1468. }
  1469. }
  1470. // Find a line map (mapping character offsets to text nodes) and a
  1471. // measurement cache for the given line number. (A line view might
  1472. // contain multiple lines when collapsed ranges are present.)
  1473. function mapFromLineView(lineView, line, lineN) {
  1474. if (lineView.line == line)
  1475. return {map: lineView.measure.map, cache: lineView.measure.cache};
  1476. for (var i = 0; i < lineView.rest.length; i++)
  1477. if (lineView.rest[i] == line)
  1478. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  1479. for (var i = 0; i < lineView.rest.length; i++)
  1480. if (lineNo(lineView.rest[i]) > lineN)
  1481. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  1482. }
  1483. // Render a line into the hidden node display.externalMeasured. Used
  1484. // when measurement is needed for a line that's not in the viewport.
  1485. function updateExternalMeasurement(cm, line) {
  1486. line = visualLine(line);
  1487. var lineN = lineNo(line);
  1488. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  1489. view.lineN = lineN;
  1490. var built = view.built = buildLineContent(cm, view);
  1491. view.text = built.pre;
  1492. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  1493. return view;
  1494. }
  1495. // Get a {top, bottom, left, right} box (in line-local coordinates)
  1496. // for a given character.
  1497. function measureChar(cm, line, ch, bias) {
  1498. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  1499. }
  1500. // Find a line view that corresponds to the given line number.
  1501. function findViewForLine(cm, lineN) {
  1502. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  1503. return cm.display.view[findViewIndex(cm, lineN)];
  1504. var ext = cm.display.externalMeasured;
  1505. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  1506. return ext;
  1507. }
  1508. // Measurement can be split in two steps, the set-up work that
  1509. // applies to the whole line, and the measurement of the actual
  1510. // character. Functions like coordsChar, that need to do a lot of
  1511. // measurements in a row, can thus ensure that the set-up work is
  1512. // only done once.
  1513. function prepareMeasureForLine(cm, line) {
  1514. var lineN = lineNo(line);
  1515. var view = findViewForLine(cm, lineN);
  1516. if (view && !view.text)
  1517. view = null;
  1518. else if (view && view.changes)
  1519. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  1520. if (!view)
  1521. view = updateExternalMeasurement(cm, line);
  1522. var info = mapFromLineView(view, line, lineN);
  1523. return {
  1524. line: line, view: view, rect: null,
  1525. map: info.map, cache: info.cache, before: info.before,
  1526. hasHeights: false
  1527. };
  1528. }
  1529. // Given a prepared measurement object, measures the position of an
  1530. // actual character (or fetches it from the cache).
  1531. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  1532. if (prepared.before) ch = -1;
  1533. var key = ch + (bias || ""), found;
  1534. if (prepared.cache.hasOwnProperty(key)) {
  1535. found = prepared.cache[key];
  1536. } else {
  1537. if (!prepared.rect)
  1538. prepared.rect = prepared.view.text.getBoundingClientRect();
  1539. if (!prepared.hasHeights) {
  1540. ensureLineHeights(cm, prepared.view, prepared.rect);
  1541. prepared.hasHeights = true;
  1542. }
  1543. found = measureCharInner(cm, prepared, ch, bias);
  1544. if (!found.bogus) prepared.cache[key] = found;
  1545. }
  1546. return {left: found.left, right: found.right,
  1547. top: varHeight ? found.rtop : found.top,
  1548. bottom: varHeight ? found.rbottom : found.bottom};
  1549. }
  1550. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  1551. function measureCharInner(cm, prepared, ch, bias) {
  1552. var map = prepared.map;
  1553. var node, start, end, collapse;
  1554. // First, search the line map for the text node corresponding to,
  1555. // or closest to, the target character.
  1556. for (var i = 0; i < map.length; i += 3) {
  1557. var mStart = map[i], mEnd = map[i + 1];
  1558. if (ch < mStart) {
  1559. start = 0; end = 1;
  1560. collapse = "left";
  1561. } else if (ch < mEnd) {
  1562. start = ch - mStart;
  1563. end = start + 1;
  1564. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  1565. end = mEnd - mStart;
  1566. start = end - 1;
  1567. if (ch >= mEnd) collapse = "right";
  1568. }
  1569. if (start != null) {
  1570. node = map[i + 2];
  1571. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  1572. collapse = bias;
  1573. if (bias == "left" && start == 0)
  1574. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  1575. node = map[(i -= 3) + 2];
  1576. collapse = "left";
  1577. }
  1578. if (bias == "right" && start == mEnd - mStart)
  1579. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  1580. node = map[(i += 3) + 2];
  1581. collapse = "right";
  1582. }
  1583. break;
  1584. }
  1585. }
  1586. var rect;
  1587. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  1588. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  1589. while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;
  1590. while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;
  1591. if (ie && ie_version < 9 && start == 0 && end == mEnd - mStart) {
  1592. rect = node.parentNode.getBoundingClientRect();
  1593. } else if (ie && cm.options.lineWrapping) {
  1594. var rects = range(node, start, end).getClientRects();
  1595. if (rects.length)
  1596. rect = rects[bias == "right" ? rects.length - 1 : 0];
  1597. else
  1598. rect = nullRect;
  1599. } else {
  1600. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  1601. }
  1602. if (rect.left || rect.right || start == 0) break;
  1603. end = start;
  1604. start = start - 1;
  1605. collapse = "right";
  1606. }
  1607. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  1608. } else { // If it is a widget, simply get the box for the whole widget.
  1609. if (start > 0) collapse = bias = "right";
  1610. var rects;
  1611. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  1612. rect = rects[bias == "right" ? rects.length - 1 : 0];
  1613. else
  1614. rect = node.getBoundingClientRect();
  1615. }
  1616. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  1617. var rSpan = node.parentNode.getClientRects()[0];
  1618. if (rSpan)
  1619. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  1620. else
  1621. rect = nullRect;
  1622. }
  1623. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  1624. var mid = (rtop + rbot) / 2;
  1625. var heights = prepared.view.measure.heights;
  1626. for (var i = 0; i < heights.length - 1; i++)
  1627. if (mid < heights[i]) break;
  1628. var top = i ? heights[i - 1] : 0, bot = heights[i];
  1629. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  1630. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  1631. top: top, bottom: bot};
  1632. if (!rect.left && !rect.right) result.bogus = true;
  1633. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  1634. return result;
  1635. }
  1636. // Work around problem with bounding client rects on ranges being
  1637. // returned incorrectly when zoomed on IE10 and below.
  1638. function maybeUpdateRectForZooming(measure, rect) {
  1639. if (!window.screen || screen.logicalXDPI == null ||
  1640. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  1641. return rect;
  1642. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  1643. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  1644. return {left: rect.left * scaleX, right: rect.right * scaleX,
  1645. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  1646. }
  1647. function clearLineMeasurementCacheFor(lineView) {
  1648. if (lineView.measure) {
  1649. lineView.measure.cache = {};
  1650. lineView.measure.heights = null;
  1651. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  1652. lineView.measure.caches[i] = {};
  1653. }
  1654. }
  1655. function clearLineMeasurementCache(cm) {
  1656. cm.display.externalMeasure = null;
  1657. removeChildren(cm.display.lineMeasure);
  1658. for (var i = 0; i < cm.display.view.length; i++)
  1659. clearLineMeasurementCacheFor(cm.display.view[i]);
  1660. }
  1661. function clearCaches(cm) {
  1662. clearLineMeasurementCache(cm);
  1663. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  1664. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  1665. cm.display.lineNumChars = null;
  1666. }
  1667. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  1668. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  1669. // Converts a {top, bottom, left, right} box from line-local
  1670. // coordinates into another coordinate system. Context may be one of
  1671. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  1672. // or "page".
  1673. function intoCoordSystem(cm, lineObj, rect, context) {
  1674. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  1675. var size = widgetHeight(lineObj.widgets[i]);
  1676. rect.top += size; rect.bottom += size;
  1677. }
  1678. if (context == "line") return rect;
  1679. if (!context) context = "local";
  1680. var yOff = heightAtLine(lineObj);
  1681. if (context == "local") yOff += paddingTop(cm.display);
  1682. else yOff -= cm.display.viewOffset;
  1683. if (context == "page" || context == "window") {
  1684. var lOff = cm.display.lineSpace.getBoundingClientRect();
  1685. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  1686. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  1687. rect.left += xOff; rect.right += xOff;
  1688. }
  1689. rect.top += yOff; rect.bottom += yOff;
  1690. return rect;
  1691. }
  1692. // Coverts a box from "div" coords to another coordinate system.
  1693. // Context may be "window", "page", "div", or "local"/null.
  1694. function fromCoordSystem(cm, coords, context) {
  1695. if (context == "div") return coords;
  1696. var left = coords.left, top = coords.top;
  1697. // First move into "page" coordinate system
  1698. if (context == "page") {
  1699. left -= pageScrollX();
  1700. top -= pageScrollY();
  1701. } else if (context == "local" || !context) {
  1702. var localBox = cm.display.sizer.getBoundingClientRect();
  1703. left += localBox.left;
  1704. top += localBox.top;
  1705. }
  1706. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  1707. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  1708. }
  1709. function charCoords(cm, pos, context, lineObj, bias) {
  1710. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  1711. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  1712. }
  1713. // Returns a box for a given cursor position, which may have an
  1714. // 'other' property containing the position of the secondary cursor
  1715. // on a bidi boundary.
  1716. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  1717. lineObj = lineObj || getLine(cm.doc, pos.line);
  1718. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  1719. function get(ch, right) {
  1720. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  1721. if (right) m.left = m.right; else m.right = m.left;
  1722. return intoCoordSystem(cm, lineObj, m, context);
  1723. }
  1724. function getBidi(ch, partPos) {
  1725. var part = order[partPos], right = part.level % 2;
  1726. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  1727. part = order[--partPos];
  1728. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  1729. right = true;
  1730. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  1731. part = order[++partPos];
  1732. ch = bidiLeft(part) - part.level % 2;
  1733. right = false;
  1734. }
  1735. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  1736. return get(ch, right);
  1737. }
  1738. var order = getOrder(lineObj), ch = pos.ch;
  1739. if (!order) return get(ch);
  1740. var partPos = getBidiPartAt(order, ch);
  1741. var val = getBidi(ch, partPos);
  1742. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  1743. return val;
  1744. }
  1745. // Used to cheaply estimate the coordinates for a position. Used for
  1746. // intermediate scroll updates.
  1747. function estimateCoords(cm, pos) {
  1748. var left = 0, pos = clipPos(cm.doc, pos);
  1749. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  1750. var lineObj = getLine(cm.doc, pos.line);
  1751. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  1752. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  1753. }
  1754. // Positions returned by coordsChar contain some extra information.
  1755. // xRel is the relative x position of the input coordinates compared
  1756. // to the found position (so xRel > 0 means the coordinates are to
  1757. // the right of the character position, for example). When outside
  1758. // is true, that means the coordinates lie outside the line's
  1759. // vertical range.
  1760. function PosWithInfo(line, ch, outside, xRel) {
  1761. var pos = Pos(line, ch);
  1762. pos.xRel = xRel;
  1763. if (outside) pos.outside = true;
  1764. return pos;
  1765. }
  1766. // Compute the character position closest to the given coordinates.
  1767. // Input must be lineSpace-local ("div" coordinate system).
  1768. function coordsChar(cm, x, y) {
  1769. var doc = cm.doc;
  1770. y += cm.display.viewOffset;
  1771. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  1772. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  1773. if (lineN > last)
  1774. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  1775. if (x < 0) x = 0;
  1776. var lineObj = getLine(doc, lineN);
  1777. for (;;) {
  1778. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  1779. var merged = collapsedSpanAtEnd(lineObj);
  1780. var mergedPos = merged && merged.find(0, true);
  1781. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  1782. lineN = lineNo(lineObj = mergedPos.to.line);
  1783. else
  1784. return found;
  1785. }
  1786. }
  1787. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  1788. var innerOff = y - heightAtLine(lineObj);
  1789. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  1790. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  1791. function getX(ch) {
  1792. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  1793. wrongLine = true;
  1794. if (innerOff > sp.bottom) return sp.left - adjust;
  1795. else if (innerOff < sp.top) return sp.left + adjust;
  1796. else wrongLine = false;
  1797. return sp.left;
  1798. }
  1799. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  1800. var from = lineLeft(lineObj), to = lineRight(lineObj);
  1801. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  1802. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  1803. // Do a binary search between these bounds.
  1804. for (;;) {
  1805. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  1806. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  1807. var xDiff = x - (ch == from ? fromX : toX);
  1808. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  1809. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  1810. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  1811. return pos;
  1812. }
  1813. var step = Math.ceil(dist / 2), middle = from + step;
  1814. if (bidi) {
  1815. middle = from;
  1816. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  1817. }
  1818. var middleX = getX(middle);
  1819. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  1820. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  1821. }
  1822. }
  1823. var measureText;
  1824. // Compute the default text height.
  1825. function textHeight(display) {
  1826. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  1827. if (measureText == null) {
  1828. measureText = elt("pre");
  1829. // Measure a bunch of lines, for browsers that compute
  1830. // fractional heights.
  1831. for (var i = 0; i < 49; ++i) {
  1832. measureText.appendChild(document.createTextNode("x"));
  1833. measureText.appendChild(elt("br"));
  1834. }
  1835. measureText.appendChild(document.createTextNode("x"));
  1836. }
  1837. removeChildrenAndAdd(display.measure, measureText);
  1838. var height = measureText.offsetHeight / 50;
  1839. if (height > 3) display.cachedTextHeight = height;
  1840. removeChildren(display.measure);
  1841. return height || 1;
  1842. }
  1843. // Compute the default character width.
  1844. function charWidth(display) {
  1845. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  1846. var anchor = elt("span", "xxxxxxxxxx");
  1847. var pre = elt("pre", [anchor]);
  1848. removeChildrenAndAdd(display.measure, pre);
  1849. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  1850. if (width > 2) display.cachedCharWidth = width;
  1851. return width || 10;
  1852. }
  1853. // OPERATIONS
  1854. // Operations are used to wrap a series of changes to the editor
  1855. // state in such a way that each change won't have to update the
  1856. // cursor and display (which would be awkward, slow, and
  1857. // error-prone). Instead, display updates are batched and then all
  1858. // combined and executed at once.
  1859. var operationGroup = null;
  1860. var nextOpId = 0;
  1861. // Start a new operation.
  1862. function startOperation(cm) {
  1863. cm.curOp = {
  1864. cm: cm,
  1865. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  1866. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  1867. forceUpdate: false, // Used to force a redraw
  1868. updateInput: null, // Whether to reset the input textarea
  1869. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  1870. changeObjs: null, // Accumulated changes, for firing change events
  1871. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  1872. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  1873. selectionChanged: false, // Whether the selection needs to be redrawn
  1874. updateMaxLine: false, // Set when the widest line needs to be determined anew
  1875. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  1876. scrollToPos: null, // Used to scroll to a specific position
  1877. id: ++nextOpId // Unique ID
  1878. };
  1879. if (operationGroup) {
  1880. operationGroup.ops.push(cm.curOp);
  1881. } else {
  1882. cm.curOp.ownsGroup = operationGroup = {
  1883. ops: [cm.curOp],
  1884. delayedCallbacks: []
  1885. };
  1886. }
  1887. }
  1888. function fireCallbacksForOps(group) {
  1889. // Calls delayed callbacks and cursorActivity handlers until no
  1890. // new ones appear
  1891. var callbacks = group.delayedCallbacks, i = 0;
  1892. do {
  1893. for (; i < callbacks.length; i++)
  1894. callbacks[i]();
  1895. for (var j = 0; j < group.ops.length; j++) {
  1896. var op = group.ops[j];
  1897. if (op.cursorActivityHandlers)
  1898. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1899. op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);
  1900. }
  1901. } while (i < callbacks.length);
  1902. }
  1903. // Finish an operation, updating the display and signalling delayed events
  1904. function endOperation(cm) {
  1905. var op = cm.curOp, group = op.ownsGroup;
  1906. if (!group) return;
  1907. try { fireCallbacksForOps(group); }
  1908. finally {
  1909. operationGroup = null;
  1910. for (var i = 0; i < group.ops.length; i++)
  1911. group.ops[i].cm.curOp = null;
  1912. endOperations(group);
  1913. }
  1914. }
  1915. // The DOM updates done when an operation finishes are batched so
  1916. // that the minimum number of relayouts are required.
  1917. function endOperations(group) {
  1918. var ops = group.ops;
  1919. for (var i = 0; i < ops.length; i++) // Read DOM
  1920. endOperation_R1(ops[i]);
  1921. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  1922. endOperation_W1(ops[i]);
  1923. for (var i = 0; i < ops.length; i++) // Read DOM
  1924. endOperation_R2(ops[i]);
  1925. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  1926. endOperation_W2(ops[i]);
  1927. for (var i = 0; i < ops.length; i++) // Read DOM
  1928. endOperation_finish(ops[i]);
  1929. }
  1930. function endOperation_R1(op) {
  1931. var cm = op.cm, display = cm.display;
  1932. maybeClipScrollbars(cm);
  1933. if (op.updateMaxLine) findMaxLine(cm);
  1934. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  1935. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  1936. op.scrollToPos.to.line >= display.viewTo) ||
  1937. display.maxLineChanged && cm.options.lineWrapping;
  1938. op.update = op.mustUpdate &&
  1939. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  1940. }
  1941. function endOperation_W1(op) {
  1942. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  1943. }
  1944. function endOperation_R2(op) {
  1945. var cm = op.cm, display = cm.display;
  1946. if (op.updatedDisplay) updateHeightsInViewport(cm);
  1947. op.barMeasure = measureForScrollbars(cm);
  1948. // If the max line changed since it was last measured, measure it,
  1949. // and ensure the document's width matches it.
  1950. // updateDisplay_W2 will use these properties to do the actual resizing
  1951. if (display.maxLineChanged && !cm.options.lineWrapping) {
  1952. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  1953. cm.display.sizerWidth = op.adjustWidthTo;
  1954. op.barMeasure.scrollWidth =
  1955. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  1956. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  1957. }
  1958. if (op.updatedDisplay || op.selectionChanged)
  1959. op.newSelectionNodes = drawSelection(cm);
  1960. }
  1961. function endOperation_W2(op) {
  1962. var cm = op.cm;
  1963. if (op.adjustWidthTo != null) {
  1964. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  1965. if (op.maxScrollLeft < cm.doc.scrollLeft)
  1966. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  1967. cm.display.maxLineChanged = false;
  1968. }
  1969. if (op.newSelectionNodes)
  1970. showSelection(cm, op.newSelectionNodes);
  1971. if (op.updatedDisplay)
  1972. setDocumentHeight(cm, op.barMeasure);
  1973. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  1974. updateScrollbars(cm, op.barMeasure);
  1975. if (op.selectionChanged) restartBlink(cm);
  1976. if (cm.state.focused && op.updateInput)
  1977. resetInput(cm, op.typing);
  1978. }
  1979. function endOperation_finish(op) {
  1980. var cm = op.cm, display = cm.display, doc = cm.doc;
  1981. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  1982. // Abort mouse wheel delta measurement, when scrolling explicitly
  1983. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  1984. display.wheelStartX = display.wheelStartY = null;
  1985. // Propagate the scroll position to the actual DOM scroller
  1986. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  1987. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  1988. display.scrollbars.setScrollTop(doc.scrollTop);
  1989. display.scroller.scrollTop = doc.scrollTop;
  1990. }
  1991. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  1992. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
  1993. display.scrollbars.setScrollLeft(doc.scrollLeft);
  1994. display.scroller.scrollLeft = doc.scrollLeft;
  1995. alignHorizontally(cm);
  1996. }
  1997. // If we need to scroll a specific position into view, do so.
  1998. if (op.scrollToPos) {
  1999. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2000. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2001. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2002. }
  2003. // Fire events for markers that are hidden/unidden by editing or
  2004. // undoing
  2005. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2006. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2007. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2008. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2009. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2010. if (display.wrapper.offsetHeight)
  2011. doc.scrollTop = cm.display.scroller.scrollTop;
  2012. // Fire change events, and delayed event handlers
  2013. if (op.changeObjs)
  2014. signal(cm, "changes", cm, op.changeObjs);
  2015. if (op.update)
  2016. op.update.finish();
  2017. }
  2018. // Run the given function in an operation
  2019. function runInOp(cm, f) {
  2020. if (cm.curOp) return f();
  2021. startOperation(cm);
  2022. try { return f(); }
  2023. finally { endOperation(cm); }
  2024. }
  2025. // Wraps a function in an operation. Returns the wrapped function.
  2026. function operation(cm, f) {
  2027. return function() {
  2028. if (cm.curOp) return f.apply(cm, arguments);
  2029. startOperation(cm);
  2030. try { return f.apply(cm, arguments); }
  2031. finally { endOperation(cm); }
  2032. };
  2033. }
  2034. // Used to add methods to editor and doc instances, wrapping them in
  2035. // operations.
  2036. function methodOp(f) {
  2037. return function() {
  2038. if (this.curOp) return f.apply(this, arguments);
  2039. startOperation(this);
  2040. try { return f.apply(this, arguments); }
  2041. finally { endOperation(this); }
  2042. };
  2043. }
  2044. function docMethodOp(f) {
  2045. return function() {
  2046. var cm = this.cm;
  2047. if (!cm || cm.curOp) return f.apply(this, arguments);
  2048. startOperation(cm);
  2049. try { return f.apply(this, arguments); }
  2050. finally { endOperation(cm); }
  2051. };
  2052. }
  2053. // VIEW TRACKING
  2054. // These objects are used to represent the visible (currently drawn)
  2055. // part of the document. A LineView may correspond to multiple
  2056. // logical lines, if those are connected by collapsed ranges.
  2057. function LineView(doc, line, lineN) {
  2058. // The starting line
  2059. this.line = line;
  2060. // Continuing lines, if any
  2061. this.rest = visualLineContinued(line);
  2062. // Number of logical lines in this visual line
  2063. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2064. this.node = this.text = null;
  2065. this.hidden = lineIsHidden(doc, line);
  2066. }
  2067. // Create a range of LineView objects for the given lines.
  2068. function buildViewArray(cm, from, to) {
  2069. var array = [], nextPos;
  2070. for (var pos = from; pos < to; pos = nextPos) {
  2071. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2072. nextPos = pos + view.size;
  2073. array.push(view);
  2074. }
  2075. return array;
  2076. }
  2077. // Updates the display.view data structure for a given change to the
  2078. // document. From and to are in pre-change coordinates. Lendiff is
  2079. // the amount of lines added or subtracted by the change. This is
  2080. // used for changes that span multiple lines, or change the way
  2081. // lines are divided into visual lines. regLineChange (below)
  2082. // registers single-line changes.
  2083. function regChange(cm, from, to, lendiff) {
  2084. if (from == null) from = cm.doc.first;
  2085. if (to == null) to = cm.doc.first + cm.doc.size;
  2086. if (!lendiff) lendiff = 0;
  2087. var display = cm.display;
  2088. if (lendiff && to < display.viewTo &&
  2089. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2090. display.updateLineNumbers = from;
  2091. cm.curOp.viewChanged = true;
  2092. if (from >= display.viewTo) { // Change after
  2093. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2094. resetView(cm);
  2095. } else if (to <= display.viewFrom) { // Change before
  2096. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2097. resetView(cm);
  2098. } else {
  2099. display.viewFrom += lendiff;
  2100. display.viewTo += lendiff;
  2101. }
  2102. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2103. resetView(cm);
  2104. } else if (from <= display.viewFrom) { // Top overlap
  2105. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2106. if (cut) {
  2107. display.view = display.view.slice(cut.index);
  2108. display.viewFrom = cut.lineN;
  2109. display.viewTo += lendiff;
  2110. } else {
  2111. resetView(cm);
  2112. }
  2113. } else if (to >= display.viewTo) { // Bottom overlap
  2114. var cut = viewCuttingPoint(cm, from, from, -1);
  2115. if (cut) {
  2116. display.view = display.view.slice(0, cut.index);
  2117. display.viewTo = cut.lineN;
  2118. } else {
  2119. resetView(cm);
  2120. }
  2121. } else { // Gap in the middle
  2122. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2123. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2124. if (cutTop && cutBot) {
  2125. display.view = display.view.slice(0, cutTop.index)
  2126. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2127. .concat(display.view.slice(cutBot.index));
  2128. display.viewTo += lendiff;
  2129. } else {
  2130. resetView(cm);
  2131. }
  2132. }
  2133. var ext = display.externalMeasured;
  2134. if (ext) {
  2135. if (to < ext.lineN)
  2136. ext.lineN += lendiff;
  2137. else if (from < ext.lineN + ext.size)
  2138. display.externalMeasured = null;
  2139. }
  2140. }
  2141. // Register a change to a single line. Type must be one of "text",
  2142. // "gutter", "class", "widget"
  2143. function regLineChange(cm, line, type) {
  2144. cm.curOp.viewChanged = true;
  2145. var display = cm.display, ext = cm.display.externalMeasured;
  2146. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2147. display.externalMeasured = null;
  2148. if (line < display.viewFrom || line >= display.viewTo) return;
  2149. var lineView = display.view[findViewIndex(cm, line)];
  2150. if (lineView.node == null) return;
  2151. var arr = lineView.changes || (lineView.changes = []);
  2152. if (indexOf(arr, type) == -1) arr.push(type);
  2153. }
  2154. // Clear the view.
  2155. function resetView(cm) {
  2156. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2157. cm.display.view = [];
  2158. cm.display.viewOffset = 0;
  2159. }
  2160. // Find the view element corresponding to a given line. Return null
  2161. // when the line isn't visible.
  2162. function findViewIndex(cm, n) {
  2163. if (n >= cm.display.viewTo) return null;
  2164. n -= cm.display.viewFrom;
  2165. if (n < 0) return null;
  2166. var view = cm.display.view;
  2167. for (var i = 0; i < view.length; i++) {
  2168. n -= view[i].size;
  2169. if (n < 0) return i;
  2170. }
  2171. }
  2172. function viewCuttingPoint(cm, oldN, newN, dir) {
  2173. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2174. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2175. return {index: index, lineN: newN};
  2176. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2177. n += view[i].size;
  2178. if (n != oldN) {
  2179. if (dir > 0) {
  2180. if (index == view.length - 1) return null;
  2181. diff = (n + view[index].size) - oldN;
  2182. index++;
  2183. } else {
  2184. diff = n - oldN;
  2185. }
  2186. oldN += diff; newN += diff;
  2187. }
  2188. while (visualLineNo(cm.doc, newN) != newN) {
  2189. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  2190. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2191. index += dir;
  2192. }
  2193. return {index: index, lineN: newN};
  2194. }
  2195. // Force the view to cover a given range, adding empty view element
  2196. // or clipping off existing ones as needed.
  2197. function adjustView(cm, from, to) {
  2198. var display = cm.display, view = display.view;
  2199. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2200. display.view = buildViewArray(cm, from, to);
  2201. display.viewFrom = from;
  2202. } else {
  2203. if (display.viewFrom > from)
  2204. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  2205. else if (display.viewFrom < from)
  2206. display.view = display.view.slice(findViewIndex(cm, from));
  2207. display.viewFrom = from;
  2208. if (display.viewTo < to)
  2209. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  2210. else if (display.viewTo > to)
  2211. display.view = display.view.slice(0, findViewIndex(cm, to));
  2212. }
  2213. display.viewTo = to;
  2214. }
  2215. // Count the number of lines in the view whose DOM representation is
  2216. // out of date (or nonexistent).
  2217. function countDirtyView(cm) {
  2218. var view = cm.display.view, dirty = 0;
  2219. for (var i = 0; i < view.length; i++) {
  2220. var lineView = view[i];
  2221. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  2222. }
  2223. return dirty;
  2224. }
  2225. // INPUT HANDLING
  2226. // Poll for input changes, using the normal rate of polling. This
  2227. // runs as long as the editor is focused.
  2228. function slowPoll(cm) {
  2229. if (cm.display.pollingFast) return;
  2230. cm.display.poll.set(cm.options.pollInterval, function() {
  2231. readInput(cm);
  2232. if (cm.state.focused) slowPoll(cm);
  2233. });
  2234. }
  2235. // When an event has just come in that is likely to add or change
  2236. // something in the input textarea, we poll faster, to ensure that
  2237. // the change appears on the screen quickly.
  2238. function fastPoll(cm) {
  2239. var missed = false;
  2240. cm.display.pollingFast = true;
  2241. function p() {
  2242. var changed = readInput(cm);
  2243. if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
  2244. else {cm.display.pollingFast = false; slowPoll(cm);}
  2245. }
  2246. cm.display.poll.set(20, p);
  2247. }
  2248. // This will be set to an array of strings when copying, so that,
  2249. // when pasting, we know what kind of selections the copied text
  2250. // was made out of.
  2251. var lastCopied = null;
  2252. // Read input from the textarea, and update the document to match.
  2253. // When something is selected, it is present in the textarea, and
  2254. // selected (unless it is huge, in which case a placeholder is
  2255. // used). When nothing is selected, the cursor sits after previously
  2256. // seen text (can be empty), which is stored in prevInput (we must
  2257. // not reset the textarea when typing, because that breaks IME).
  2258. function readInput(cm) {
  2259. var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;
  2260. // Since this is called a *lot*, try to bail out as cheaply as
  2261. // possible when it is clear that nothing happened. hasSelection
  2262. // will be the case when there is a lot of text in the textarea,
  2263. // in which case reading its value would be expensive.
  2264. if (!cm.state.focused || (hasSelection(input) && !prevInput) || isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
  2265. return false;
  2266. // See paste handler for more on the fakedLastChar kludge
  2267. if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
  2268. input.value = input.value.substring(0, input.value.length - 1);
  2269. cm.state.fakedLastChar = false;
  2270. }
  2271. var text = input.value;
  2272. // If nothing changed, bail.
  2273. if (text == prevInput && !cm.somethingSelected()) return false;
  2274. // Work around nonsensical selection resetting in IE9/10, and
  2275. // inexplicable appearance of private area unicode characters on
  2276. // some key combos in Mac (#2689).
  2277. if (ie && ie_version >= 9 && cm.display.inputHasSelection === text ||
  2278. mac && /[\uf700-\uf7ff]/.test(text)) {
  2279. resetInput(cm);
  2280. return false;
  2281. }
  2282. var withOp = !cm.curOp;
  2283. if (withOp) startOperation(cm);
  2284. cm.display.shift = false;
  2285. if (text.charCodeAt(0) == 0x200b && doc.sel == cm.display.selForContextMenu && !prevInput)
  2286. prevInput = "\u200b";
  2287. // Find the part of the input that is actually new
  2288. var same = 0, l = Math.min(prevInput.length, text.length);
  2289. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  2290. var inserted = text.slice(same), textLines = splitLines(inserted);
  2291. // When pasing N lines into N selections, insert one line per selection
  2292. var multiPaste = null;
  2293. if (cm.state.pasteIncoming && doc.sel.ranges.length > 1) {
  2294. if (lastCopied && lastCopied.join("\n") == inserted)
  2295. multiPaste = doc.sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);
  2296. else if (textLines.length == doc.sel.ranges.length)
  2297. multiPaste = map(textLines, function(l) { return [l]; });
  2298. }
  2299. // Normal behavior is to insert the new text into every selection
  2300. for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {
  2301. var range = doc.sel.ranges[i];
  2302. var from = range.from(), to = range.to();
  2303. // Handle deletion
  2304. if (same < prevInput.length)
  2305. from = Pos(from.line, from.ch - (prevInput.length - same));
  2306. // Handle overwrite
  2307. else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)
  2308. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  2309. var updateInput = cm.curOp.updateInput;
  2310. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  2311. origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
  2312. makeChange(cm.doc, changeEvent);
  2313. signalLater(cm, "inputRead", cm, changeEvent);
  2314. // When an 'electric' character is inserted, immediately trigger a reindent
  2315. if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
  2316. cm.options.smartIndent && range.head.ch < 100 &&
  2317. (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {
  2318. var mode = cm.getModeAt(range.head);
  2319. var end = changeEnd(changeEvent);
  2320. if (mode.electricChars) {
  2321. for (var j = 0; j < mode.electricChars.length; j++)
  2322. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  2323. indentLine(cm, end.line, "smart");
  2324. break;
  2325. }
  2326. } else if (mode.electricInput) {
  2327. if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))
  2328. indentLine(cm, end.line, "smart");
  2329. }
  2330. }
  2331. }
  2332. ensureCursorVisible(cm);
  2333. cm.curOp.updateInput = updateInput;
  2334. cm.curOp.typing = true;
  2335. // Don't leave long text in the textarea, since it makes further polling slow
  2336. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
  2337. else cm.display.prevInput = text;
  2338. if (withOp) endOperation(cm);
  2339. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  2340. return true;
  2341. }
  2342. // Reset the input to correspond to the selection (or to be empty,
  2343. // when not typing and nothing is selected)
  2344. function resetInput(cm, typing) {
  2345. if (cm.display.contextMenuPending) return;
  2346. var minimal, selected, doc = cm.doc;
  2347. if (cm.somethingSelected()) {
  2348. cm.display.prevInput = "";
  2349. var range = doc.sel.primary();
  2350. minimal = hasCopyEvent &&
  2351. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  2352. var content = minimal ? "-" : selected || cm.getSelection();
  2353. cm.display.input.value = content;
  2354. if (cm.state.focused) selectInput(cm.display.input);
  2355. if (ie && ie_version >= 9) cm.display.inputHasSelection = content;
  2356. } else if (!typing) {
  2357. cm.display.prevInput = cm.display.input.value = "";
  2358. if (ie && ie_version >= 9) cm.display.inputHasSelection = null;
  2359. }
  2360. cm.display.inaccurateSelection = minimal;
  2361. }
  2362. function focusInput(cm) {
  2363. if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input)) {
  2364. try { cm.display.input.focus(); }
  2365. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  2366. }
  2367. }
  2368. function ensureFocus(cm) {
  2369. if (!cm.state.focused) { focusInput(cm); onFocus(cm); }
  2370. }
  2371. function isReadOnly(cm) {
  2372. return cm.options.readOnly || cm.doc.cantEdit;
  2373. }
  2374. // EVENT HANDLERS
  2375. // Attach the necessary event handlers when initializing the editor
  2376. function registerEventHandlers(cm) {
  2377. var d = cm.display;
  2378. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  2379. // Older IE's will not fire a second mousedown for a double click
  2380. if (ie && ie_version < 11)
  2381. on(d.scroller, "dblclick", operation(cm, function(e) {
  2382. if (signalDOMEvent(cm, e)) return;
  2383. var pos = posFromMouse(cm, e);
  2384. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  2385. e_preventDefault(e);
  2386. var word = cm.findWordAt(pos);
  2387. extendSelection(cm.doc, word.anchor, word.head);
  2388. }));
  2389. else
  2390. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  2391. // Prevent normal selection in the editor (we handle our own)
  2392. on(d.lineSpace, "selectstart", function(e) {
  2393. if (!eventInWidget(d, e)) e_preventDefault(e);
  2394. });
  2395. // Some browsers fire contextmenu *after* opening the menu, at
  2396. // which point we can't mess with it anymore. Context menu is
  2397. // handled in onMouseDown for these browsers.
  2398. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  2399. // Sync scrolling between fake scrollbars and real scrollable
  2400. // area, ensure viewport is updated when scrolling.
  2401. on(d.scroller, "scroll", function() {
  2402. if (d.scroller.clientHeight) {
  2403. setScrollTop(cm, d.scroller.scrollTop);
  2404. setScrollLeft(cm, d.scroller.scrollLeft, true);
  2405. signal(cm, "scroll", cm);
  2406. }
  2407. });
  2408. // Listen to wheel events in order to try and update the viewport on time.
  2409. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  2410. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  2411. // Prevent wrapper from ever scrolling
  2412. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  2413. on(d.input, "keyup", function(e) { onKeyUp.call(cm, e); });
  2414. on(d.input, "input", function() {
  2415. if (ie && ie_version >= 9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
  2416. readInput(cm);
  2417. });
  2418. on(d.input, "keydown", operation(cm, onKeyDown));
  2419. on(d.input, "keypress", operation(cm, onKeyPress));
  2420. on(d.input, "focus", bind(onFocus, cm));
  2421. on(d.input, "blur", bind(onBlur, cm));
  2422. function drag_(e) {
  2423. if (!signalDOMEvent(cm, e)) e_stop(e);
  2424. }
  2425. if (cm.options.dragDrop) {
  2426. on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
  2427. on(d.scroller, "dragenter", drag_);
  2428. on(d.scroller, "dragover", drag_);
  2429. on(d.scroller, "drop", operation(cm, onDrop));
  2430. }
  2431. on(d.scroller, "paste", function(e) {
  2432. if (eventInWidget(d, e)) return;
  2433. cm.state.pasteIncoming = true;
  2434. focusInput(cm);
  2435. fastPoll(cm);
  2436. });
  2437. on(d.input, "paste", function() {
  2438. // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
  2439. // Add a char to the end of textarea before paste occur so that
  2440. // selection doesn't span to the end of textarea.
  2441. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
  2442. var start = d.input.selectionStart, end = d.input.selectionEnd;
  2443. d.input.value += "$";
  2444. // The selection end needs to be set before the start, otherwise there
  2445. // can be an intermediate non-empty selection between the two, which
  2446. // can override the middle-click paste buffer on linux and cause the
  2447. // wrong thing to get pasted.
  2448. d.input.selectionEnd = end;
  2449. d.input.selectionStart = start;
  2450. cm.state.fakedLastChar = true;
  2451. }
  2452. cm.state.pasteIncoming = true;
  2453. fastPoll(cm);
  2454. });
  2455. function prepareCopyCut(e) {
  2456. if (cm.somethingSelected()) {
  2457. lastCopied = cm.getSelections();
  2458. if (d.inaccurateSelection) {
  2459. d.prevInput = "";
  2460. d.inaccurateSelection = false;
  2461. d.input.value = lastCopied.join("\n");
  2462. selectInput(d.input);
  2463. }
  2464. } else {
  2465. var text = [], ranges = [];
  2466. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  2467. var line = cm.doc.sel.ranges[i].head.line;
  2468. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  2469. ranges.push(lineRange);
  2470. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  2471. }
  2472. if (e.type == "cut") {
  2473. cm.setSelections(ranges, null, sel_dontScroll);
  2474. } else {
  2475. d.prevInput = "";
  2476. d.input.value = text.join("\n");
  2477. selectInput(d.input);
  2478. }
  2479. lastCopied = text;
  2480. }
  2481. if (e.type == "cut") cm.state.cutIncoming = true;
  2482. }
  2483. on(d.input, "cut", prepareCopyCut);
  2484. on(d.input, "copy", prepareCopyCut);
  2485. // Needed to handle Tab key in KHTML
  2486. if (khtml) on(d.sizer, "mouseup", function() {
  2487. if (activeElt() == d.input) d.input.blur();
  2488. focusInput(cm);
  2489. });
  2490. }
  2491. // Called when the window resizes
  2492. function onResize(cm) {
  2493. var d = cm.display;
  2494. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  2495. return;
  2496. // Might be a text scaling operation, clear size caches.
  2497. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  2498. d.scrollbarsClipped = false;
  2499. cm.setSize();
  2500. }
  2501. // MOUSE EVENTS
  2502. // Return true when the given mouse event happened in a widget
  2503. function eventInWidget(display, e) {
  2504. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2505. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2506. (n.parentNode == display.sizer && n != display.mover))
  2507. return true;
  2508. }
  2509. }
  2510. // Given a mouse event, find the corresponding position. If liberal
  2511. // is false, it checks whether a gutter or scrollbar was clicked,
  2512. // and returns null if it was. forRect is used by rectangular
  2513. // selections, and tries to estimate a character position even for
  2514. // coordinates beyond the right of the text.
  2515. function posFromMouse(cm, e, liberal, forRect) {
  2516. var display = cm.display;
  2517. if (!liberal && e_target(e).getAttribute("not-content") == "true") return null;
  2518. var x, y, space = display.lineSpace.getBoundingClientRect();
  2519. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2520. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2521. catch (e) { return null; }
  2522. var coords = coordsChar(cm, x, y), line;
  2523. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2524. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2525. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2526. }
  2527. return coords;
  2528. }
  2529. // A mouse down can be a single click, double click, triple click,
  2530. // start of selection drag, start of text drag, new cursor
  2531. // (ctrl-click), rectangle drag (alt-drag), or xwin
  2532. // middle-click-paste. Or it might be a click on something we should
  2533. // not interfere with, such as a scrollbar or widget.
  2534. function onMouseDown(e) {
  2535. if (signalDOMEvent(this, e)) return;
  2536. var cm = this, display = cm.display;
  2537. display.shift = e.shiftKey;
  2538. if (eventInWidget(display, e)) {
  2539. if (!webkit) {
  2540. // Briefly turn off draggability, to allow widgets to do
  2541. // normal dragging things.
  2542. display.scroller.draggable = false;
  2543. setTimeout(function(){display.scroller.draggable = true;}, 100);
  2544. }
  2545. return;
  2546. }
  2547. if (clickInGutter(cm, e)) return;
  2548. var start = posFromMouse(cm, e);
  2549. window.focus();
  2550. switch (e_button(e)) {
  2551. case 1:
  2552. if (start)
  2553. leftButtonDown(cm, e, start);
  2554. else if (e_target(e) == display.scroller)
  2555. e_preventDefault(e);
  2556. break;
  2557. case 2:
  2558. if (webkit) cm.state.lastMiddleDown = +new Date;
  2559. if (start) extendSelection(cm.doc, start);
  2560. setTimeout(bind(focusInput, cm), 20);
  2561. e_preventDefault(e);
  2562. break;
  2563. case 3:
  2564. if (captureRightClick) onContextMenu(cm, e);
  2565. break;
  2566. }
  2567. }
  2568. var lastClick, lastDoubleClick;
  2569. function leftButtonDown(cm, e, start) {
  2570. setTimeout(bind(ensureFocus, cm), 0);
  2571. var now = +new Date, type;
  2572. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  2573. type = "triple";
  2574. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  2575. type = "double";
  2576. lastDoubleClick = {time: now, pos: start};
  2577. } else {
  2578. type = "single";
  2579. lastClick = {time: now, pos: start};
  2580. }
  2581. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  2582. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
  2583. type == "single" && (contained = sel.contains(start)) > -1 &&
  2584. !sel.ranges[contained].empty())
  2585. leftButtonStartDrag(cm, e, start, modifier);
  2586. else
  2587. leftButtonSelect(cm, e, start, type, modifier);
  2588. }
  2589. // Start a text drag. When it ends, see if any dragging actually
  2590. // happen, and treat as a click if it didn't.
  2591. function leftButtonStartDrag(cm, e, start, modifier) {
  2592. var display = cm.display;
  2593. var dragEnd = operation(cm, function(e2) {
  2594. if (webkit) display.scroller.draggable = false;
  2595. cm.state.draggingText = false;
  2596. off(document, "mouseup", dragEnd);
  2597. off(display.scroller, "drop", dragEnd);
  2598. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  2599. e_preventDefault(e2);
  2600. if (!modifier)
  2601. extendSelection(cm.doc, start);
  2602. focusInput(cm);
  2603. // Work around unexplainable focus problem in IE9 (#2127)
  2604. if (ie && ie_version == 9)
  2605. setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);
  2606. }
  2607. });
  2608. // Let the drag handler handle this.
  2609. if (webkit) display.scroller.draggable = true;
  2610. cm.state.draggingText = dragEnd;
  2611. // IE's approach to draggable
  2612. if (display.scroller.dragDrop) display.scroller.dragDrop();
  2613. on(document, "mouseup", dragEnd);
  2614. on(display.scroller, "drop", dragEnd);
  2615. }
  2616. // Normal selection, as opposed to text dragging.
  2617. function leftButtonSelect(cm, e, start, type, addNew) {
  2618. var display = cm.display, doc = cm.doc;
  2619. e_preventDefault(e);
  2620. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  2621. if (addNew && !e.shiftKey) {
  2622. ourIndex = doc.sel.contains(start);
  2623. if (ourIndex > -1)
  2624. ourRange = ranges[ourIndex];
  2625. else
  2626. ourRange = new Range(start, start);
  2627. } else {
  2628. ourRange = doc.sel.primary();
  2629. }
  2630. if (e.altKey) {
  2631. type = "rect";
  2632. if (!addNew) ourRange = new Range(start, start);
  2633. start = posFromMouse(cm, e, true, true);
  2634. ourIndex = -1;
  2635. } else if (type == "double") {
  2636. var word = cm.findWordAt(start);
  2637. if (cm.display.shift || doc.extend)
  2638. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  2639. else
  2640. ourRange = word;
  2641. } else if (type == "triple") {
  2642. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  2643. if (cm.display.shift || doc.extend)
  2644. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  2645. else
  2646. ourRange = line;
  2647. } else {
  2648. ourRange = extendRange(doc, ourRange, start);
  2649. }
  2650. if (!addNew) {
  2651. ourIndex = 0;
  2652. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  2653. startSel = doc.sel;
  2654. } else if (ourIndex == -1) {
  2655. ourIndex = ranges.length;
  2656. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  2657. {scroll: false, origin: "*mouse"});
  2658. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single") {
  2659. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
  2660. startSel = doc.sel;
  2661. } else {
  2662. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  2663. }
  2664. var lastPos = start;
  2665. function extendTo(pos) {
  2666. if (cmp(lastPos, pos) == 0) return;
  2667. lastPos = pos;
  2668. if (type == "rect") {
  2669. var ranges = [], tabSize = cm.options.tabSize;
  2670. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  2671. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  2672. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  2673. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  2674. line <= end; line++) {
  2675. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  2676. if (left == right)
  2677. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  2678. else if (text.length > leftPos)
  2679. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  2680. }
  2681. if (!ranges.length) ranges.push(new Range(start, start));
  2682. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  2683. {origin: "*mouse", scroll: false});
  2684. cm.scrollIntoView(pos);
  2685. } else {
  2686. var oldRange = ourRange;
  2687. var anchor = oldRange.anchor, head = pos;
  2688. if (type != "single") {
  2689. if (type == "double")
  2690. var range = cm.findWordAt(pos);
  2691. else
  2692. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  2693. if (cmp(range.anchor, anchor) > 0) {
  2694. head = range.head;
  2695. anchor = minPos(oldRange.from(), range.anchor);
  2696. } else {
  2697. head = range.anchor;
  2698. anchor = maxPos(oldRange.to(), range.head);
  2699. }
  2700. }
  2701. var ranges = startSel.ranges.slice(0);
  2702. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  2703. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  2704. }
  2705. }
  2706. var editorSize = display.wrapper.getBoundingClientRect();
  2707. // Used to ensure timeout re-tries don't fire when another extend
  2708. // happened in the meantime (clearTimeout isn't reliable -- at
  2709. // least on Chrome, the timeouts still happen even when cleared,
  2710. // if the clear happens after their scheduled firing time).
  2711. var counter = 0;
  2712. function extend(e) {
  2713. var curCount = ++counter;
  2714. var cur = posFromMouse(cm, e, true, type == "rect");
  2715. if (!cur) return;
  2716. if (cmp(cur, lastPos) != 0) {
  2717. ensureFocus(cm);
  2718. extendTo(cur);
  2719. var visible = visibleLines(display, doc);
  2720. if (cur.line >= visible.to || cur.line < visible.from)
  2721. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  2722. } else {
  2723. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  2724. if (outside) setTimeout(operation(cm, function() {
  2725. if (counter != curCount) return;
  2726. display.scroller.scrollTop += outside;
  2727. extend(e);
  2728. }), 50);
  2729. }
  2730. }
  2731. function done(e) {
  2732. counter = Infinity;
  2733. e_preventDefault(e);
  2734. focusInput(cm);
  2735. off(document, "mousemove", move);
  2736. off(document, "mouseup", up);
  2737. doc.history.lastSelOrigin = null;
  2738. }
  2739. var move = operation(cm, function(e) {
  2740. if (!e_button(e)) done(e);
  2741. else extend(e);
  2742. });
  2743. var up = operation(cm, done);
  2744. on(document, "mousemove", move);
  2745. on(document, "mouseup", up);
  2746. }
  2747. // Determines whether an event happened in the gutter, and fires the
  2748. // handlers for the corresponding event.
  2749. function gutterEvent(cm, e, type, prevent, signalfn) {
  2750. try { var mX = e.clientX, mY = e.clientY; }
  2751. catch(e) { return false; }
  2752. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  2753. if (prevent) e_preventDefault(e);
  2754. var display = cm.display;
  2755. var lineBox = display.lineDiv.getBoundingClientRect();
  2756. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  2757. mY -= lineBox.top - display.viewOffset;
  2758. for (var i = 0; i < cm.options.gutters.length; ++i) {
  2759. var g = display.gutters.childNodes[i];
  2760. if (g && g.getBoundingClientRect().right >= mX) {
  2761. var line = lineAtHeight(cm.doc, mY);
  2762. var gutter = cm.options.gutters[i];
  2763. signalfn(cm, type, cm, line, gutter, e);
  2764. return e_defaultPrevented(e);
  2765. }
  2766. }
  2767. }
  2768. function clickInGutter(cm, e) {
  2769. return gutterEvent(cm, e, "gutterClick", true, signalLater);
  2770. }
  2771. // Kludge to work around strange IE behavior where it'll sometimes
  2772. // re-fire a series of drag-related events right after the drop (#1551)
  2773. var lastDrop = 0;
  2774. function onDrop(e) {
  2775. var cm = this;
  2776. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  2777. return;
  2778. e_preventDefault(e);
  2779. if (ie) lastDrop = +new Date;
  2780. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  2781. if (!pos || isReadOnly(cm)) return;
  2782. // Might be a file drop, in which case we simply extract the text
  2783. // and insert it.
  2784. if (files && files.length && window.FileReader && window.File) {
  2785. var n = files.length, text = Array(n), read = 0;
  2786. var loadFile = function(file, i) {
  2787. var reader = new FileReader;
  2788. reader.onload = operation(cm, function() {
  2789. text[i] = reader.result;
  2790. if (++read == n) {
  2791. pos = clipPos(cm.doc, pos);
  2792. var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
  2793. makeChange(cm.doc, change);
  2794. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  2795. }
  2796. });
  2797. reader.readAsText(file);
  2798. };
  2799. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  2800. } else { // Normal drop
  2801. // Don't do a replace if the drop happened inside of the selected text.
  2802. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  2803. cm.state.draggingText(e);
  2804. // Ensure the editor is re-focused
  2805. setTimeout(bind(focusInput, cm), 20);
  2806. return;
  2807. }
  2808. try {
  2809. var text = e.dataTransfer.getData("Text");
  2810. if (text) {
  2811. if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey))
  2812. var selected = cm.listSelections();
  2813. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  2814. if (selected) for (var i = 0; i < selected.length; ++i)
  2815. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  2816. cm.replaceSelection(text, "around", "paste");
  2817. focusInput(cm);
  2818. }
  2819. }
  2820. catch(e){}
  2821. }
  2822. }
  2823. function onDragStart(cm, e) {
  2824. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  2825. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  2826. e.dataTransfer.setData("Text", cm.getSelection());
  2827. // Use dummy image instead of default browsers image.
  2828. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  2829. if (e.dataTransfer.setDragImage && !safari) {
  2830. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  2831. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  2832. if (presto) {
  2833. img.width = img.height = 1;
  2834. cm.display.wrapper.appendChild(img);
  2835. // Force a relayout, or Opera won't use our image for some obscure reason
  2836. img._top = img.offsetTop;
  2837. }
  2838. e.dataTransfer.setDragImage(img, 0, 0);
  2839. if (presto) img.parentNode.removeChild(img);
  2840. }
  2841. }
  2842. // SCROLL EVENTS
  2843. // Sync the scrollable area and scrollbars, ensure the viewport
  2844. // covers the visible area.
  2845. function setScrollTop(cm, val) {
  2846. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  2847. cm.doc.scrollTop = val;
  2848. if (!gecko) updateDisplaySimple(cm, {top: val});
  2849. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  2850. cm.display.scrollbars.setScrollTop(val);
  2851. if (gecko) updateDisplaySimple(cm);
  2852. startWorker(cm, 100);
  2853. }
  2854. // Sync scroller and scrollbar, ensure the gutter elements are
  2855. // aligned.
  2856. function setScrollLeft(cm, val, isScroller) {
  2857. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  2858. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  2859. cm.doc.scrollLeft = val;
  2860. alignHorizontally(cm);
  2861. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  2862. cm.display.scrollbars.setScrollLeft(val);
  2863. }
  2864. // Since the delta values reported on mouse wheel events are
  2865. // unstandardized between browsers and even browser versions, and
  2866. // generally horribly unpredictable, this code starts by measuring
  2867. // the scroll effect that the first few mouse wheel events have,
  2868. // and, from that, detects the way it can convert deltas to pixel
  2869. // offsets afterwards.
  2870. //
  2871. // The reason we want to know the amount a wheel event will scroll
  2872. // is that it gives us a chance to update the display before the
  2873. // actual scrolling happens, reducing flickering.
  2874. var wheelSamples = 0, wheelPixelsPerUnit = null;
  2875. // Fill in a browser-detected starting value on browsers where we
  2876. // know one. These don't have to be accurate -- the result of them
  2877. // being wrong would just be a slight flicker on the first wheel
  2878. // scroll (if it is large enough).
  2879. if (ie) wheelPixelsPerUnit = -.53;
  2880. else if (gecko) wheelPixelsPerUnit = 15;
  2881. else if (chrome) wheelPixelsPerUnit = -.7;
  2882. else if (safari) wheelPixelsPerUnit = -1/3;
  2883. var wheelEventDelta = function(e) {
  2884. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  2885. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  2886. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  2887. else if (dy == null) dy = e.wheelDelta;
  2888. return {x: dx, y: dy};
  2889. };
  2890. CodeMirror.wheelEventPixels = function(e) {
  2891. var delta = wheelEventDelta(e);
  2892. delta.x *= wheelPixelsPerUnit;
  2893. delta.y *= wheelPixelsPerUnit;
  2894. return delta;
  2895. };
  2896. function onScrollWheel(cm, e) {
  2897. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  2898. var display = cm.display, scroll = display.scroller;
  2899. // Quit if there's nothing to scroll here
  2900. if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
  2901. dy && scroll.scrollHeight > scroll.clientHeight)) return;
  2902. // Webkit browsers on OS X abort momentum scrolls when the target
  2903. // of the scroll event is removed from the scrollable element.
  2904. // This hack (see related code in patchDisplay) makes sure the
  2905. // element is kept around.
  2906. if (dy && mac && webkit) {
  2907. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  2908. for (var i = 0; i < view.length; i++) {
  2909. if (view[i].node == cur) {
  2910. cm.display.currentWheelTarget = cur;
  2911. break outer;
  2912. }
  2913. }
  2914. }
  2915. }
  2916. // On some browsers, horizontal scrolling will cause redraws to
  2917. // happen before the gutter has been realigned, causing it to
  2918. // wriggle around in a most unseemly way. When we have an
  2919. // estimated pixels/delta value, we just handle horizontal
  2920. // scrolling entirely here. It'll be slightly off from native, but
  2921. // better than glitching out.
  2922. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  2923. if (dy)
  2924. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  2925. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  2926. e_preventDefault(e);
  2927. display.wheelStartX = null; // Abort measurement, if in progress
  2928. return;
  2929. }
  2930. // 'Project' the visible viewport to cover the area that is being
  2931. // scrolled into view (if we know enough to estimate it).
  2932. if (dy && wheelPixelsPerUnit != null) {
  2933. var pixels = dy * wheelPixelsPerUnit;
  2934. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  2935. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  2936. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  2937. updateDisplaySimple(cm, {top: top, bottom: bot});
  2938. }
  2939. if (wheelSamples < 20) {
  2940. if (display.wheelStartX == null) {
  2941. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  2942. display.wheelDX = dx; display.wheelDY = dy;
  2943. setTimeout(function() {
  2944. if (display.wheelStartX == null) return;
  2945. var movedX = scroll.scrollLeft - display.wheelStartX;
  2946. var movedY = scroll.scrollTop - display.wheelStartY;
  2947. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  2948. (movedX && display.wheelDX && movedX / display.wheelDX);
  2949. display.wheelStartX = display.wheelStartY = null;
  2950. if (!sample) return;
  2951. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  2952. ++wheelSamples;
  2953. }, 200);
  2954. } else {
  2955. display.wheelDX += dx; display.wheelDY += dy;
  2956. }
  2957. }
  2958. }
  2959. // KEY EVENTS
  2960. // Run a handler that was bound to a key.
  2961. function doHandleBinding(cm, bound, dropShift) {
  2962. if (typeof bound == "string") {
  2963. bound = commands[bound];
  2964. if (!bound) return false;
  2965. }
  2966. // Ensure previous input has been read, so that the handler sees a
  2967. // consistent view of the document
  2968. if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
  2969. var prevShift = cm.display.shift, done = false;
  2970. try {
  2971. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  2972. if (dropShift) cm.display.shift = false;
  2973. done = bound(cm) != Pass;
  2974. } finally {
  2975. cm.display.shift = prevShift;
  2976. cm.state.suppressEdits = false;
  2977. }
  2978. return done;
  2979. }
  2980. function lookupKeyForEditor(cm, name, handle) {
  2981. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  2982. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  2983. if (result) return result;
  2984. }
  2985. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  2986. || lookupKey(name, cm.options.keyMap, handle, cm);
  2987. }
  2988. var stopSeq = new Delayed;
  2989. function dispatchKey(cm, name, e, handle) {
  2990. var seq = cm.state.keySeq;
  2991. if (seq) {
  2992. if (isModifierKey(name)) return "handled";
  2993. stopSeq.set(50, function() {
  2994. if (cm.state.keySeq == seq) {
  2995. cm.state.keySeq = null;
  2996. resetInput(cm);
  2997. }
  2998. });
  2999. name = seq + " " + name;
  3000. }
  3001. var result = lookupKeyForEditor(cm, name, handle);
  3002. if (result == "multi")
  3003. cm.state.keySeq = name;
  3004. if (result == "handled")
  3005. signalLater(cm, "keyHandled", cm, name, e);
  3006. if (result == "handled" || result == "multi") {
  3007. e_preventDefault(e);
  3008. restartBlink(cm);
  3009. }
  3010. if (seq && !result && /\'$/.test(name)) {
  3011. e_preventDefault(e);
  3012. return true;
  3013. }
  3014. return !!result;
  3015. }
  3016. // Handle a key from the keydown event.
  3017. function handleKeyBinding(cm, e) {
  3018. var name = keyName(e, true);
  3019. if (!name) return false;
  3020. if (e.shiftKey && !cm.state.keySeq) {
  3021. // First try to resolve full name (including 'Shift-'). Failing
  3022. // that, see if there is a cursor-motion command (starting with
  3023. // 'go') bound to the keyname without 'Shift-'.
  3024. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3025. || dispatchKey(cm, name, e, function(b) {
  3026. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3027. return doHandleBinding(cm, b);
  3028. });
  3029. } else {
  3030. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3031. }
  3032. }
  3033. // Handle a key from the keypress event
  3034. function handleCharBinding(cm, e, ch) {
  3035. return dispatchKey(cm, "'" + ch + "'", e,
  3036. function(b) { return doHandleBinding(cm, b, true); });
  3037. }
  3038. var lastStoppedKey = null;
  3039. function onKeyDown(e) {
  3040. var cm = this;
  3041. ensureFocus(cm);
  3042. if (signalDOMEvent(cm, e)) return;
  3043. // IE does strange things with escape.
  3044. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3045. var code = e.keyCode;
  3046. cm.display.shift = code == 16 || e.shiftKey;
  3047. var handled = handleKeyBinding(cm, e);
  3048. if (presto) {
  3049. lastStoppedKey = handled ? code : null;
  3050. // Opera has no cut event... we try to at least catch the key combo
  3051. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3052. cm.replaceSelection("", null, "cut");
  3053. }
  3054. // Turn mouse into crosshair when Alt is held on Mac.
  3055. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3056. showCrossHair(cm);
  3057. }
  3058. function showCrossHair(cm) {
  3059. var lineDiv = cm.display.lineDiv;
  3060. addClass(lineDiv, "CodeMirror-crosshair");
  3061. function up(e) {
  3062. if (e.keyCode == 18 || !e.altKey) {
  3063. rmClass(lineDiv, "CodeMirror-crosshair");
  3064. off(document, "keyup", up);
  3065. off(document, "mouseover", up);
  3066. }
  3067. }
  3068. on(document, "keyup", up);
  3069. on(document, "mouseover", up);
  3070. }
  3071. function onKeyUp(e) {
  3072. if (e.keyCode == 16) this.doc.sel.shift = false;
  3073. signalDOMEvent(this, e);
  3074. }
  3075. function onKeyPress(e) {
  3076. var cm = this;
  3077. if (signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3078. var keyCode = e.keyCode, charCode = e.charCode;
  3079. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3080. if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
  3081. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3082. if (handleCharBinding(cm, e, ch)) return;
  3083. if (ie && ie_version >= 9) cm.display.inputHasSelection = null;
  3084. fastPoll(cm);
  3085. }
  3086. // FOCUS/BLUR EVENTS
  3087. function onFocus(cm) {
  3088. if (cm.options.readOnly == "nocursor") return;
  3089. if (!cm.state.focused) {
  3090. signal(cm, "focus", cm);
  3091. cm.state.focused = true;
  3092. addClass(cm.display.wrapper, "CodeMirror-focused");
  3093. // The prevInput test prevents this from firing when a context
  3094. // menu is closed (since the resetInput would kill the
  3095. // select-all detection hack)
  3096. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3097. resetInput(cm);
  3098. if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
  3099. }
  3100. }
  3101. slowPoll(cm);
  3102. restartBlink(cm);
  3103. }
  3104. function onBlur(cm) {
  3105. if (cm.state.focused) {
  3106. signal(cm, "blur", cm);
  3107. cm.state.focused = false;
  3108. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3109. }
  3110. clearInterval(cm.display.blinker);
  3111. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3112. }
  3113. // CONTEXT MENU HANDLING
  3114. // To make the context menu work, we need to briefly unhide the
  3115. // textarea (making it as unobtrusive as possible) to let the
  3116. // right-click take effect on it.
  3117. function onContextMenu(cm, e) {
  3118. if (signalDOMEvent(cm, e, "contextmenu")) return;
  3119. var display = cm.display;
  3120. if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
  3121. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  3122. if (!pos || presto) return; // Opera is difficult.
  3123. // Reset the current text selection only if the click is done outside of the selection
  3124. // and 'resetSelectionOnContextMenu' option is true.
  3125. var reset = cm.options.resetSelectionOnContextMenu;
  3126. if (reset && cm.doc.sel.contains(pos) == -1)
  3127. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  3128. var oldCSS = display.input.style.cssText;
  3129. display.inputDiv.style.position = "absolute";
  3130. display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  3131. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
  3132. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  3133. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  3134. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  3135. focusInput(cm);
  3136. if (webkit) window.scrollTo(null, oldScrollY);
  3137. resetInput(cm);
  3138. // Adds "Select all" to context menu in FF
  3139. if (!cm.somethingSelected()) display.input.value = display.prevInput = " ";
  3140. display.contextMenuPending = true;
  3141. display.selForContextMenu = cm.doc.sel;
  3142. clearTimeout(display.detectingSelectAll);
  3143. // Select-all will be greyed out if there's nothing to select, so
  3144. // this adds a zero-width space so that we can later check whether
  3145. // it got selected.
  3146. function prepareSelectAllHack() {
  3147. if (display.input.selectionStart != null) {
  3148. var selected = cm.somethingSelected();
  3149. var extval = display.input.value = "\u200b" + (selected ? display.input.value : "");
  3150. display.prevInput = selected ? "" : "\u200b";
  3151. display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
  3152. // Re-set this, in case some other handler touched the
  3153. // selection in the meantime.
  3154. display.selForContextMenu = cm.doc.sel;
  3155. }
  3156. }
  3157. function rehide() {
  3158. display.contextMenuPending = false;
  3159. display.inputDiv.style.position = "relative";
  3160. display.input.style.cssText = oldCSS;
  3161. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  3162. slowPoll(cm);
  3163. // Try to detect the user choosing select-all
  3164. if (display.input.selectionStart != null) {
  3165. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  3166. var i = 0, poll = function() {
  3167. if (display.selForContextMenu == cm.doc.sel && display.input.selectionStart == 0)
  3168. operation(cm, commands.selectAll)(cm);
  3169. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  3170. else resetInput(cm);
  3171. };
  3172. display.detectingSelectAll = setTimeout(poll, 200);
  3173. }
  3174. }
  3175. if (ie && ie_version >= 9) prepareSelectAllHack();
  3176. if (captureRightClick) {
  3177. e_stop(e);
  3178. var mouseup = function() {
  3179. off(window, "mouseup", mouseup);
  3180. setTimeout(rehide, 20);
  3181. };
  3182. on(window, "mouseup", mouseup);
  3183. } else {
  3184. setTimeout(rehide, 50);
  3185. }
  3186. }
  3187. function contextMenuInGutter(cm, e) {
  3188. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3189. return gutterEvent(cm, e, "gutterContextMenu", false, signal);
  3190. }
  3191. // UPDATING
  3192. // Compute the position of the end of a change (its 'to' property
  3193. // refers to the pre-change end).
  3194. var changeEnd = CodeMirror.changeEnd = function(change) {
  3195. if (!change.text) return change.to;
  3196. return Pos(change.from.line + change.text.length - 1,
  3197. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3198. };
  3199. // Adjust a position to refer to the post-change position of the
  3200. // same text, or the end of the change if the change covers it.
  3201. function adjustForChange(pos, change) {
  3202. if (cmp(pos, change.from) < 0) return pos;
  3203. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3204. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3205. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3206. return Pos(line, ch);
  3207. }
  3208. function computeSelAfterChange(doc, change) {
  3209. var out = [];
  3210. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3211. var range = doc.sel.ranges[i];
  3212. out.push(new Range(adjustForChange(range.anchor, change),
  3213. adjustForChange(range.head, change)));
  3214. }
  3215. return normalizeSelection(out, doc.sel.primIndex);
  3216. }
  3217. function offsetPos(pos, old, nw) {
  3218. if (pos.line == old.line)
  3219. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3220. else
  3221. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3222. }
  3223. // Used by replaceSelections to allow moving the selection to the
  3224. // start or around the replaced test. Hint may be "start" or "around".
  3225. function computeReplacedSel(doc, changes, hint) {
  3226. var out = [];
  3227. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3228. for (var i = 0; i < changes.length; i++) {
  3229. var change = changes[i];
  3230. var from = offsetPos(change.from, oldPrev, newPrev);
  3231. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3232. oldPrev = change.to;
  3233. newPrev = to;
  3234. if (hint == "around") {
  3235. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3236. out[i] = new Range(inv ? to : from, inv ? from : to);
  3237. } else {
  3238. out[i] = new Range(from, from);
  3239. }
  3240. }
  3241. return new Selection(out, doc.sel.primIndex);
  3242. }
  3243. // Allow "beforeChange" event handlers to influence a change
  3244. function filterChange(doc, change, update) {
  3245. var obj = {
  3246. canceled: false,
  3247. from: change.from,
  3248. to: change.to,
  3249. text: change.text,
  3250. origin: change.origin,
  3251. cancel: function() { this.canceled = true; }
  3252. };
  3253. if (update) obj.update = function(from, to, text, origin) {
  3254. if (from) this.from = clipPos(doc, from);
  3255. if (to) this.to = clipPos(doc, to);
  3256. if (text) this.text = text;
  3257. if (origin !== undefined) this.origin = origin;
  3258. };
  3259. signal(doc, "beforeChange", doc, obj);
  3260. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3261. if (obj.canceled) return null;
  3262. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3263. }
  3264. // Apply a change to a document, and add it to the document's
  3265. // history, and propagating it to all linked documents.
  3266. function makeChange(doc, change, ignoreReadOnly) {
  3267. if (doc.cm) {
  3268. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3269. if (doc.cm.state.suppressEdits) return;
  3270. }
  3271. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3272. change = filterChange(doc, change, true);
  3273. if (!change) return;
  3274. }
  3275. // Possibly split or suppress the update based on the presence
  3276. // of read-only spans in its range.
  3277. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3278. if (split) {
  3279. for (var i = split.length - 1; i >= 0; --i)
  3280. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3281. } else {
  3282. makeChangeInner(doc, change);
  3283. }
  3284. }
  3285. function makeChangeInner(doc, change) {
  3286. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3287. var selAfter = computeSelAfterChange(doc, change);
  3288. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3289. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3290. var rebased = [];
  3291. linkedDocs(doc, function(doc, sharedHist) {
  3292. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3293. rebaseHist(doc.history, change);
  3294. rebased.push(doc.history);
  3295. }
  3296. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3297. });
  3298. }
  3299. // Revert a change stored in a document's history.
  3300. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3301. if (doc.cm && doc.cm.state.suppressEdits) return;
  3302. var hist = doc.history, event, selAfter = doc.sel;
  3303. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3304. // Verify that there is a useable event (so that ctrl-z won't
  3305. // needlessly clear selection events)
  3306. for (var i = 0; i < source.length; i++) {
  3307. event = source[i];
  3308. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3309. break;
  3310. }
  3311. if (i == source.length) return;
  3312. hist.lastOrigin = hist.lastSelOrigin = null;
  3313. for (;;) {
  3314. event = source.pop();
  3315. if (event.ranges) {
  3316. pushSelectionToHistory(event, dest);
  3317. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3318. setSelection(doc, event, {clearRedo: false});
  3319. return;
  3320. }
  3321. selAfter = event;
  3322. }
  3323. else break;
  3324. }
  3325. // Build up a reverse change object to add to the opposite history
  3326. // stack (redo when undoing, and vice versa).
  3327. var antiChanges = [];
  3328. pushSelectionToHistory(selAfter, dest);
  3329. dest.push({changes: antiChanges, generation: hist.generation});
  3330. hist.generation = event.generation || ++hist.maxGeneration;
  3331. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3332. for (var i = event.changes.length - 1; i >= 0; --i) {
  3333. var change = event.changes[i];
  3334. change.origin = type;
  3335. if (filter && !filterChange(doc, change, false)) {
  3336. source.length = 0;
  3337. return;
  3338. }
  3339. antiChanges.push(historyChangeFromChange(doc, change));
  3340. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3341. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3342. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  3343. var rebased = [];
  3344. // Propagate to the linked documents
  3345. linkedDocs(doc, function(doc, sharedHist) {
  3346. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3347. rebaseHist(doc.history, change);
  3348. rebased.push(doc.history);
  3349. }
  3350. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  3351. });
  3352. }
  3353. }
  3354. // Sub-views need their line numbers shifted when text is added
  3355. // above or below them in the parent document.
  3356. function shiftDoc(doc, distance) {
  3357. if (distance == 0) return;
  3358. doc.first += distance;
  3359. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  3360. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  3361. Pos(range.head.line + distance, range.head.ch));
  3362. }), doc.sel.primIndex);
  3363. if (doc.cm) {
  3364. regChange(doc.cm, doc.first, doc.first - distance, distance);
  3365. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  3366. regLineChange(doc.cm, l, "gutter");
  3367. }
  3368. }
  3369. // More lower-level change function, handling only a single document
  3370. // (not linked ones).
  3371. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  3372. if (doc.cm && !doc.cm.curOp)
  3373. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  3374. if (change.to.line < doc.first) {
  3375. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  3376. return;
  3377. }
  3378. if (change.from.line > doc.lastLine()) return;
  3379. // Clip the change to the size of this doc
  3380. if (change.from.line < doc.first) {
  3381. var shift = change.text.length - 1 - (doc.first - change.from.line);
  3382. shiftDoc(doc, shift);
  3383. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  3384. text: [lst(change.text)], origin: change.origin};
  3385. }
  3386. var last = doc.lastLine();
  3387. if (change.to.line > last) {
  3388. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  3389. text: [change.text[0]], origin: change.origin};
  3390. }
  3391. change.removed = getBetween(doc, change.from, change.to);
  3392. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  3393. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  3394. else updateDoc(doc, change, spans);
  3395. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  3396. }
  3397. // Handle the interaction of a change to a document with the editor
  3398. // that this document is part of.
  3399. function makeChangeSingleDocInEditor(cm, change, spans) {
  3400. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  3401. var recomputeMaxLength = false, checkWidthStart = from.line;
  3402. if (!cm.options.lineWrapping) {
  3403. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  3404. doc.iter(checkWidthStart, to.line + 1, function(line) {
  3405. if (line == display.maxLine) {
  3406. recomputeMaxLength = true;
  3407. return true;
  3408. }
  3409. });
  3410. }
  3411. if (doc.sel.contains(change.from, change.to) > -1)
  3412. signalCursorActivity(cm);
  3413. updateDoc(doc, change, spans, estimateHeight(cm));
  3414. if (!cm.options.lineWrapping) {
  3415. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  3416. var len = lineLength(line);
  3417. if (len > display.maxLineLength) {
  3418. display.maxLine = line;
  3419. display.maxLineLength = len;
  3420. display.maxLineChanged = true;
  3421. recomputeMaxLength = false;
  3422. }
  3423. });
  3424. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  3425. }
  3426. // Adjust frontier, schedule worker
  3427. doc.frontier = Math.min(doc.frontier, from.line);
  3428. startWorker(cm, 400);
  3429. var lendiff = change.text.length - (to.line - from.line) - 1;
  3430. // Remember that these lines changed, for updating the display
  3431. if (change.full)
  3432. regChange(cm);
  3433. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  3434. regLineChange(cm, from.line, "text");
  3435. else
  3436. regChange(cm, from.line, to.line + 1, lendiff);
  3437. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  3438. if (changeHandler || changesHandler) {
  3439. var obj = {
  3440. from: from, to: to,
  3441. text: change.text,
  3442. removed: change.removed,
  3443. origin: change.origin
  3444. };
  3445. if (changeHandler) signalLater(cm, "change", cm, obj);
  3446. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  3447. }
  3448. cm.display.selForContextMenu = null;
  3449. }
  3450. function replaceRange(doc, code, from, to, origin) {
  3451. if (!to) to = from;
  3452. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  3453. if (typeof code == "string") code = splitLines(code);
  3454. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  3455. }
  3456. // SCROLLING THINGS INTO VIEW
  3457. // If an editor sits on the top or bottom of the window, partially
  3458. // scrolled out of view, this ensures that the cursor is visible.
  3459. function maybeScrollWindow(cm, coords) {
  3460. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  3461. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3462. if (coords.top + box.top < 0) doScroll = true;
  3463. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  3464. if (doScroll != null && !phantom) {
  3465. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  3466. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  3467. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  3468. coords.left + "px; width: 2px;");
  3469. cm.display.lineSpace.appendChild(scrollNode);
  3470. scrollNode.scrollIntoView(doScroll);
  3471. cm.display.lineSpace.removeChild(scrollNode);
  3472. }
  3473. }
  3474. // Scroll a given position into view (immediately), verifying that
  3475. // it actually became visible (as line heights are accurately
  3476. // measured, the position of something may 'drift' during drawing).
  3477. function scrollPosIntoView(cm, pos, end, margin) {
  3478. if (margin == null) margin = 0;
  3479. for (var limit = 0; limit < 5; limit++) {
  3480. var changed = false, coords = cursorCoords(cm, pos);
  3481. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3482. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  3483. Math.min(coords.top, endCoords.top) - margin,
  3484. Math.max(coords.left, endCoords.left),
  3485. Math.max(coords.bottom, endCoords.bottom) + margin);
  3486. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3487. if (scrollPos.scrollTop != null) {
  3488. setScrollTop(cm, scrollPos.scrollTop);
  3489. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  3490. }
  3491. if (scrollPos.scrollLeft != null) {
  3492. setScrollLeft(cm, scrollPos.scrollLeft);
  3493. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  3494. }
  3495. if (!changed) break;
  3496. }
  3497. return coords;
  3498. }
  3499. // Scroll a given set of coordinates into view (immediately).
  3500. function scrollIntoView(cm, x1, y1, x2, y2) {
  3501. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  3502. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  3503. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  3504. }
  3505. // Calculate a new scroll position needed to scroll the given
  3506. // rectangle into view. Returns an object with scrollTop and
  3507. // scrollLeft properties. When these are undefined, the
  3508. // vertical/horizontal position does not need to be adjusted.
  3509. function calculateScrollPos(cm, x1, y1, x2, y2) {
  3510. var display = cm.display, snapMargin = textHeight(cm.display);
  3511. if (y1 < 0) y1 = 0;
  3512. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3513. var screen = displayHeight(cm), result = {};
  3514. if (y2 - y1 > screen) y2 = y1 + screen;
  3515. var docBottom = cm.doc.height + paddingVert(display);
  3516. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  3517. if (y1 < screentop) {
  3518. result.scrollTop = atTop ? 0 : y1;
  3519. } else if (y2 > screentop + screen) {
  3520. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  3521. if (newTop != screentop) result.scrollTop = newTop;
  3522. }
  3523. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  3524. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  3525. var tooWide = x2 - x1 > screenw;
  3526. if (tooWide) x2 = x1 + screenw;
  3527. if (x1 < 10)
  3528. result.scrollLeft = 0;
  3529. else if (x1 < screenleft)
  3530. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  3531. else if (x2 > screenw + screenleft - 3)
  3532. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  3533. return result;
  3534. }
  3535. // Store a relative adjustment to the scroll position in the current
  3536. // operation (to be applied when the operation finishes).
  3537. function addToScrollPos(cm, left, top) {
  3538. if (left != null || top != null) resolveScrollToPos(cm);
  3539. if (left != null)
  3540. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  3541. if (top != null)
  3542. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3543. }
  3544. // Make sure that at the end of the operation the current cursor is
  3545. // shown.
  3546. function ensureCursorVisible(cm) {
  3547. resolveScrollToPos(cm);
  3548. var cur = cm.getCursor(), from = cur, to = cur;
  3549. if (!cm.options.lineWrapping) {
  3550. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  3551. to = Pos(cur.line, cur.ch + 1);
  3552. }
  3553. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  3554. }
  3555. // When an operation has its scrollToPos property set, and another
  3556. // scroll action is applied before the end of the operation, this
  3557. // 'simulates' scrolling that position into view in a cheap way, so
  3558. // that the effect of intermediate scroll commands is not ignored.
  3559. function resolveScrollToPos(cm) {
  3560. var range = cm.curOp.scrollToPos;
  3561. if (range) {
  3562. cm.curOp.scrollToPos = null;
  3563. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3564. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  3565. Math.min(from.top, to.top) - range.margin,
  3566. Math.max(from.right, to.right),
  3567. Math.max(from.bottom, to.bottom) + range.margin);
  3568. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  3569. }
  3570. }
  3571. // API UTILITIES
  3572. // Indent the given line. The how parameter can be "smart",
  3573. // "add"/null, "subtract", or "prev". When aggressive is false
  3574. // (typically set to true for forced single-line indents), empty
  3575. // lines are not indented, and places where the mode returns Pass
  3576. // are left alone.
  3577. function indentLine(cm, n, how, aggressive) {
  3578. var doc = cm.doc, state;
  3579. if (how == null) how = "add";
  3580. if (how == "smart") {
  3581. // Fall back to "prev" when the mode doesn't have an indentation
  3582. // method.
  3583. if (!doc.mode.indent) how = "prev";
  3584. else state = getStateBefore(cm, n);
  3585. }
  3586. var tabSize = cm.options.tabSize;
  3587. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  3588. if (line.stateAfter) line.stateAfter = null;
  3589. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  3590. if (!aggressive && !/\S/.test(line.text)) {
  3591. indentation = 0;
  3592. how = "not";
  3593. } else if (how == "smart") {
  3594. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  3595. if (indentation == Pass || indentation > 150) {
  3596. if (!aggressive) return;
  3597. how = "prev";
  3598. }
  3599. }
  3600. if (how == "prev") {
  3601. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  3602. else indentation = 0;
  3603. } else if (how == "add") {
  3604. indentation = curSpace + cm.options.indentUnit;
  3605. } else if (how == "subtract") {
  3606. indentation = curSpace - cm.options.indentUnit;
  3607. } else if (typeof how == "number") {
  3608. indentation = curSpace + how;
  3609. }
  3610. indentation = Math.max(0, indentation);
  3611. var indentString = "", pos = 0;
  3612. if (cm.options.indentWithTabs)
  3613. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  3614. if (pos < indentation) indentString += spaceStr(indentation - pos);
  3615. if (indentString != curSpaceString) {
  3616. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  3617. } else {
  3618. // Ensure that, if the cursor was in the whitespace at the start
  3619. // of the line, it is moved to the end of that space.
  3620. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3621. var range = doc.sel.ranges[i];
  3622. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  3623. var pos = Pos(n, curSpaceString.length);
  3624. replaceOneSelection(doc, i, new Range(pos, pos));
  3625. break;
  3626. }
  3627. }
  3628. }
  3629. line.stateAfter = null;
  3630. }
  3631. // Utility for applying a change to a line by handle or number,
  3632. // returning the number and optionally registering the line as
  3633. // changed.
  3634. function changeLine(doc, handle, changeType, op) {
  3635. var no = handle, line = handle;
  3636. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  3637. else no = lineNo(handle);
  3638. if (no == null) return null;
  3639. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  3640. return line;
  3641. }
  3642. // Helper for deleting text near the selection(s), used to implement
  3643. // backspace, delete, and similar functionality.
  3644. function deleteNearSelection(cm, compute) {
  3645. var ranges = cm.doc.sel.ranges, kill = [];
  3646. // Build up a set of ranges to kill first, merging overlapping
  3647. // ranges.
  3648. for (var i = 0; i < ranges.length; i++) {
  3649. var toKill = compute(ranges[i]);
  3650. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  3651. var replaced = kill.pop();
  3652. if (cmp(replaced.from, toKill.from) < 0) {
  3653. toKill.from = replaced.from;
  3654. break;
  3655. }
  3656. }
  3657. kill.push(toKill);
  3658. }
  3659. // Next, remove those actual ranges.
  3660. runInOp(cm, function() {
  3661. for (var i = kill.length - 1; i >= 0; i--)
  3662. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  3663. ensureCursorVisible(cm);
  3664. });
  3665. }
  3666. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  3667. // right), unit can be "char", "column" (like char, but doesn't
  3668. // cross line boundaries), "word" (across next word), or "group" (to
  3669. // the start of next group of word or non-word-non-whitespace
  3670. // chars). The visually param controls whether, in right-to-left
  3671. // text, direction 1 means to move towards the next index in the
  3672. // string, or towards the character to the right of the current
  3673. // position. The resulting position will have a hitSide=true
  3674. // property if it reached the end of the document.
  3675. function findPosH(doc, pos, dir, unit, visually) {
  3676. var line = pos.line, ch = pos.ch, origDir = dir;
  3677. var lineObj = getLine(doc, line);
  3678. var possible = true;
  3679. function findNextLine() {
  3680. var l = line + dir;
  3681. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  3682. line = l;
  3683. return lineObj = getLine(doc, l);
  3684. }
  3685. function moveOnce(boundToLine) {
  3686. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  3687. if (next == null) {
  3688. if (!boundToLine && findNextLine()) {
  3689. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  3690. else ch = dir < 0 ? lineObj.text.length : 0;
  3691. } else return (possible = false);
  3692. } else ch = next;
  3693. return true;
  3694. }
  3695. if (unit == "char") moveOnce();
  3696. else if (unit == "column") moveOnce(true);
  3697. else if (unit == "word" || unit == "group") {
  3698. var sawType = null, group = unit == "group";
  3699. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  3700. for (var first = true;; first = false) {
  3701. if (dir < 0 && !moveOnce(!first)) break;
  3702. var cur = lineObj.text.charAt(ch) || "\n";
  3703. var type = isWordChar(cur, helper) ? "w"
  3704. : group && cur == "\n" ? "n"
  3705. : !group || /\s/.test(cur) ? null
  3706. : "p";
  3707. if (group && !first && !type) type = "s";
  3708. if (sawType && sawType != type) {
  3709. if (dir < 0) {dir = 1; moveOnce();}
  3710. break;
  3711. }
  3712. if (type) sawType = type;
  3713. if (dir > 0 && !moveOnce(!first)) break;
  3714. }
  3715. }
  3716. var result = skipAtomic(doc, Pos(line, ch), origDir, true);
  3717. if (!possible) result.hitSide = true;
  3718. return result;
  3719. }
  3720. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  3721. // "page" or "line". The resulting position will have a hitSide=true
  3722. // property if it reached the end of the document.
  3723. function findPosV(cm, pos, dir, unit) {
  3724. var doc = cm.doc, x = pos.left, y;
  3725. if (unit == "page") {
  3726. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  3727. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  3728. } else if (unit == "line") {
  3729. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  3730. }
  3731. for (;;) {
  3732. var target = coordsChar(cm, x, y);
  3733. if (!target.outside) break;
  3734. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  3735. y += dir * 5;
  3736. }
  3737. return target;
  3738. }
  3739. // EDITOR METHODS
  3740. // The publicly visible API. Note that methodOp(f) means
  3741. // 'wrap f in an operation, performed on its `this` parameter'.
  3742. // This is not the complete set of editor methods. Most of the
  3743. // methods defined on the Doc type are also injected into
  3744. // CodeMirror.prototype, for backwards compatibility and
  3745. // convenience.
  3746. CodeMirror.prototype = {
  3747. constructor: CodeMirror,
  3748. focus: function(){window.focus(); focusInput(this); fastPoll(this);},
  3749. setOption: function(option, value) {
  3750. var options = this.options, old = options[option];
  3751. if (options[option] == value && option != "mode") return;
  3752. options[option] = value;
  3753. if (optionHandlers.hasOwnProperty(option))
  3754. operation(this, optionHandlers[option])(this, value, old);
  3755. },
  3756. getOption: function(option) {return this.options[option];},
  3757. getDoc: function() {return this.doc;},
  3758. addKeyMap: function(map, bottom) {
  3759. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  3760. },
  3761. removeKeyMap: function(map) {
  3762. var maps = this.state.keyMaps;
  3763. for (var i = 0; i < maps.length; ++i)
  3764. if (maps[i] == map || maps[i].name == map) {
  3765. maps.splice(i, 1);
  3766. return true;
  3767. }
  3768. },
  3769. addOverlay: methodOp(function(spec, options) {
  3770. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  3771. if (mode.startState) throw new Error("Overlays may not be stateful.");
  3772. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  3773. this.state.modeGen++;
  3774. regChange(this);
  3775. }),
  3776. removeOverlay: methodOp(function(spec) {
  3777. var overlays = this.state.overlays;
  3778. for (var i = 0; i < overlays.length; ++i) {
  3779. var cur = overlays[i].modeSpec;
  3780. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  3781. overlays.splice(i, 1);
  3782. this.state.modeGen++;
  3783. regChange(this);
  3784. return;
  3785. }
  3786. }
  3787. }),
  3788. indentLine: methodOp(function(n, dir, aggressive) {
  3789. if (typeof dir != "string" && typeof dir != "number") {
  3790. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  3791. else dir = dir ? "add" : "subtract";
  3792. }
  3793. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  3794. }),
  3795. indentSelection: methodOp(function(how) {
  3796. var ranges = this.doc.sel.ranges, end = -1;
  3797. for (var i = 0; i < ranges.length; i++) {
  3798. var range = ranges[i];
  3799. if (!range.empty()) {
  3800. var from = range.from(), to = range.to();
  3801. var start = Math.max(end, from.line);
  3802. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  3803. for (var j = start; j < end; ++j)
  3804. indentLine(this, j, how);
  3805. var newRanges = this.doc.sel.ranges;
  3806. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  3807. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  3808. } else if (range.head.line > end) {
  3809. indentLine(this, range.head.line, how, true);
  3810. end = range.head.line;
  3811. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  3812. }
  3813. }
  3814. }),
  3815. // Fetch the parser token for a given character. Useful for hacks
  3816. // that want to inspect the mode state (say, for completion).
  3817. getTokenAt: function(pos, precise) {
  3818. return takeToken(this, pos, precise);
  3819. },
  3820. getLineTokens: function(line, precise) {
  3821. return takeToken(this, Pos(line), precise, true);
  3822. },
  3823. getTokenTypeAt: function(pos) {
  3824. pos = clipPos(this.doc, pos);
  3825. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  3826. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  3827. var type;
  3828. if (ch == 0) type = styles[2];
  3829. else for (;;) {
  3830. var mid = (before + after) >> 1;
  3831. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  3832. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  3833. else { type = styles[mid * 2 + 2]; break; }
  3834. }
  3835. var cut = type ? type.indexOf("cm-overlay ") : -1;
  3836. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  3837. },
  3838. getModeAt: function(pos) {
  3839. var mode = this.doc.mode;
  3840. if (!mode.innerMode) return mode;
  3841. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  3842. },
  3843. getHelper: function(pos, type) {
  3844. return this.getHelpers(pos, type)[0];
  3845. },
  3846. getHelpers: function(pos, type) {
  3847. var found = [];
  3848. if (!helpers.hasOwnProperty(type)) return helpers;
  3849. var help = helpers[type], mode = this.getModeAt(pos);
  3850. if (typeof mode[type] == "string") {
  3851. if (help[mode[type]]) found.push(help[mode[type]]);
  3852. } else if (mode[type]) {
  3853. for (var i = 0; i < mode[type].length; i++) {
  3854. var val = help[mode[type][i]];
  3855. if (val) found.push(val);
  3856. }
  3857. } else if (mode.helperType && help[mode.helperType]) {
  3858. found.push(help[mode.helperType]);
  3859. } else if (help[mode.name]) {
  3860. found.push(help[mode.name]);
  3861. }
  3862. for (var i = 0; i < help._global.length; i++) {
  3863. var cur = help._global[i];
  3864. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  3865. found.push(cur.val);
  3866. }
  3867. return found;
  3868. },
  3869. getStateAfter: function(line, precise) {
  3870. var doc = this.doc;
  3871. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  3872. return getStateBefore(this, line + 1, precise);
  3873. },
  3874. cursorCoords: function(start, mode) {
  3875. var pos, range = this.doc.sel.primary();
  3876. if (start == null) pos = range.head;
  3877. else if (typeof start == "object") pos = clipPos(this.doc, start);
  3878. else pos = start ? range.from() : range.to();
  3879. return cursorCoords(this, pos, mode || "page");
  3880. },
  3881. charCoords: function(pos, mode) {
  3882. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  3883. },
  3884. coordsChar: function(coords, mode) {
  3885. coords = fromCoordSystem(this, coords, mode || "page");
  3886. return coordsChar(this, coords.left, coords.top);
  3887. },
  3888. lineAtHeight: function(height, mode) {
  3889. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  3890. return lineAtHeight(this.doc, height + this.display.viewOffset);
  3891. },
  3892. heightAtLine: function(line, mode) {
  3893. var end = false, last = this.doc.first + this.doc.size - 1;
  3894. if (line < this.doc.first) line = this.doc.first;
  3895. else if (line > last) { line = last; end = true; }
  3896. var lineObj = getLine(this.doc, line);
  3897. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  3898. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  3899. },
  3900. defaultTextHeight: function() { return textHeight(this.display); },
  3901. defaultCharWidth: function() { return charWidth(this.display); },
  3902. setGutterMarker: methodOp(function(line, gutterID, value) {
  3903. return changeLine(this.doc, line, "gutter", function(line) {
  3904. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  3905. markers[gutterID] = value;
  3906. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  3907. return true;
  3908. });
  3909. }),
  3910. clearGutter: methodOp(function(gutterID) {
  3911. var cm = this, doc = cm.doc, i = doc.first;
  3912. doc.iter(function(line) {
  3913. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  3914. line.gutterMarkers[gutterID] = null;
  3915. regLineChange(cm, i, "gutter");
  3916. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  3917. }
  3918. ++i;
  3919. });
  3920. }),
  3921. addLineWidget: methodOp(function(handle, node, options) {
  3922. return addLineWidget(this, handle, node, options);
  3923. }),
  3924. removeLineWidget: function(widget) { widget.clear(); },
  3925. lineInfo: function(line) {
  3926. if (typeof line == "number") {
  3927. if (!isLine(this.doc, line)) return null;
  3928. var n = line;
  3929. line = getLine(this.doc, line);
  3930. if (!line) return null;
  3931. } else {
  3932. var n = lineNo(line);
  3933. if (n == null) return null;
  3934. }
  3935. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  3936. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  3937. widgets: line.widgets};
  3938. },
  3939. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  3940. addWidget: function(pos, node, scroll, vert, horiz) {
  3941. var display = this.display;
  3942. pos = cursorCoords(this, clipPos(this.doc, pos));
  3943. var top = pos.bottom, left = pos.left;
  3944. node.style.position = "absolute";
  3945. node.setAttribute("cm-ignore-events", "true");
  3946. display.sizer.appendChild(node);
  3947. if (vert == "over") {
  3948. top = pos.top;
  3949. } else if (vert == "above" || vert == "near") {
  3950. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  3951. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  3952. // Default to positioning above (if specified and possible); otherwise default to positioning below
  3953. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  3954. top = pos.top - node.offsetHeight;
  3955. else if (pos.bottom + node.offsetHeight <= vspace)
  3956. top = pos.bottom;
  3957. if (left + node.offsetWidth > hspace)
  3958. left = hspace - node.offsetWidth;
  3959. }
  3960. node.style.top = top + "px";
  3961. node.style.left = node.style.right = "";
  3962. if (horiz == "right") {
  3963. left = display.sizer.clientWidth - node.offsetWidth;
  3964. node.style.right = "0px";
  3965. } else {
  3966. if (horiz == "left") left = 0;
  3967. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  3968. node.style.left = left + "px";
  3969. }
  3970. if (scroll)
  3971. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  3972. },
  3973. triggerOnKeyDown: methodOp(onKeyDown),
  3974. triggerOnKeyPress: methodOp(onKeyPress),
  3975. triggerOnKeyUp: onKeyUp,
  3976. execCommand: function(cmd) {
  3977. if (commands.hasOwnProperty(cmd))
  3978. return commands[cmd](this);
  3979. },
  3980. findPosH: function(from, amount, unit, visually) {
  3981. var dir = 1;
  3982. if (amount < 0) { dir = -1; amount = -amount; }
  3983. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  3984. cur = findPosH(this.doc, cur, dir, unit, visually);
  3985. if (cur.hitSide) break;
  3986. }
  3987. return cur;
  3988. },
  3989. moveH: methodOp(function(dir, unit) {
  3990. var cm = this;
  3991. cm.extendSelectionsBy(function(range) {
  3992. if (cm.display.shift || cm.doc.extend || range.empty())
  3993. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  3994. else
  3995. return dir < 0 ? range.from() : range.to();
  3996. }, sel_move);
  3997. }),
  3998. deleteH: methodOp(function(dir, unit) {
  3999. var sel = this.doc.sel, doc = this.doc;
  4000. if (sel.somethingSelected())
  4001. doc.replaceSelection("", null, "+delete");
  4002. else
  4003. deleteNearSelection(this, function(range) {
  4004. var other = findPosH(doc, range.head, dir, unit, false);
  4005. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4006. });
  4007. }),
  4008. findPosV: function(from, amount, unit, goalColumn) {
  4009. var dir = 1, x = goalColumn;
  4010. if (amount < 0) { dir = -1; amount = -amount; }
  4011. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4012. var coords = cursorCoords(this, cur, "div");
  4013. if (x == null) x = coords.left;
  4014. else coords.left = x;
  4015. cur = findPosV(this, coords, dir, unit);
  4016. if (cur.hitSide) break;
  4017. }
  4018. return cur;
  4019. },
  4020. moveV: methodOp(function(dir, unit) {
  4021. var cm = this, doc = this.doc, goals = [];
  4022. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4023. doc.extendSelectionsBy(function(range) {
  4024. if (collapse)
  4025. return dir < 0 ? range.from() : range.to();
  4026. var headPos = cursorCoords(cm, range.head, "div");
  4027. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4028. goals.push(headPos.left);
  4029. var pos = findPosV(cm, headPos, dir, unit);
  4030. if (unit == "page" && range == doc.sel.primary())
  4031. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4032. return pos;
  4033. }, sel_move);
  4034. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4035. doc.sel.ranges[i].goalColumn = goals[i];
  4036. }),
  4037. // Find the word at the given position (as returned by coordsChar).
  4038. findWordAt: function(pos) {
  4039. var doc = this.doc, line = getLine(doc, pos.line).text;
  4040. var start = pos.ch, end = pos.ch;
  4041. if (line) {
  4042. var helper = this.getHelper(pos, "wordChars");
  4043. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4044. var startChar = line.charAt(start);
  4045. var check = isWordChar(startChar, helper)
  4046. ? function(ch) { return isWordChar(ch, helper); }
  4047. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4048. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4049. while (start > 0 && check(line.charAt(start - 1))) --start;
  4050. while (end < line.length && check(line.charAt(end))) ++end;
  4051. }
  4052. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4053. },
  4054. toggleOverwrite: function(value) {
  4055. if (value != null && value == this.state.overwrite) return;
  4056. if (this.state.overwrite = !this.state.overwrite)
  4057. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4058. else
  4059. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4060. signal(this, "overwriteToggle", this, this.state.overwrite);
  4061. },
  4062. hasFocus: function() { return activeElt() == this.display.input; },
  4063. scrollTo: methodOp(function(x, y) {
  4064. if (x != null || y != null) resolveScrollToPos(this);
  4065. if (x != null) this.curOp.scrollLeft = x;
  4066. if (y != null) this.curOp.scrollTop = y;
  4067. }),
  4068. getScrollInfo: function() {
  4069. var scroller = this.display.scroller;
  4070. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4071. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4072. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4073. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4074. },
  4075. scrollIntoView: methodOp(function(range, margin) {
  4076. if (range == null) {
  4077. range = {from: this.doc.sel.primary().head, to: null};
  4078. if (margin == null) margin = this.options.cursorScrollMargin;
  4079. } else if (typeof range == "number") {
  4080. range = {from: Pos(range, 0), to: null};
  4081. } else if (range.from == null) {
  4082. range = {from: range, to: null};
  4083. }
  4084. if (!range.to) range.to = range.from;
  4085. range.margin = margin || 0;
  4086. if (range.from.line != null) {
  4087. resolveScrollToPos(this);
  4088. this.curOp.scrollToPos = range;
  4089. } else {
  4090. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4091. Math.min(range.from.top, range.to.top) - range.margin,
  4092. Math.max(range.from.right, range.to.right),
  4093. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4094. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4095. }
  4096. }),
  4097. setSize: methodOp(function(width, height) {
  4098. var cm = this;
  4099. function interpret(val) {
  4100. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4101. }
  4102. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4103. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4104. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4105. var lineNo = cm.display.viewFrom;
  4106. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4107. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4108. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4109. ++lineNo;
  4110. });
  4111. cm.curOp.forceUpdate = true;
  4112. signal(cm, "refresh", this);
  4113. }),
  4114. operation: function(f){return runInOp(this, f);},
  4115. refresh: methodOp(function() {
  4116. var oldHeight = this.display.cachedTextHeight;
  4117. regChange(this);
  4118. this.curOp.forceUpdate = true;
  4119. clearCaches(this);
  4120. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4121. updateGutterSpace(this);
  4122. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4123. estimateLineHeights(this);
  4124. signal(this, "refresh", this);
  4125. }),
  4126. swapDoc: methodOp(function(doc) {
  4127. var old = this.doc;
  4128. old.cm = null;
  4129. attachDoc(this, doc);
  4130. clearCaches(this);
  4131. resetInput(this);
  4132. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4133. this.curOp.forceScroll = true;
  4134. signalLater(this, "swapDoc", this, old);
  4135. return old;
  4136. }),
  4137. getInputField: function(){return this.display.input;},
  4138. getWrapperElement: function(){return this.display.wrapper;},
  4139. getScrollerElement: function(){return this.display.scroller;},
  4140. getGutterElement: function(){return this.display.gutters;}
  4141. };
  4142. eventMixin(CodeMirror);
  4143. // OPTION DEFAULTS
  4144. // The default configuration options.
  4145. var defaults = CodeMirror.defaults = {};
  4146. // Functions to run when options are changed.
  4147. var optionHandlers = CodeMirror.optionHandlers = {};
  4148. function option(name, deflt, handle, notOnInit) {
  4149. CodeMirror.defaults[name] = deflt;
  4150. if (handle) optionHandlers[name] =
  4151. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4152. }
  4153. // Passed to option handlers when there is no old value.
  4154. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4155. // These two are, on init, called from the constructor because they
  4156. // have to be initialized before the editor can start at all.
  4157. option("value", "", function(cm, val) {
  4158. cm.setValue(val);
  4159. }, true);
  4160. option("mode", null, function(cm, val) {
  4161. cm.doc.modeOption = val;
  4162. loadMode(cm);
  4163. }, true);
  4164. option("indentUnit", 2, loadMode, true);
  4165. option("indentWithTabs", false);
  4166. option("smartIndent", true);
  4167. option("tabSize", 4, function(cm) {
  4168. resetModeState(cm);
  4169. clearCaches(cm);
  4170. regChange(cm);
  4171. }, true);
  4172. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val) {
  4173. cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4174. cm.refresh();
  4175. }, true);
  4176. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4177. option("electricChars", true);
  4178. option("rtlMoveVisually", !windows);
  4179. option("wholeLineUpdateBefore", true);
  4180. option("theme", "default", function(cm) {
  4181. themeChanged(cm);
  4182. guttersChanged(cm);
  4183. }, true);
  4184. option("keyMap", "default", function(cm, val, old) {
  4185. var next = getKeyMap(val);
  4186. var prev = old != CodeMirror.Init && getKeyMap(old);
  4187. if (prev && prev.detach) prev.detach(cm, next);
  4188. if (next.attach) next.attach(cm, prev || null);
  4189. });
  4190. option("extraKeys", null);
  4191. option("lineWrapping", false, wrappingChanged, true);
  4192. option("gutters", [], function(cm) {
  4193. setGuttersForLineNumbers(cm.options);
  4194. guttersChanged(cm);
  4195. }, true);
  4196. option("fixedGutter", true, function(cm, val) {
  4197. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4198. cm.refresh();
  4199. }, true);
  4200. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4201. option("scrollbarStyle", "native", function(cm) {
  4202. initScrollbars(cm);
  4203. updateScrollbars(cm);
  4204. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4205. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4206. }, true);
  4207. option("lineNumbers", false, function(cm) {
  4208. setGuttersForLineNumbers(cm.options);
  4209. guttersChanged(cm);
  4210. }, true);
  4211. option("firstLineNumber", 1, guttersChanged, true);
  4212. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4213. option("showCursorWhenSelecting", false, updateSelection, true);
  4214. option("resetSelectionOnContextMenu", true);
  4215. option("readOnly", false, function(cm, val) {
  4216. if (val == "nocursor") {
  4217. onBlur(cm);
  4218. cm.display.input.blur();
  4219. cm.display.disabled = true;
  4220. } else {
  4221. cm.display.disabled = false;
  4222. if (!val) resetInput(cm);
  4223. }
  4224. });
  4225. option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true);
  4226. option("dragDrop", true);
  4227. option("cursorBlinkRate", 530);
  4228. option("cursorScrollMargin", 0);
  4229. option("cursorHeight", 1, updateSelection, true);
  4230. option("singleCursorHeightPerLine", true, updateSelection, true);
  4231. option("workTime", 100);
  4232. option("workDelay", 100);
  4233. option("flattenSpans", true, resetModeState, true);
  4234. option("addModeClass", false, resetModeState, true);
  4235. option("pollInterval", 100);
  4236. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4237. option("historyEventDelay", 1250);
  4238. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4239. option("maxHighlightLength", 10000, resetModeState, true);
  4240. option("moveInputWithCursor", true, function(cm, val) {
  4241. if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
  4242. });
  4243. option("tabindex", null, function(cm, val) {
  4244. cm.display.input.tabIndex = val || "";
  4245. });
  4246. option("autofocus", null);
  4247. // MODE DEFINITION AND QUERYING
  4248. // Known modes, by name and by MIME
  4249. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4250. // Extra arguments are stored as the mode's dependencies, which is
  4251. // used by (legacy) mechanisms like loadmode.js to automatically
  4252. // load a mode. (Preferred mechanism is the require/define calls.)
  4253. CodeMirror.defineMode = function(name, mode) {
  4254. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4255. if (arguments.length > 2)
  4256. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4257. modes[name] = mode;
  4258. };
  4259. CodeMirror.defineMIME = function(mime, spec) {
  4260. mimeModes[mime] = spec;
  4261. };
  4262. // Given a MIME type, a {name, ...options} config object, or a name
  4263. // string, return a mode config object.
  4264. CodeMirror.resolveMode = function(spec) {
  4265. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4266. spec = mimeModes[spec];
  4267. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4268. var found = mimeModes[spec.name];
  4269. if (typeof found == "string") found = {name: found};
  4270. spec = createObj(found, spec);
  4271. spec.name = found.name;
  4272. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4273. return CodeMirror.resolveMode("application/xml");
  4274. }
  4275. if (typeof spec == "string") return {name: spec};
  4276. else return spec || {name: "null"};
  4277. };
  4278. // Given a mode spec (anything that resolveMode accepts), find and
  4279. // initialize an actual mode object.
  4280. CodeMirror.getMode = function(options, spec) {
  4281. var spec = CodeMirror.resolveMode(spec);
  4282. var mfactory = modes[spec.name];
  4283. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4284. var modeObj = mfactory(options, spec);
  4285. if (modeExtensions.hasOwnProperty(spec.name)) {
  4286. var exts = modeExtensions[spec.name];
  4287. for (var prop in exts) {
  4288. if (!exts.hasOwnProperty(prop)) continue;
  4289. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4290. modeObj[prop] = exts[prop];
  4291. }
  4292. }
  4293. modeObj.name = spec.name;
  4294. if (spec.helperType) modeObj.helperType = spec.helperType;
  4295. if (spec.modeProps) for (var prop in spec.modeProps)
  4296. modeObj[prop] = spec.modeProps[prop];
  4297. return modeObj;
  4298. };
  4299. // Minimal default mode.
  4300. CodeMirror.defineMode("null", function() {
  4301. return {token: function(stream) {stream.skipToEnd();}};
  4302. });
  4303. CodeMirror.defineMIME("text/plain", "null");
  4304. // This can be used to attach properties to mode objects from
  4305. // outside the actual mode definition.
  4306. var modeExtensions = CodeMirror.modeExtensions = {};
  4307. CodeMirror.extendMode = function(mode, properties) {
  4308. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4309. copyObj(properties, exts);
  4310. };
  4311. // EXTENSIONS
  4312. CodeMirror.defineExtension = function(name, func) {
  4313. CodeMirror.prototype[name] = func;
  4314. };
  4315. CodeMirror.defineDocExtension = function(name, func) {
  4316. Doc.prototype[name] = func;
  4317. };
  4318. CodeMirror.defineOption = option;
  4319. var initHooks = [];
  4320. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  4321. var helpers = CodeMirror.helpers = {};
  4322. CodeMirror.registerHelper = function(type, name, value) {
  4323. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  4324. helpers[type][name] = value;
  4325. };
  4326. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  4327. CodeMirror.registerHelper(type, name, value);
  4328. helpers[type]._global.push({pred: predicate, val: value});
  4329. };
  4330. // MODE STATE HANDLING
  4331. // Utility functions for working with state. Exported because nested
  4332. // modes need to do this for their inner modes.
  4333. var copyState = CodeMirror.copyState = function(mode, state) {
  4334. if (state === true) return state;
  4335. if (mode.copyState) return mode.copyState(state);
  4336. var nstate = {};
  4337. for (var n in state) {
  4338. var val = state[n];
  4339. if (val instanceof Array) val = val.concat([]);
  4340. nstate[n] = val;
  4341. }
  4342. return nstate;
  4343. };
  4344. var startState = CodeMirror.startState = function(mode, a1, a2) {
  4345. return mode.startState ? mode.startState(a1, a2) : true;
  4346. };
  4347. // Given a mode and a state (for that mode), find the inner mode and
  4348. // state at the position that the state refers to.
  4349. CodeMirror.innerMode = function(mode, state) {
  4350. while (mode.innerMode) {
  4351. var info = mode.innerMode(state);
  4352. if (!info || info.mode == mode) break;
  4353. state = info.state;
  4354. mode = info.mode;
  4355. }
  4356. return info || {mode: mode, state: state};
  4357. };
  4358. // STANDARD COMMANDS
  4359. // Commands are parameter-less actions that can be performed on an
  4360. // editor, mostly used for keybindings.
  4361. var commands = CodeMirror.commands = {
  4362. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  4363. singleSelection: function(cm) {
  4364. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  4365. },
  4366. killLine: function(cm) {
  4367. deleteNearSelection(cm, function(range) {
  4368. if (range.empty()) {
  4369. var len = getLine(cm.doc, range.head.line).text.length;
  4370. if (range.head.ch == len && range.head.line < cm.lastLine())
  4371. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  4372. else
  4373. return {from: range.head, to: Pos(range.head.line, len)};
  4374. } else {
  4375. return {from: range.from(), to: range.to()};
  4376. }
  4377. });
  4378. },
  4379. deleteLine: function(cm) {
  4380. deleteNearSelection(cm, function(range) {
  4381. return {from: Pos(range.from().line, 0),
  4382. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  4383. });
  4384. },
  4385. delLineLeft: function(cm) {
  4386. deleteNearSelection(cm, function(range) {
  4387. return {from: Pos(range.from().line, 0), to: range.from()};
  4388. });
  4389. },
  4390. delWrappedLineLeft: function(cm) {
  4391. deleteNearSelection(cm, function(range) {
  4392. var top = cm.charCoords(range.head, "div").top + 5;
  4393. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  4394. return {from: leftPos, to: range.from()};
  4395. });
  4396. },
  4397. delWrappedLineRight: function(cm) {
  4398. deleteNearSelection(cm, function(range) {
  4399. var top = cm.charCoords(range.head, "div").top + 5;
  4400. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4401. return {from: range.from(), to: rightPos };
  4402. });
  4403. },
  4404. undo: function(cm) {cm.undo();},
  4405. redo: function(cm) {cm.redo();},
  4406. undoSelection: function(cm) {cm.undoSelection();},
  4407. redoSelection: function(cm) {cm.redoSelection();},
  4408. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  4409. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  4410. goLineStart: function(cm) {
  4411. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  4412. {origin: "+move", bias: 1});
  4413. },
  4414. goLineStartSmart: function(cm) {
  4415. cm.extendSelectionsBy(function(range) {
  4416. return lineStartSmart(cm, range.head);
  4417. }, {origin: "+move", bias: 1});
  4418. },
  4419. goLineEnd: function(cm) {
  4420. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  4421. {origin: "+move", bias: -1});
  4422. },
  4423. goLineRight: function(cm) {
  4424. cm.extendSelectionsBy(function(range) {
  4425. var top = cm.charCoords(range.head, "div").top + 5;
  4426. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4427. }, sel_move);
  4428. },
  4429. goLineLeft: function(cm) {
  4430. cm.extendSelectionsBy(function(range) {
  4431. var top = cm.charCoords(range.head, "div").top + 5;
  4432. return cm.coordsChar({left: 0, top: top}, "div");
  4433. }, sel_move);
  4434. },
  4435. goLineLeftSmart: function(cm) {
  4436. cm.extendSelectionsBy(function(range) {
  4437. var top = cm.charCoords(range.head, "div").top + 5;
  4438. var pos = cm.coordsChar({left: 0, top: top}, "div");
  4439. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  4440. return pos;
  4441. }, sel_move);
  4442. },
  4443. goLineUp: function(cm) {cm.moveV(-1, "line");},
  4444. goLineDown: function(cm) {cm.moveV(1, "line");},
  4445. goPageUp: function(cm) {cm.moveV(-1, "page");},
  4446. goPageDown: function(cm) {cm.moveV(1, "page");},
  4447. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  4448. goCharRight: function(cm) {cm.moveH(1, "char");},
  4449. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  4450. goColumnRight: function(cm) {cm.moveH(1, "column");},
  4451. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  4452. goGroupRight: function(cm) {cm.moveH(1, "group");},
  4453. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  4454. goWordRight: function(cm) {cm.moveH(1, "word");},
  4455. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  4456. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  4457. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  4458. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  4459. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  4460. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  4461. indentAuto: function(cm) {cm.indentSelection("smart");},
  4462. indentMore: function(cm) {cm.indentSelection("add");},
  4463. indentLess: function(cm) {cm.indentSelection("subtract");},
  4464. insertTab: function(cm) {cm.replaceSelection("\t");},
  4465. insertSoftTab: function(cm) {
  4466. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  4467. for (var i = 0; i < ranges.length; i++) {
  4468. var pos = ranges[i].from();
  4469. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  4470. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  4471. }
  4472. cm.replaceSelections(spaces);
  4473. },
  4474. defaultTab: function(cm) {
  4475. if (cm.somethingSelected()) cm.indentSelection("add");
  4476. else cm.execCommand("insertTab");
  4477. },
  4478. transposeChars: function(cm) {
  4479. runInOp(cm, function() {
  4480. var ranges = cm.listSelections(), newSel = [];
  4481. for (var i = 0; i < ranges.length; i++) {
  4482. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  4483. if (line) {
  4484. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  4485. if (cur.ch > 0) {
  4486. cur = new Pos(cur.line, cur.ch + 1);
  4487. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  4488. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  4489. } else if (cur.line > cm.doc.first) {
  4490. var prev = getLine(cm.doc, cur.line - 1).text;
  4491. if (prev)
  4492. cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
  4493. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  4494. }
  4495. }
  4496. newSel.push(new Range(cur, cur));
  4497. }
  4498. cm.setSelections(newSel);
  4499. });
  4500. },
  4501. newlineAndIndent: function(cm) {
  4502. runInOp(cm, function() {
  4503. var len = cm.listSelections().length;
  4504. for (var i = 0; i < len; i++) {
  4505. var range = cm.listSelections()[i];
  4506. cm.replaceRange("\n", range.anchor, range.head, "+input");
  4507. cm.indentLine(range.from().line + 1, null, true);
  4508. ensureCursorVisible(cm);
  4509. }
  4510. });
  4511. },
  4512. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  4513. };
  4514. // STANDARD KEYMAPS
  4515. var keyMap = CodeMirror.keyMap = {};
  4516. keyMap.basic = {
  4517. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  4518. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  4519. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  4520. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  4521. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  4522. "Esc": "singleSelection"
  4523. };
  4524. // Note that the save and find-related commands aren't defined by
  4525. // default. User code or addons can define them. Unknown commands
  4526. // are simply ignored.
  4527. keyMap.pcDefault = {
  4528. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  4529. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  4530. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  4531. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  4532. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  4533. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  4534. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  4535. fallthrough: "basic"
  4536. };
  4537. // Very basic readline/emacs-style bindings, which are standard on Mac.
  4538. keyMap.emacsy = {
  4539. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  4540. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  4541. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  4542. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  4543. };
  4544. keyMap.macDefault = {
  4545. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  4546. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  4547. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  4548. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  4549. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  4550. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  4551. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  4552. fallthrough: ["basic", "emacsy"]
  4553. };
  4554. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  4555. // KEYMAP DISPATCH
  4556. function normalizeKeyName(name) {
  4557. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  4558. var alt, ctrl, shift, cmd;
  4559. for (var i = 0; i < parts.length - 1; i++) {
  4560. var mod = parts[i];
  4561. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  4562. else if (/^a(lt)?$/i.test(mod)) alt = true;
  4563. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  4564. else if (/^s(hift)$/i.test(mod)) shift = true;
  4565. else throw new Error("Unrecognized modifier name: " + mod);
  4566. }
  4567. if (alt) name = "Alt-" + name;
  4568. if (ctrl) name = "Ctrl-" + name;
  4569. if (cmd) name = "Cmd-" + name;
  4570. if (shift) name = "Shift-" + name;
  4571. return name;
  4572. }
  4573. // This is a kludge to keep keymaps mostly working as raw objects
  4574. // (backwards compatibility) while at the same time support features
  4575. // like normalization and multi-stroke key bindings. It compiles a
  4576. // new normalized keymap, and then updates the old object to reflect
  4577. // this.
  4578. CodeMirror.normalizeKeyMap = function(keymap) {
  4579. var copy = {};
  4580. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  4581. var value = keymap[keyname];
  4582. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  4583. if (value == "...") { delete keymap[keyname]; continue; }
  4584. var keys = map(keyname.split(" "), normalizeKeyName);
  4585. for (var i = 0; i < keys.length; i++) {
  4586. var val, name;
  4587. if (i == keys.length - 1) {
  4588. name = keyname;
  4589. val = value;
  4590. } else {
  4591. name = keys.slice(0, i + 1).join(" ");
  4592. val = "...";
  4593. }
  4594. var prev = copy[name];
  4595. if (!prev) copy[name] = val;
  4596. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  4597. }
  4598. delete keymap[keyname];
  4599. }
  4600. for (var prop in copy) keymap[prop] = copy[prop];
  4601. return keymap;
  4602. };
  4603. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  4604. map = getKeyMap(map);
  4605. var found = map.call ? map.call(key, context) : map[key];
  4606. if (found === false) return "nothing";
  4607. if (found === "...") return "multi";
  4608. if (found != null && handle(found)) return "handled";
  4609. if (map.fallthrough) {
  4610. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  4611. return lookupKey(key, map.fallthrough, handle, context);
  4612. for (var i = 0; i < map.fallthrough.length; i++) {
  4613. var result = lookupKey(key, map.fallthrough[i], handle, context);
  4614. if (result) return result;
  4615. }
  4616. }
  4617. };
  4618. // Modifier key presses don't count as 'real' key presses for the
  4619. // purpose of keymap fallthrough.
  4620. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  4621. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  4622. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  4623. };
  4624. // Look up the name of a key as indicated by an event object.
  4625. var keyName = CodeMirror.keyName = function(event, noShift) {
  4626. if (presto && event.keyCode == 34 && event["char"]) return false;
  4627. var base = keyNames[event.keyCode], name = base;
  4628. if (name == null || event.altGraphKey) return false;
  4629. if (event.altKey && base != "Alt") name = "Alt-" + name;
  4630. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  4631. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  4632. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  4633. return name;
  4634. };
  4635. function getKeyMap(val) {
  4636. return typeof val == "string" ? keyMap[val] : val;
  4637. }
  4638. // FROMTEXTAREA
  4639. CodeMirror.fromTextArea = function(textarea, options) {
  4640. options = options ? copyObj(options) : {};
  4641. options.value = textarea.value;
  4642. if (!options.tabindex && textarea.tabindex)
  4643. options.tabindex = textarea.tabindex;
  4644. if (!options.placeholder && textarea.placeholder)
  4645. options.placeholder = textarea.placeholder;
  4646. // Set autofocus to true if this textarea is focused, or if it has
  4647. // autofocus and no other element is focused.
  4648. if (options.autofocus == null) {
  4649. var hasFocus = activeElt();
  4650. options.autofocus = hasFocus == textarea ||
  4651. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  4652. }
  4653. function save() {textarea.value = cm.getValue();}
  4654. if (textarea.form) {
  4655. on(textarea.form, "submit", save);
  4656. // Deplorable hack to make the submit method do the right thing.
  4657. if (!options.leaveSubmitMethodAlone) {
  4658. var form = textarea.form, realSubmit = form.submit;
  4659. try {
  4660. var wrappedSubmit = form.submit = function() {
  4661. save();
  4662. form.submit = realSubmit;
  4663. form.submit();
  4664. form.submit = wrappedSubmit;
  4665. };
  4666. } catch(e) {}
  4667. }
  4668. }
  4669. options.finishInit = function(cm) {
  4670. cm.save = save;
  4671. cm.getTextArea = function() { return textarea; };
  4672. cm.toTextArea = function() {
  4673. cm.toTextArea = isNaN; // Prevent this from being ran twice
  4674. save();
  4675. textarea.parentNode.removeChild(cm.getWrapperElement());
  4676. textarea.style.display = "";
  4677. if (textarea.form) {
  4678. off(textarea.form, "submit", save);
  4679. if (typeof textarea.form.submit == "function")
  4680. textarea.form.submit = realSubmit;
  4681. }
  4682. };
  4683. };
  4684. textarea.style.display = "none";
  4685. var cm = CodeMirror(function(node) {
  4686. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  4687. }, options);
  4688. return cm;
  4689. };
  4690. // STRING STREAM
  4691. // Fed to the mode parsers, provides helper functions to make
  4692. // parsers more succinct.
  4693. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  4694. this.pos = this.start = 0;
  4695. this.string = string;
  4696. this.tabSize = tabSize || 8;
  4697. this.lastColumnPos = this.lastColumnValue = 0;
  4698. this.lineStart = 0;
  4699. };
  4700. StringStream.prototype = {
  4701. eol: function() {return this.pos >= this.string.length;},
  4702. sol: function() {return this.pos == this.lineStart;},
  4703. peek: function() {return this.string.charAt(this.pos) || undefined;},
  4704. next: function() {
  4705. if (this.pos < this.string.length)
  4706. return this.string.charAt(this.pos++);
  4707. },
  4708. eat: function(match) {
  4709. var ch = this.string.charAt(this.pos);
  4710. if (typeof match == "string") var ok = ch == match;
  4711. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  4712. if (ok) {++this.pos; return ch;}
  4713. },
  4714. eatWhile: function(match) {
  4715. var start = this.pos;
  4716. while (this.eat(match)){}
  4717. return this.pos > start;
  4718. },
  4719. eatSpace: function() {
  4720. var start = this.pos;
  4721. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  4722. return this.pos > start;
  4723. },
  4724. skipToEnd: function() {this.pos = this.string.length;},
  4725. skipTo: function(ch) {
  4726. var found = this.string.indexOf(ch, this.pos);
  4727. if (found > -1) {this.pos = found; return true;}
  4728. },
  4729. backUp: function(n) {this.pos -= n;},
  4730. column: function() {
  4731. if (this.lastColumnPos < this.start) {
  4732. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  4733. this.lastColumnPos = this.start;
  4734. }
  4735. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  4736. },
  4737. indentation: function() {
  4738. return countColumn(this.string, null, this.tabSize) -
  4739. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  4740. },
  4741. match: function(pattern, consume, caseInsensitive) {
  4742. if (typeof pattern == "string") {
  4743. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  4744. var substr = this.string.substr(this.pos, pattern.length);
  4745. if (cased(substr) == cased(pattern)) {
  4746. if (consume !== false) this.pos += pattern.length;
  4747. return true;
  4748. }
  4749. } else {
  4750. var match = this.string.slice(this.pos).match(pattern);
  4751. if (match && match.index > 0) return null;
  4752. if (match && consume !== false) this.pos += match[0].length;
  4753. return match;
  4754. }
  4755. },
  4756. current: function(){return this.string.slice(this.start, this.pos);},
  4757. hideFirstChars: function(n, inner) {
  4758. this.lineStart += n;
  4759. try { return inner(); }
  4760. finally { this.lineStart -= n; }
  4761. }
  4762. };
  4763. // TEXTMARKERS
  4764. // Created with markText and setBookmark methods. A TextMarker is a
  4765. // handle that can be used to clear or find a marked position in the
  4766. // document. Line objects hold arrays (markedSpans) containing
  4767. // {from, to, marker} object pointing to such marker objects, and
  4768. // indicating that such a marker is present on that line. Multiple
  4769. // lines may point to the same marker when it spans across lines.
  4770. // The spans will have null for their from/to properties when the
  4771. // marker continues beyond the start/end of the line. Markers have
  4772. // links back to the lines they currently touch.
  4773. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  4774. this.lines = [];
  4775. this.type = type;
  4776. this.doc = doc;
  4777. };
  4778. eventMixin(TextMarker);
  4779. // Clear the marker.
  4780. TextMarker.prototype.clear = function() {
  4781. if (this.explicitlyCleared) return;
  4782. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  4783. if (withOp) startOperation(cm);
  4784. if (hasHandler(this, "clear")) {
  4785. var found = this.find();
  4786. if (found) signalLater(this, "clear", found.from, found.to);
  4787. }
  4788. var min = null, max = null;
  4789. for (var i = 0; i < this.lines.length; ++i) {
  4790. var line = this.lines[i];
  4791. var span = getMarkedSpanFor(line.markedSpans, this);
  4792. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  4793. else if (cm) {
  4794. if (span.to != null) max = lineNo(line);
  4795. if (span.from != null) min = lineNo(line);
  4796. }
  4797. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  4798. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  4799. updateLineHeight(line, textHeight(cm.display));
  4800. }
  4801. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  4802. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  4803. if (len > cm.display.maxLineLength) {
  4804. cm.display.maxLine = visual;
  4805. cm.display.maxLineLength = len;
  4806. cm.display.maxLineChanged = true;
  4807. }
  4808. }
  4809. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  4810. this.lines.length = 0;
  4811. this.explicitlyCleared = true;
  4812. if (this.atomic && this.doc.cantEdit) {
  4813. this.doc.cantEdit = false;
  4814. if (cm) reCheckSelection(cm.doc);
  4815. }
  4816. if (cm) signalLater(cm, "markerCleared", cm, this);
  4817. if (withOp) endOperation(cm);
  4818. if (this.parent) this.parent.clear();
  4819. };
  4820. // Find the position of the marker in the document. Returns a {from,
  4821. // to} object by default. Side can be passed to get a specific side
  4822. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  4823. // Pos objects returned contain a line object, rather than a line
  4824. // number (used to prevent looking up the same line twice).
  4825. TextMarker.prototype.find = function(side, lineObj) {
  4826. if (side == null && this.type == "bookmark") side = 1;
  4827. var from, to;
  4828. for (var i = 0; i < this.lines.length; ++i) {
  4829. var line = this.lines[i];
  4830. var span = getMarkedSpanFor(line.markedSpans, this);
  4831. if (span.from != null) {
  4832. from = Pos(lineObj ? line : lineNo(line), span.from);
  4833. if (side == -1) return from;
  4834. }
  4835. if (span.to != null) {
  4836. to = Pos(lineObj ? line : lineNo(line), span.to);
  4837. if (side == 1) return to;
  4838. }
  4839. }
  4840. return from && {from: from, to: to};
  4841. };
  4842. // Signals that the marker's widget changed, and surrounding layout
  4843. // should be recomputed.
  4844. TextMarker.prototype.changed = function() {
  4845. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  4846. if (!pos || !cm) return;
  4847. runInOp(cm, function() {
  4848. var line = pos.line, lineN = lineNo(pos.line);
  4849. var view = findViewForLine(cm, lineN);
  4850. if (view) {
  4851. clearLineMeasurementCacheFor(view);
  4852. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  4853. }
  4854. cm.curOp.updateMaxLine = true;
  4855. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  4856. var oldHeight = widget.height;
  4857. widget.height = null;
  4858. var dHeight = widgetHeight(widget) - oldHeight;
  4859. if (dHeight)
  4860. updateLineHeight(line, line.height + dHeight);
  4861. }
  4862. });
  4863. };
  4864. TextMarker.prototype.attachLine = function(line) {
  4865. if (!this.lines.length && this.doc.cm) {
  4866. var op = this.doc.cm.curOp;
  4867. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  4868. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  4869. }
  4870. this.lines.push(line);
  4871. };
  4872. TextMarker.prototype.detachLine = function(line) {
  4873. this.lines.splice(indexOf(this.lines, line), 1);
  4874. if (!this.lines.length && this.doc.cm) {
  4875. var op = this.doc.cm.curOp;
  4876. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  4877. }
  4878. };
  4879. // Collapsed markers have unique ids, in order to be able to order
  4880. // them, which is needed for uniquely determining an outer marker
  4881. // when they overlap (they may nest, but not partially overlap).
  4882. var nextMarkerId = 0;
  4883. // Create a marker, wire it up to the right lines, and
  4884. function markText(doc, from, to, options, type) {
  4885. // Shared markers (across linked documents) are handled separately
  4886. // (markTextShared will call out to this again, once per
  4887. // document).
  4888. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  4889. // Ensure we are in an operation.
  4890. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  4891. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  4892. if (options) copyObj(options, marker, false);
  4893. // Don't connect empty markers unless clearWhenEmpty is false
  4894. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  4895. return marker;
  4896. if (marker.replacedWith) {
  4897. // Showing up as a widget implies collapsed (widget replaces text)
  4898. marker.collapsed = true;
  4899. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  4900. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  4901. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  4902. }
  4903. if (marker.collapsed) {
  4904. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  4905. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  4906. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  4907. sawCollapsedSpans = true;
  4908. }
  4909. if (marker.addToHistory)
  4910. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  4911. var curLine = from.line, cm = doc.cm, updateMaxLine;
  4912. doc.iter(curLine, to.line + 1, function(line) {
  4913. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  4914. updateMaxLine = true;
  4915. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  4916. addMarkedSpan(line, new MarkedSpan(marker,
  4917. curLine == from.line ? from.ch : null,
  4918. curLine == to.line ? to.ch : null));
  4919. ++curLine;
  4920. });
  4921. // lineIsHidden depends on the presence of the spans, so needs a second pass
  4922. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  4923. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  4924. });
  4925. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  4926. if (marker.readOnly) {
  4927. sawReadOnlySpans = true;
  4928. if (doc.history.done.length || doc.history.undone.length)
  4929. doc.clearHistory();
  4930. }
  4931. if (marker.collapsed) {
  4932. marker.id = ++nextMarkerId;
  4933. marker.atomic = true;
  4934. }
  4935. if (cm) {
  4936. // Sync editor state
  4937. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  4938. if (marker.collapsed)
  4939. regChange(cm, from.line, to.line + 1);
  4940. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  4941. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  4942. if (marker.atomic) reCheckSelection(cm.doc);
  4943. signalLater(cm, "markerAdded", cm, marker);
  4944. }
  4945. return marker;
  4946. }
  4947. // SHARED TEXTMARKERS
  4948. // A shared marker spans multiple linked documents. It is
  4949. // implemented as a meta-marker-object controlling multiple normal
  4950. // markers.
  4951. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  4952. this.markers = markers;
  4953. this.primary = primary;
  4954. for (var i = 0; i < markers.length; ++i)
  4955. markers[i].parent = this;
  4956. };
  4957. eventMixin(SharedTextMarker);
  4958. SharedTextMarker.prototype.clear = function() {
  4959. if (this.explicitlyCleared) return;
  4960. this.explicitlyCleared = true;
  4961. for (var i = 0; i < this.markers.length; ++i)
  4962. this.markers[i].clear();
  4963. signalLater(this, "clear");
  4964. };
  4965. SharedTextMarker.prototype.find = function(side, lineObj) {
  4966. return this.primary.find(side, lineObj);
  4967. };
  4968. function markTextShared(doc, from, to, options, type) {
  4969. options = copyObj(options);
  4970. options.shared = false;
  4971. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  4972. var widget = options.widgetNode;
  4973. linkedDocs(doc, function(doc) {
  4974. if (widget) options.widgetNode = widget.cloneNode(true);
  4975. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  4976. for (var i = 0; i < doc.linked.length; ++i)
  4977. if (doc.linked[i].isParent) return;
  4978. primary = lst(markers);
  4979. });
  4980. return new SharedTextMarker(markers, primary);
  4981. }
  4982. function findSharedMarkers(doc) {
  4983. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  4984. function(m) { return m.parent; });
  4985. }
  4986. function copySharedMarkers(doc, markers) {
  4987. for (var i = 0; i < markers.length; i++) {
  4988. var marker = markers[i], pos = marker.find();
  4989. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  4990. if (cmp(mFrom, mTo)) {
  4991. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  4992. marker.markers.push(subMark);
  4993. subMark.parent = marker;
  4994. }
  4995. }
  4996. }
  4997. function detachSharedMarkers(markers) {
  4998. for (var i = 0; i < markers.length; i++) {
  4999. var marker = markers[i], linked = [marker.primary.doc];;
  5000. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5001. for (var j = 0; j < marker.markers.length; j++) {
  5002. var subMarker = marker.markers[j];
  5003. if (indexOf(linked, subMarker.doc) == -1) {
  5004. subMarker.parent = null;
  5005. marker.markers.splice(j--, 1);
  5006. }
  5007. }
  5008. }
  5009. }
  5010. // TEXTMARKER SPANS
  5011. function MarkedSpan(marker, from, to) {
  5012. this.marker = marker;
  5013. this.from = from; this.to = to;
  5014. }
  5015. // Search an array of spans for a span matching the given marker.
  5016. function getMarkedSpanFor(spans, marker) {
  5017. if (spans) for (var i = 0; i < spans.length; ++i) {
  5018. var span = spans[i];
  5019. if (span.marker == marker) return span;
  5020. }
  5021. }
  5022. // Remove a span from an array, returning undefined if no spans are
  5023. // left (we don't store arrays for lines without spans).
  5024. function removeMarkedSpan(spans, span) {
  5025. for (var r, i = 0; i < spans.length; ++i)
  5026. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5027. return r;
  5028. }
  5029. // Add a span to a line.
  5030. function addMarkedSpan(line, span) {
  5031. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5032. span.marker.attachLine(line);
  5033. }
  5034. // Used for the algorithm that adjusts markers for a change in the
  5035. // document. These functions cut an array of spans at a given
  5036. // character position, returning an array of remaining chunks (or
  5037. // undefined if nothing remains).
  5038. function markedSpansBefore(old, startCh, isInsert) {
  5039. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5040. var span = old[i], marker = span.marker;
  5041. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5042. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5043. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5044. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5045. }
  5046. }
  5047. return nw;
  5048. }
  5049. function markedSpansAfter(old, endCh, isInsert) {
  5050. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5051. var span = old[i], marker = span.marker;
  5052. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5053. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5054. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5055. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5056. span.to == null ? null : span.to - endCh));
  5057. }
  5058. }
  5059. return nw;
  5060. }
  5061. // Given a change object, compute the new set of marker spans that
  5062. // cover the line in which the change took place. Removes spans
  5063. // entirely within the change, reconnects spans belonging to the
  5064. // same marker that appear on both sides of the change, and cuts off
  5065. // spans partially within the change. Returns an array of span
  5066. // arrays with one element for each line in (after) the change.
  5067. function stretchSpansOverChange(doc, change) {
  5068. if (change.full) return null;
  5069. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5070. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5071. if (!oldFirst && !oldLast) return null;
  5072. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5073. // Get the spans that 'stick out' on both sides
  5074. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5075. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5076. // Next, merge those two ends
  5077. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5078. if (first) {
  5079. // Fix up .to properties of first
  5080. for (var i = 0; i < first.length; ++i) {
  5081. var span = first[i];
  5082. if (span.to == null) {
  5083. var found = getMarkedSpanFor(last, span.marker);
  5084. if (!found) span.to = startCh;
  5085. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5086. }
  5087. }
  5088. }
  5089. if (last) {
  5090. // Fix up .from in last (or move them into first in case of sameLine)
  5091. for (var i = 0; i < last.length; ++i) {
  5092. var span = last[i];
  5093. if (span.to != null) span.to += offset;
  5094. if (span.from == null) {
  5095. var found = getMarkedSpanFor(first, span.marker);
  5096. if (!found) {
  5097. span.from = offset;
  5098. if (sameLine) (first || (first = [])).push(span);
  5099. }
  5100. } else {
  5101. span.from += offset;
  5102. if (sameLine) (first || (first = [])).push(span);
  5103. }
  5104. }
  5105. }
  5106. // Make sure we didn't create any zero-length spans
  5107. if (first) first = clearEmptySpans(first);
  5108. if (last && last != first) last = clearEmptySpans(last);
  5109. var newMarkers = [first];
  5110. if (!sameLine) {
  5111. // Fill gap with whole-line-spans
  5112. var gap = change.text.length - 2, gapMarkers;
  5113. if (gap > 0 && first)
  5114. for (var i = 0; i < first.length; ++i)
  5115. if (first[i].to == null)
  5116. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5117. for (var i = 0; i < gap; ++i)
  5118. newMarkers.push(gapMarkers);
  5119. newMarkers.push(last);
  5120. }
  5121. return newMarkers;
  5122. }
  5123. // Remove spans that are empty and don't have a clearWhenEmpty
  5124. // option of false.
  5125. function clearEmptySpans(spans) {
  5126. for (var i = 0; i < spans.length; ++i) {
  5127. var span = spans[i];
  5128. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5129. spans.splice(i--, 1);
  5130. }
  5131. if (!spans.length) return null;
  5132. return spans;
  5133. }
  5134. // Used for un/re-doing changes from the history. Combines the
  5135. // result of computing the existing spans with the set of spans that
  5136. // existed in the history (so that deleting around a span and then
  5137. // undoing brings back the span).
  5138. function mergeOldSpans(doc, change) {
  5139. var old = getOldSpans(doc, change);
  5140. var stretched = stretchSpansOverChange(doc, change);
  5141. if (!old) return stretched;
  5142. if (!stretched) return old;
  5143. for (var i = 0; i < old.length; ++i) {
  5144. var oldCur = old[i], stretchCur = stretched[i];
  5145. if (oldCur && stretchCur) {
  5146. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5147. var span = stretchCur[j];
  5148. for (var k = 0; k < oldCur.length; ++k)
  5149. if (oldCur[k].marker == span.marker) continue spans;
  5150. oldCur.push(span);
  5151. }
  5152. } else if (stretchCur) {
  5153. old[i] = stretchCur;
  5154. }
  5155. }
  5156. return old;
  5157. }
  5158. // Used to 'clip' out readOnly ranges when making a change.
  5159. function removeReadOnlyRanges(doc, from, to) {
  5160. var markers = null;
  5161. doc.iter(from.line, to.line + 1, function(line) {
  5162. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5163. var mark = line.markedSpans[i].marker;
  5164. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5165. (markers || (markers = [])).push(mark);
  5166. }
  5167. });
  5168. if (!markers) return null;
  5169. var parts = [{from: from, to: to}];
  5170. for (var i = 0; i < markers.length; ++i) {
  5171. var mk = markers[i], m = mk.find(0);
  5172. for (var j = 0; j < parts.length; ++j) {
  5173. var p = parts[j];
  5174. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5175. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5176. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5177. newParts.push({from: p.from, to: m.from});
  5178. if (dto > 0 || !mk.inclusiveRight && !dto)
  5179. newParts.push({from: m.to, to: p.to});
  5180. parts.splice.apply(parts, newParts);
  5181. j += newParts.length - 1;
  5182. }
  5183. }
  5184. return parts;
  5185. }
  5186. // Connect or disconnect spans from a line.
  5187. function detachMarkedSpans(line) {
  5188. var spans = line.markedSpans;
  5189. if (!spans) return;
  5190. for (var i = 0; i < spans.length; ++i)
  5191. spans[i].marker.detachLine(line);
  5192. line.markedSpans = null;
  5193. }
  5194. function attachMarkedSpans(line, spans) {
  5195. if (!spans) return;
  5196. for (var i = 0; i < spans.length; ++i)
  5197. spans[i].marker.attachLine(line);
  5198. line.markedSpans = spans;
  5199. }
  5200. // Helpers used when computing which overlapping collapsed span
  5201. // counts as the larger one.
  5202. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5203. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5204. // Returns a number indicating which of two overlapping collapsed
  5205. // spans is larger (and thus includes the other). Falls back to
  5206. // comparing ids when the spans cover exactly the same range.
  5207. function compareCollapsedMarkers(a, b) {
  5208. var lenDiff = a.lines.length - b.lines.length;
  5209. if (lenDiff != 0) return lenDiff;
  5210. var aPos = a.find(), bPos = b.find();
  5211. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5212. if (fromCmp) return -fromCmp;
  5213. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5214. if (toCmp) return toCmp;
  5215. return b.id - a.id;
  5216. }
  5217. // Find out whether a line ends or starts in a collapsed span. If
  5218. // so, return the marker for that span.
  5219. function collapsedSpanAtSide(line, start) {
  5220. var sps = sawCollapsedSpans && line.markedSpans, found;
  5221. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5222. sp = sps[i];
  5223. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5224. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5225. found = sp.marker;
  5226. }
  5227. return found;
  5228. }
  5229. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5230. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5231. // Test whether there exists a collapsed span that partially
  5232. // overlaps (covers the start or end, but not both) of a new span.
  5233. // Such overlap is not allowed.
  5234. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5235. var line = getLine(doc, lineNo);
  5236. var sps = sawCollapsedSpans && line.markedSpans;
  5237. if (sps) for (var i = 0; i < sps.length; ++i) {
  5238. var sp = sps[i];
  5239. if (!sp.marker.collapsed) continue;
  5240. var found = sp.marker.find(0);
  5241. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5242. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5243. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5244. if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
  5245. fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
  5246. return true;
  5247. }
  5248. }
  5249. // A visual line is a line as drawn on the screen. Folding, for
  5250. // example, can cause multiple logical lines to appear on the same
  5251. // visual line. This finds the start of the visual line that the
  5252. // given line is part of (usually that is the line itself).
  5253. function visualLine(line) {
  5254. var merged;
  5255. while (merged = collapsedSpanAtStart(line))
  5256. line = merged.find(-1, true).line;
  5257. return line;
  5258. }
  5259. // Returns an array of logical lines that continue the visual line
  5260. // started by the argument, or undefined if there are no such lines.
  5261. function visualLineContinued(line) {
  5262. var merged, lines;
  5263. while (merged = collapsedSpanAtEnd(line)) {
  5264. line = merged.find(1, true).line;
  5265. (lines || (lines = [])).push(line);
  5266. }
  5267. return lines;
  5268. }
  5269. // Get the line number of the start of the visual line that the
  5270. // given line number is part of.
  5271. function visualLineNo(doc, lineN) {
  5272. var line = getLine(doc, lineN), vis = visualLine(line);
  5273. if (line == vis) return lineN;
  5274. return lineNo(vis);
  5275. }
  5276. // Get the line number of the start of the next visual line after
  5277. // the given line.
  5278. function visualLineEndNo(doc, lineN) {
  5279. if (lineN > doc.lastLine()) return lineN;
  5280. var line = getLine(doc, lineN), merged;
  5281. if (!lineIsHidden(doc, line)) return lineN;
  5282. while (merged = collapsedSpanAtEnd(line))
  5283. line = merged.find(1, true).line;
  5284. return lineNo(line) + 1;
  5285. }
  5286. // Compute whether a line is hidden. Lines count as hidden when they
  5287. // are part of a visual line that starts with another line, or when
  5288. // they are entirely covered by collapsed, non-widget span.
  5289. function lineIsHidden(doc, line) {
  5290. var sps = sawCollapsedSpans && line.markedSpans;
  5291. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5292. sp = sps[i];
  5293. if (!sp.marker.collapsed) continue;
  5294. if (sp.from == null) return true;
  5295. if (sp.marker.widgetNode) continue;
  5296. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5297. return true;
  5298. }
  5299. }
  5300. function lineIsHiddenInner(doc, line, span) {
  5301. if (span.to == null) {
  5302. var end = span.marker.find(1, true);
  5303. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5304. }
  5305. if (span.marker.inclusiveRight && span.to == line.text.length)
  5306. return true;
  5307. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5308. sp = line.markedSpans[i];
  5309. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5310. (sp.to == null || sp.to != span.from) &&
  5311. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5312. lineIsHiddenInner(doc, line, sp)) return true;
  5313. }
  5314. }
  5315. // LINE WIDGETS
  5316. // Line widgets are block elements displayed above or below a line.
  5317. var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
  5318. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  5319. this[opt] = options[opt];
  5320. this.cm = cm;
  5321. this.node = node;
  5322. };
  5323. eventMixin(LineWidget);
  5324. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5325. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5326. addToScrollPos(cm, null, diff);
  5327. }
  5328. LineWidget.prototype.clear = function() {
  5329. var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5330. if (no == null || !ws) return;
  5331. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  5332. if (!ws.length) line.widgets = null;
  5333. var height = widgetHeight(this);
  5334. runInOp(cm, function() {
  5335. adjustScrollWhenAboveVisible(cm, line, -height);
  5336. regLineChange(cm, no, "widget");
  5337. updateLineHeight(line, Math.max(0, line.height - height));
  5338. });
  5339. };
  5340. LineWidget.prototype.changed = function() {
  5341. var oldH = this.height, cm = this.cm, line = this.line;
  5342. this.height = null;
  5343. var diff = widgetHeight(this) - oldH;
  5344. if (!diff) return;
  5345. runInOp(cm, function() {
  5346. cm.curOp.forceUpdate = true;
  5347. adjustScrollWhenAboveVisible(cm, line, diff);
  5348. updateLineHeight(line, line.height + diff);
  5349. });
  5350. };
  5351. function widgetHeight(widget) {
  5352. if (widget.height != null) return widget.height;
  5353. if (!contains(document.body, widget.node)) {
  5354. var parentStyle = "position: relative;";
  5355. if (widget.coverGutter)
  5356. parentStyle += "margin-left: -" + widget.cm.display.gutters.offsetWidth + "px;";
  5357. if (widget.noHScroll)
  5358. parentStyle += "width: " + widget.cm.display.wrapper.clientWidth + "px;";
  5359. removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, parentStyle));
  5360. }
  5361. return widget.height = widget.node.offsetHeight;
  5362. }
  5363. function addLineWidget(cm, handle, node, options) {
  5364. var widget = new LineWidget(cm, node, options);
  5365. if (widget.noHScroll) cm.display.alignWidgets = true;
  5366. changeLine(cm.doc, handle, "widget", function(line) {
  5367. var widgets = line.widgets || (line.widgets = []);
  5368. if (widget.insertAt == null) widgets.push(widget);
  5369. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  5370. widget.line = line;
  5371. if (!lineIsHidden(cm.doc, line)) {
  5372. var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
  5373. updateLineHeight(line, line.height + widgetHeight(widget));
  5374. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  5375. cm.curOp.forceUpdate = true;
  5376. }
  5377. return true;
  5378. });
  5379. return widget;
  5380. }
  5381. // LINE DATA STRUCTURE
  5382. // Line objects. These hold state related to a line, including
  5383. // highlighting info (the styles array).
  5384. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  5385. this.text = text;
  5386. attachMarkedSpans(this, markedSpans);
  5387. this.height = estimateHeight ? estimateHeight(this) : 1;
  5388. };
  5389. eventMixin(Line);
  5390. Line.prototype.lineNo = function() { return lineNo(this); };
  5391. // Change the content (text, markers) of a line. Automatically
  5392. // invalidates cached information and tries to re-estimate the
  5393. // line's height.
  5394. function updateLine(line, text, markedSpans, estimateHeight) {
  5395. line.text = text;
  5396. if (line.stateAfter) line.stateAfter = null;
  5397. if (line.styles) line.styles = null;
  5398. if (line.order != null) line.order = null;
  5399. detachMarkedSpans(line);
  5400. attachMarkedSpans(line, markedSpans);
  5401. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  5402. if (estHeight != line.height) updateLineHeight(line, estHeight);
  5403. }
  5404. // Detach a line from the document tree and its markers.
  5405. function cleanUpLine(line) {
  5406. line.parent = null;
  5407. detachMarkedSpans(line);
  5408. }
  5409. function extractLineClasses(type, output) {
  5410. if (type) for (;;) {
  5411. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  5412. if (!lineClass) break;
  5413. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  5414. var prop = lineClass[1] ? "bgClass" : "textClass";
  5415. if (output[prop] == null)
  5416. output[prop] = lineClass[2];
  5417. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  5418. output[prop] += " " + lineClass[2];
  5419. }
  5420. return type;
  5421. }
  5422. function callBlankLine(mode, state) {
  5423. if (mode.blankLine) return mode.blankLine(state);
  5424. if (!mode.innerMode) return;
  5425. var inner = CodeMirror.innerMode(mode, state);
  5426. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  5427. }
  5428. function readToken(mode, stream, state, inner) {
  5429. for (var i = 0; i < 10; i++) {
  5430. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  5431. var style = mode.token(stream, state);
  5432. if (stream.pos > stream.start) return style;
  5433. }
  5434. throw new Error("Mode " + mode.name + " failed to advance stream.");
  5435. }
  5436. // Utility for getTokenAt and getLineTokens
  5437. function takeToken(cm, pos, precise, asArray) {
  5438. function getObj(copy) {
  5439. return {start: stream.start, end: stream.pos,
  5440. string: stream.current(),
  5441. type: style || null,
  5442. state: copy ? copyState(doc.mode, state) : state};
  5443. }
  5444. var doc = cm.doc, mode = doc.mode, style;
  5445. pos = clipPos(doc, pos);
  5446. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  5447. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  5448. if (asArray) tokens = [];
  5449. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  5450. stream.start = stream.pos;
  5451. style = readToken(mode, stream, state);
  5452. if (asArray) tokens.push(getObj(true));
  5453. }
  5454. return asArray ? tokens : getObj();
  5455. }
  5456. // Run the given mode's parser over a line, calling f for each token.
  5457. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  5458. var flattenSpans = mode.flattenSpans;
  5459. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  5460. var curStart = 0, curStyle = null;
  5461. var stream = new StringStream(text, cm.options.tabSize), style;
  5462. var inner = cm.options.addModeClass && [null];
  5463. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  5464. while (!stream.eol()) {
  5465. if (stream.pos > cm.options.maxHighlightLength) {
  5466. flattenSpans = false;
  5467. if (forceToEnd) processLine(cm, text, state, stream.pos);
  5468. stream.pos = text.length;
  5469. style = null;
  5470. } else {
  5471. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  5472. }
  5473. if (inner) {
  5474. var mName = inner[0].name;
  5475. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  5476. }
  5477. if (!flattenSpans || curStyle != style) {
  5478. while (curStart < stream.start) {
  5479. curStart = Math.min(stream.start, curStart + 50000);
  5480. f(curStart, curStyle);
  5481. }
  5482. curStyle = style;
  5483. }
  5484. stream.start = stream.pos;
  5485. }
  5486. while (curStart < stream.pos) {
  5487. // Webkit seems to refuse to render text nodes longer than 57444 characters
  5488. var pos = Math.min(stream.pos, curStart + 50000);
  5489. f(pos, curStyle);
  5490. curStart = pos;
  5491. }
  5492. }
  5493. // Compute a style array (an array starting with a mode generation
  5494. // -- for invalidation -- followed by pairs of end positions and
  5495. // style strings), which is used to highlight the tokens on the
  5496. // line.
  5497. function highlightLine(cm, line, state, forceToEnd) {
  5498. // A styles array always starts with a number identifying the
  5499. // mode/overlays that it is based on (for easy invalidation).
  5500. var st = [cm.state.modeGen], lineClasses = {};
  5501. // Compute the base array of styles
  5502. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  5503. st.push(end, style);
  5504. }, lineClasses, forceToEnd);
  5505. // Run overlays, adjust style array.
  5506. for (var o = 0; o < cm.state.overlays.length; ++o) {
  5507. var overlay = cm.state.overlays[o], i = 1, at = 0;
  5508. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  5509. var start = i;
  5510. // Ensure there's a token end at the current position, and that i points at it
  5511. while (at < end) {
  5512. var i_end = st[i];
  5513. if (i_end > end)
  5514. st.splice(i, 1, end, st[i+1], i_end);
  5515. i += 2;
  5516. at = Math.min(end, i_end);
  5517. }
  5518. if (!style) return;
  5519. if (overlay.opaque) {
  5520. st.splice(start, i - start, end, "cm-overlay " + style);
  5521. i = start + 2;
  5522. } else {
  5523. for (; start < i; start += 2) {
  5524. var cur = st[start+1];
  5525. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  5526. }
  5527. }
  5528. }, lineClasses);
  5529. }
  5530. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  5531. }
  5532. function getLineStyles(cm, line, updateFrontier) {
  5533. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  5534. var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  5535. line.styles = result.styles;
  5536. if (result.classes) line.styleClasses = result.classes;
  5537. else if (line.styleClasses) line.styleClasses = null;
  5538. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  5539. }
  5540. return line.styles;
  5541. }
  5542. // Lightweight form of highlight -- proceed over this line and
  5543. // update state, but don't save a style array. Used for lines that
  5544. // aren't currently visible.
  5545. function processLine(cm, text, state, startAt) {
  5546. var mode = cm.doc.mode;
  5547. var stream = new StringStream(text, cm.options.tabSize);
  5548. stream.start = stream.pos = startAt || 0;
  5549. if (text == "") callBlankLine(mode, state);
  5550. while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
  5551. readToken(mode, stream, state);
  5552. stream.start = stream.pos;
  5553. }
  5554. }
  5555. // Convert a style as returned by a mode (either null, or a string
  5556. // containing one or more styles) to a CSS style. This is cached,
  5557. // and also looks for line-wide styles.
  5558. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  5559. function interpretTokenStyle(style, options) {
  5560. if (!style || /^\s*$/.test(style)) return null;
  5561. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  5562. return cache[style] ||
  5563. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  5564. }
  5565. // Render the DOM representation of the text of a line. Also builds
  5566. // up a 'line map', which points at the DOM nodes that represent
  5567. // specific stretches of text, and is used by the measuring code.
  5568. // The returned object contains the DOM node, this map, and
  5569. // information about line-wide styles that were set by the mode.
  5570. function buildLineContent(cm, lineView) {
  5571. // The padding-right forces the element to have a 'border', which
  5572. // is needed on Webkit to be able to get line-level bounding
  5573. // rectangles for it (in measureChar).
  5574. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  5575. var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
  5576. lineView.measure = {};
  5577. // Iterate over the logical lines that make up this visual line.
  5578. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  5579. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  5580. builder.pos = 0;
  5581. builder.addToken = buildToken;
  5582. // Optionally wire in some hacks into the token-rendering
  5583. // algorithm, to deal with browser quirks.
  5584. if ((ie || webkit) && cm.getOption("lineWrapping"))
  5585. builder.addToken = buildTokenSplitSpaces(builder.addToken);
  5586. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  5587. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  5588. builder.map = [];
  5589. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  5590. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  5591. if (line.styleClasses) {
  5592. if (line.styleClasses.bgClass)
  5593. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  5594. if (line.styleClasses.textClass)
  5595. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  5596. }
  5597. // Ensure at least a single node is present, for measuring.
  5598. if (builder.map.length == 0)
  5599. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  5600. // Store the map and a cache object for the current logical line
  5601. if (i == 0) {
  5602. lineView.measure.map = builder.map;
  5603. lineView.measure.cache = {};
  5604. } else {
  5605. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  5606. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  5607. }
  5608. }
  5609. // See issue #2901
  5610. if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
  5611. builder.content.className = "cm-tab-wrap-hack";
  5612. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  5613. if (builder.pre.className)
  5614. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  5615. return builder;
  5616. }
  5617. function defaultSpecialCharPlaceholder(ch) {
  5618. var token = elt("span", "\u2022", "cm-invalidchar");
  5619. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  5620. token.setAttribute("aria-label", token.title);
  5621. return token;
  5622. }
  5623. // Build up the DOM representation for a single token, and add it to
  5624. // the line map. Takes care to render special characters separately.
  5625. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  5626. if (!text) return;
  5627. var special = builder.cm.options.specialChars, mustWrap = false;
  5628. if (!special.test(text)) {
  5629. builder.col += text.length;
  5630. var content = document.createTextNode(text);
  5631. builder.map.push(builder.pos, builder.pos + text.length, content);
  5632. if (ie && ie_version < 9) mustWrap = true;
  5633. builder.pos += text.length;
  5634. } else {
  5635. var content = document.createDocumentFragment(), pos = 0;
  5636. while (true) {
  5637. special.lastIndex = pos;
  5638. var m = special.exec(text);
  5639. var skipped = m ? m.index - pos : text.length - pos;
  5640. if (skipped) {
  5641. var txt = document.createTextNode(text.slice(pos, pos + skipped));
  5642. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  5643. else content.appendChild(txt);
  5644. builder.map.push(builder.pos, builder.pos + skipped, txt);
  5645. builder.col += skipped;
  5646. builder.pos += skipped;
  5647. }
  5648. if (!m) break;
  5649. pos += skipped + 1;
  5650. if (m[0] == "\t") {
  5651. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  5652. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  5653. txt.setAttribute("role", "presentation");
  5654. builder.col += tabWidth;
  5655. } else {
  5656. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  5657. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  5658. else content.appendChild(txt);
  5659. builder.col += 1;
  5660. }
  5661. builder.map.push(builder.pos, builder.pos + 1, txt);
  5662. builder.pos++;
  5663. }
  5664. }
  5665. if (style || startStyle || endStyle || mustWrap || css) {
  5666. var fullStyle = style || "";
  5667. if (startStyle) fullStyle += startStyle;
  5668. if (endStyle) fullStyle += endStyle;
  5669. var token = elt("span", [content], fullStyle, css);
  5670. if (title) token.title = title;
  5671. return builder.content.appendChild(token);
  5672. }
  5673. builder.content.appendChild(content);
  5674. }
  5675. function buildTokenSplitSpaces(inner) {
  5676. function split(old) {
  5677. var out = " ";
  5678. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  5679. out += " ";
  5680. return out;
  5681. }
  5682. return function(builder, text, style, startStyle, endStyle, title) {
  5683. inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
  5684. };
  5685. }
  5686. // Work around nonsense dimensions being reported for stretches of
  5687. // right-to-left text.
  5688. function buildTokenBadBidi(inner, order) {
  5689. return function(builder, text, style, startStyle, endStyle, title) {
  5690. style = style ? style + " cm-force-border" : "cm-force-border";
  5691. var start = builder.pos, end = start + text.length;
  5692. for (;;) {
  5693. // Find the part that overlaps with the start of this text
  5694. for (var i = 0; i < order.length; i++) {
  5695. var part = order[i];
  5696. if (part.to > start && part.from <= start) break;
  5697. }
  5698. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
  5699. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
  5700. startStyle = null;
  5701. text = text.slice(part.to - start);
  5702. start = part.to;
  5703. }
  5704. };
  5705. }
  5706. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  5707. var widget = !ignoreWidget && marker.widgetNode;
  5708. if (widget) {
  5709. builder.map.push(builder.pos, builder.pos + size, widget);
  5710. builder.content.appendChild(widget);
  5711. }
  5712. builder.pos += size;
  5713. }
  5714. // Outputs a number of spans to make up a line, taking highlighting
  5715. // and marked text into account.
  5716. function insertLineContent(line, builder, styles) {
  5717. var spans = line.markedSpans, allText = line.text, at = 0;
  5718. if (!spans) {
  5719. for (var i = 1; i < styles.length; i+=2)
  5720. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  5721. return;
  5722. }
  5723. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  5724. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  5725. for (;;) {
  5726. if (nextChange == pos) { // Update current marker set
  5727. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  5728. collapsed = null; nextChange = Infinity;
  5729. var foundBookmarks = [];
  5730. for (var j = 0; j < spans.length; ++j) {
  5731. var sp = spans[j], m = sp.marker;
  5732. if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
  5733. if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
  5734. if (m.className) spanStyle += " " + m.className;
  5735. if (m.css) css = m.css;
  5736. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  5737. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  5738. if (m.title && !title) title = m.title;
  5739. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  5740. collapsed = sp;
  5741. } else if (sp.from > pos && nextChange > sp.from) {
  5742. nextChange = sp.from;
  5743. }
  5744. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
  5745. }
  5746. if (collapsed && (collapsed.from || 0) == pos) {
  5747. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  5748. collapsed.marker, collapsed.from == null);
  5749. if (collapsed.to == null) return;
  5750. }
  5751. if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
  5752. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  5753. }
  5754. if (pos >= len) break;
  5755. var upto = Math.min(len, nextChange);
  5756. while (true) {
  5757. if (text) {
  5758. var end = pos + text.length;
  5759. if (!collapsed) {
  5760. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  5761. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  5762. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  5763. }
  5764. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  5765. pos = end;
  5766. spanStartStyle = "";
  5767. }
  5768. text = allText.slice(at, at = styles[i++]);
  5769. style = interpretTokenStyle(styles[i++], builder.cm.options);
  5770. }
  5771. }
  5772. }
  5773. // DOCUMENT DATA STRUCTURE
  5774. // By default, updates that start and end at the beginning of a line
  5775. // are treated specially, in order to make the association of line
  5776. // widgets and marker elements with the text behave more intuitive.
  5777. function isWholeLineUpdate(doc, change) {
  5778. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  5779. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  5780. }
  5781. // Perform a change on the document data structure.
  5782. function updateDoc(doc, change, markedSpans, estimateHeight) {
  5783. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  5784. function update(line, text, spans) {
  5785. updateLine(line, text, spans, estimateHeight);
  5786. signalLater(line, "change", line, change);
  5787. }
  5788. function linesFor(start, end) {
  5789. for (var i = start, result = []; i < end; ++i)
  5790. result.push(new Line(text[i], spansFor(i), estimateHeight));
  5791. return result;
  5792. }
  5793. var from = change.from, to = change.to, text = change.text;
  5794. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  5795. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  5796. // Adjust the line structure
  5797. if (change.full) {
  5798. doc.insert(0, linesFor(0, text.length));
  5799. doc.remove(text.length, doc.size - text.length);
  5800. } else if (isWholeLineUpdate(doc, change)) {
  5801. // This is a whole-line replace. Treated specially to make
  5802. // sure line objects move the way they are supposed to.
  5803. var added = linesFor(0, text.length - 1);
  5804. update(lastLine, lastLine.text, lastSpans);
  5805. if (nlines) doc.remove(from.line, nlines);
  5806. if (added.length) doc.insert(from.line, added);
  5807. } else if (firstLine == lastLine) {
  5808. if (text.length == 1) {
  5809. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  5810. } else {
  5811. var added = linesFor(1, text.length - 1);
  5812. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  5813. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  5814. doc.insert(from.line + 1, added);
  5815. }
  5816. } else if (text.length == 1) {
  5817. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  5818. doc.remove(from.line + 1, nlines);
  5819. } else {
  5820. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  5821. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  5822. var added = linesFor(1, text.length - 1);
  5823. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  5824. doc.insert(from.line + 1, added);
  5825. }
  5826. signalLater(doc, "change", doc, change);
  5827. }
  5828. // The document is represented as a BTree consisting of leaves, with
  5829. // chunk of lines in them, and branches, with up to ten leaves or
  5830. // other branch nodes below them. The top node is always a branch
  5831. // node, and is the document object itself (meaning it has
  5832. // additional methods and properties).
  5833. //
  5834. // All nodes have parent links. The tree is used both to go from
  5835. // line numbers to line objects, and to go from objects to numbers.
  5836. // It also indexes by height, and is used to convert between height
  5837. // and line object, and to find the total height of the document.
  5838. //
  5839. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5840. function LeafChunk(lines) {
  5841. this.lines = lines;
  5842. this.parent = null;
  5843. for (var i = 0, height = 0; i < lines.length; ++i) {
  5844. lines[i].parent = this;
  5845. height += lines[i].height;
  5846. }
  5847. this.height = height;
  5848. }
  5849. LeafChunk.prototype = {
  5850. chunkSize: function() { return this.lines.length; },
  5851. // Remove the n lines at offset 'at'.
  5852. removeInner: function(at, n) {
  5853. for (var i = at, e = at + n; i < e; ++i) {
  5854. var line = this.lines[i];
  5855. this.height -= line.height;
  5856. cleanUpLine(line);
  5857. signalLater(line, "delete");
  5858. }
  5859. this.lines.splice(at, n);
  5860. },
  5861. // Helper used to collapse a small branch into a single leaf.
  5862. collapse: function(lines) {
  5863. lines.push.apply(lines, this.lines);
  5864. },
  5865. // Insert the given array of lines at offset 'at', count them as
  5866. // having the given height.
  5867. insertInner: function(at, lines, height) {
  5868. this.height += height;
  5869. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5870. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  5871. },
  5872. // Used to iterate over a part of the tree.
  5873. iterN: function(at, n, op) {
  5874. for (var e = at + n; at < e; ++at)
  5875. if (op(this.lines[at])) return true;
  5876. }
  5877. };
  5878. function BranchChunk(children) {
  5879. this.children = children;
  5880. var size = 0, height = 0;
  5881. for (var i = 0; i < children.length; ++i) {
  5882. var ch = children[i];
  5883. size += ch.chunkSize(); height += ch.height;
  5884. ch.parent = this;
  5885. }
  5886. this.size = size;
  5887. this.height = height;
  5888. this.parent = null;
  5889. }
  5890. BranchChunk.prototype = {
  5891. chunkSize: function() { return this.size; },
  5892. removeInner: function(at, n) {
  5893. this.size -= n;
  5894. for (var i = 0; i < this.children.length; ++i) {
  5895. var child = this.children[i], sz = child.chunkSize();
  5896. if (at < sz) {
  5897. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5898. child.removeInner(at, rm);
  5899. this.height -= oldHeight - child.height;
  5900. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5901. if ((n -= rm) == 0) break;
  5902. at = 0;
  5903. } else at -= sz;
  5904. }
  5905. // If the result is smaller than 25 lines, ensure that it is a
  5906. // single leaf node.
  5907. if (this.size - n < 25 &&
  5908. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5909. var lines = [];
  5910. this.collapse(lines);
  5911. this.children = [new LeafChunk(lines)];
  5912. this.children[0].parent = this;
  5913. }
  5914. },
  5915. collapse: function(lines) {
  5916. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  5917. },
  5918. insertInner: function(at, lines, height) {
  5919. this.size += lines.length;
  5920. this.height += height;
  5921. for (var i = 0; i < this.children.length; ++i) {
  5922. var child = this.children[i], sz = child.chunkSize();
  5923. if (at <= sz) {
  5924. child.insertInner(at, lines, height);
  5925. if (child.lines && child.lines.length > 50) {
  5926. while (child.lines.length > 50) {
  5927. var spilled = child.lines.splice(child.lines.length - 25, 25);
  5928. var newleaf = new LeafChunk(spilled);
  5929. child.height -= newleaf.height;
  5930. this.children.splice(i + 1, 0, newleaf);
  5931. newleaf.parent = this;
  5932. }
  5933. this.maybeSpill();
  5934. }
  5935. break;
  5936. }
  5937. at -= sz;
  5938. }
  5939. },
  5940. // When a node has grown, check whether it should be split.
  5941. maybeSpill: function() {
  5942. if (this.children.length <= 10) return;
  5943. var me = this;
  5944. do {
  5945. var spilled = me.children.splice(me.children.length - 5, 5);
  5946. var sibling = new BranchChunk(spilled);
  5947. if (!me.parent) { // Become the parent node
  5948. var copy = new BranchChunk(me.children);
  5949. copy.parent = me;
  5950. me.children = [copy, sibling];
  5951. me = copy;
  5952. } else {
  5953. me.size -= sibling.size;
  5954. me.height -= sibling.height;
  5955. var myIndex = indexOf(me.parent.children, me);
  5956. me.parent.children.splice(myIndex + 1, 0, sibling);
  5957. }
  5958. sibling.parent = me.parent;
  5959. } while (me.children.length > 10);
  5960. me.parent.maybeSpill();
  5961. },
  5962. iterN: function(at, n, op) {
  5963. for (var i = 0; i < this.children.length; ++i) {
  5964. var child = this.children[i], sz = child.chunkSize();
  5965. if (at < sz) {
  5966. var used = Math.min(n, sz - at);
  5967. if (child.iterN(at, used, op)) return true;
  5968. if ((n -= used) == 0) break;
  5969. at = 0;
  5970. } else at -= sz;
  5971. }
  5972. }
  5973. };
  5974. var nextDocId = 0;
  5975. var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
  5976. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  5977. if (firstLine == null) firstLine = 0;
  5978. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5979. this.first = firstLine;
  5980. this.scrollTop = this.scrollLeft = 0;
  5981. this.cantEdit = false;
  5982. this.cleanGeneration = 1;
  5983. this.frontier = firstLine;
  5984. var start = Pos(firstLine, 0);
  5985. this.sel = simpleSelection(start);
  5986. this.history = new History(null);
  5987. this.id = ++nextDocId;
  5988. this.modeOption = mode;
  5989. if (typeof text == "string") text = splitLines(text);
  5990. updateDoc(this, {from: start, to: start, text: text});
  5991. setSelection(this, simpleSelection(start), sel_dontScroll);
  5992. };
  5993. Doc.prototype = createObj(BranchChunk.prototype, {
  5994. constructor: Doc,
  5995. // Iterate over the document. Supports two forms -- with only one
  5996. // argument, it calls that for each line in the document. With
  5997. // three, it iterates over the range given by the first two (with
  5998. // the second being non-inclusive).
  5999. iter: function(from, to, op) {
  6000. if (op) this.iterN(from - this.first, to - from, op);
  6001. else this.iterN(this.first, this.first + this.size, from);
  6002. },
  6003. // Non-public interface for adding and removing lines.
  6004. insert: function(at, lines) {
  6005. var height = 0;
  6006. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6007. this.insertInner(at - this.first, lines, height);
  6008. },
  6009. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6010. // From here, the methods are part of the public interface. Most
  6011. // are also available from CodeMirror (editor) instances.
  6012. getValue: function(lineSep) {
  6013. var lines = getLines(this, this.first, this.first + this.size);
  6014. if (lineSep === false) return lines;
  6015. return lines.join(lineSep || "\n");
  6016. },
  6017. setValue: docMethodOp(function(code) {
  6018. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6019. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6020. text: splitLines(code), origin: "setValue", full: true}, true);
  6021. setSelection(this, simpleSelection(top));
  6022. }),
  6023. replaceRange: function(code, from, to, origin) {
  6024. from = clipPos(this, from);
  6025. to = to ? clipPos(this, to) : from;
  6026. replaceRange(this, code, from, to, origin);
  6027. },
  6028. getRange: function(from, to, lineSep) {
  6029. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6030. if (lineSep === false) return lines;
  6031. return lines.join(lineSep || "\n");
  6032. },
  6033. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6034. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6035. getLineNumber: function(line) {return lineNo(line);},
  6036. getLineHandleVisualStart: function(line) {
  6037. if (typeof line == "number") line = getLine(this, line);
  6038. return visualLine(line);
  6039. },
  6040. lineCount: function() {return this.size;},
  6041. firstLine: function() {return this.first;},
  6042. lastLine: function() {return this.first + this.size - 1;},
  6043. clipPos: function(pos) {return clipPos(this, pos);},
  6044. getCursor: function(start) {
  6045. var range = this.sel.primary(), pos;
  6046. if (start == null || start == "head") pos = range.head;
  6047. else if (start == "anchor") pos = range.anchor;
  6048. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6049. else pos = range.from();
  6050. return pos;
  6051. },
  6052. listSelections: function() { return this.sel.ranges; },
  6053. somethingSelected: function() {return this.sel.somethingSelected();},
  6054. setCursor: docMethodOp(function(line, ch, options) {
  6055. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6056. }),
  6057. setSelection: docMethodOp(function(anchor, head, options) {
  6058. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6059. }),
  6060. extendSelection: docMethodOp(function(head, other, options) {
  6061. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6062. }),
  6063. extendSelections: docMethodOp(function(heads, options) {
  6064. extendSelections(this, clipPosArray(this, heads, options));
  6065. }),
  6066. extendSelectionsBy: docMethodOp(function(f, options) {
  6067. extendSelections(this, map(this.sel.ranges, f), options);
  6068. }),
  6069. setSelections: docMethodOp(function(ranges, primary, options) {
  6070. if (!ranges.length) return;
  6071. for (var i = 0, out = []; i < ranges.length; i++)
  6072. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6073. clipPos(this, ranges[i].head));
  6074. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6075. setSelection(this, normalizeSelection(out, primary), options);
  6076. }),
  6077. addSelection: docMethodOp(function(anchor, head, options) {
  6078. var ranges = this.sel.ranges.slice(0);
  6079. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6080. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6081. }),
  6082. getSelection: function(lineSep) {
  6083. var ranges = this.sel.ranges, lines;
  6084. for (var i = 0; i < ranges.length; i++) {
  6085. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6086. lines = lines ? lines.concat(sel) : sel;
  6087. }
  6088. if (lineSep === false) return lines;
  6089. else return lines.join(lineSep || "\n");
  6090. },
  6091. getSelections: function(lineSep) {
  6092. var parts = [], ranges = this.sel.ranges;
  6093. for (var i = 0; i < ranges.length; i++) {
  6094. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6095. if (lineSep !== false) sel = sel.join(lineSep || "\n");
  6096. parts[i] = sel;
  6097. }
  6098. return parts;
  6099. },
  6100. replaceSelection: function(code, collapse, origin) {
  6101. var dup = [];
  6102. for (var i = 0; i < this.sel.ranges.length; i++)
  6103. dup[i] = code;
  6104. this.replaceSelections(dup, collapse, origin || "+input");
  6105. },
  6106. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6107. var changes = [], sel = this.sel;
  6108. for (var i = 0; i < sel.ranges.length; i++) {
  6109. var range = sel.ranges[i];
  6110. changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
  6111. }
  6112. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6113. for (var i = changes.length - 1; i >= 0; i--)
  6114. makeChange(this, changes[i]);
  6115. if (newSel) setSelectionReplaceHistory(this, newSel);
  6116. else if (this.cm) ensureCursorVisible(this.cm);
  6117. }),
  6118. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6119. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6120. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6121. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6122. setExtending: function(val) {this.extend = val;},
  6123. getExtending: function() {return this.extend;},
  6124. historySize: function() {
  6125. var hist = this.history, done = 0, undone = 0;
  6126. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6127. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6128. return {undo: done, redo: undone};
  6129. },
  6130. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6131. markClean: function() {
  6132. this.cleanGeneration = this.changeGeneration(true);
  6133. },
  6134. changeGeneration: function(forceSplit) {
  6135. if (forceSplit)
  6136. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6137. return this.history.generation;
  6138. },
  6139. isClean: function (gen) {
  6140. return this.history.generation == (gen || this.cleanGeneration);
  6141. },
  6142. getHistory: function() {
  6143. return {done: copyHistoryArray(this.history.done),
  6144. undone: copyHistoryArray(this.history.undone)};
  6145. },
  6146. setHistory: function(histData) {
  6147. var hist = this.history = new History(this.history.maxGeneration);
  6148. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6149. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6150. },
  6151. addLineClass: docMethodOp(function(handle, where, cls) {
  6152. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6153. var prop = where == "text" ? "textClass"
  6154. : where == "background" ? "bgClass"
  6155. : where == "gutter" ? "gutterClass" : "wrapClass";
  6156. if (!line[prop]) line[prop] = cls;
  6157. else if (classTest(cls).test(line[prop])) return false;
  6158. else line[prop] += " " + cls;
  6159. return true;
  6160. });
  6161. }),
  6162. removeLineClass: docMethodOp(function(handle, where, cls) {
  6163. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6164. var prop = where == "text" ? "textClass"
  6165. : where == "background" ? "bgClass"
  6166. : where == "gutter" ? "gutterClass" : "wrapClass";
  6167. var cur = line[prop];
  6168. if (!cur) return false;
  6169. else if (cls == null) line[prop] = null;
  6170. else {
  6171. var found = cur.match(classTest(cls));
  6172. if (!found) return false;
  6173. var end = found.index + found[0].length;
  6174. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6175. }
  6176. return true;
  6177. });
  6178. }),
  6179. markText: function(from, to, options) {
  6180. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  6181. },
  6182. setBookmark: function(pos, options) {
  6183. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6184. insertLeft: options && options.insertLeft,
  6185. clearWhenEmpty: false, shared: options && options.shared};
  6186. pos = clipPos(this, pos);
  6187. return markText(this, pos, pos, realOpts, "bookmark");
  6188. },
  6189. findMarksAt: function(pos) {
  6190. pos = clipPos(this, pos);
  6191. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6192. if (spans) for (var i = 0; i < spans.length; ++i) {
  6193. var span = spans[i];
  6194. if ((span.from == null || span.from <= pos.ch) &&
  6195. (span.to == null || span.to >= pos.ch))
  6196. markers.push(span.marker.parent || span.marker);
  6197. }
  6198. return markers;
  6199. },
  6200. findMarks: function(from, to, filter) {
  6201. from = clipPos(this, from); to = clipPos(this, to);
  6202. var found = [], lineNo = from.line;
  6203. this.iter(from.line, to.line + 1, function(line) {
  6204. var spans = line.markedSpans;
  6205. if (spans) for (var i = 0; i < spans.length; i++) {
  6206. var span = spans[i];
  6207. if (!(lineNo == from.line && from.ch > span.to ||
  6208. span.from == null && lineNo != from.line||
  6209. lineNo == to.line && span.from > to.ch) &&
  6210. (!filter || filter(span.marker)))
  6211. found.push(span.marker.parent || span.marker);
  6212. }
  6213. ++lineNo;
  6214. });
  6215. return found;
  6216. },
  6217. getAllMarks: function() {
  6218. var markers = [];
  6219. this.iter(function(line) {
  6220. var sps = line.markedSpans;
  6221. if (sps) for (var i = 0; i < sps.length; ++i)
  6222. if (sps[i].from != null) markers.push(sps[i].marker);
  6223. });
  6224. return markers;
  6225. },
  6226. posFromIndex: function(off) {
  6227. var ch, lineNo = this.first;
  6228. this.iter(function(line) {
  6229. var sz = line.text.length + 1;
  6230. if (sz > off) { ch = off; return true; }
  6231. off -= sz;
  6232. ++lineNo;
  6233. });
  6234. return clipPos(this, Pos(lineNo, ch));
  6235. },
  6236. indexFromPos: function (coords) {
  6237. coords = clipPos(this, coords);
  6238. var index = coords.ch;
  6239. if (coords.line < this.first || coords.ch < 0) return 0;
  6240. this.iter(this.first, coords.line, function (line) {
  6241. index += line.text.length + 1;
  6242. });
  6243. return index;
  6244. },
  6245. copy: function(copyHistory) {
  6246. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  6247. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6248. doc.sel = this.sel;
  6249. doc.extend = false;
  6250. if (copyHistory) {
  6251. doc.history.undoDepth = this.history.undoDepth;
  6252. doc.setHistory(this.getHistory());
  6253. }
  6254. return doc;
  6255. },
  6256. linkedDoc: function(options) {
  6257. if (!options) options = {};
  6258. var from = this.first, to = this.first + this.size;
  6259. if (options.from != null && options.from > from) from = options.from;
  6260. if (options.to != null && options.to < to) to = options.to;
  6261. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  6262. if (options.sharedHist) copy.history = this.history;
  6263. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6264. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6265. copySharedMarkers(copy, findSharedMarkers(this));
  6266. return copy;
  6267. },
  6268. unlinkDoc: function(other) {
  6269. if (other instanceof CodeMirror) other = other.doc;
  6270. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6271. var link = this.linked[i];
  6272. if (link.doc != other) continue;
  6273. this.linked.splice(i, 1);
  6274. other.unlinkDoc(this);
  6275. detachSharedMarkers(findSharedMarkers(this));
  6276. break;
  6277. }
  6278. // If the histories were shared, split them again
  6279. if (other.history == this.history) {
  6280. var splitIds = [other.id];
  6281. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  6282. other.history = new History(null);
  6283. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6284. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6285. }
  6286. },
  6287. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  6288. getMode: function() {return this.mode;},
  6289. getEditor: function() {return this.cm;}
  6290. });
  6291. // Public alias.
  6292. Doc.prototype.eachLine = Doc.prototype.iter;
  6293. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  6294. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  6295. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  6296. CodeMirror.prototype[prop] = (function(method) {
  6297. return function() {return method.apply(this.doc, arguments);};
  6298. })(Doc.prototype[prop]);
  6299. eventMixin(Doc);
  6300. // Call f for all linked documents.
  6301. function linkedDocs(doc, f, sharedHistOnly) {
  6302. function propagate(doc, skip, sharedHist) {
  6303. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  6304. var rel = doc.linked[i];
  6305. if (rel.doc == skip) continue;
  6306. var shared = sharedHist && rel.sharedHist;
  6307. if (sharedHistOnly && !shared) continue;
  6308. f(rel.doc, shared);
  6309. propagate(rel.doc, doc, shared);
  6310. }
  6311. }
  6312. propagate(doc, null, true);
  6313. }
  6314. // Attach a document to an editor.
  6315. function attachDoc(cm, doc) {
  6316. if (doc.cm) throw new Error("This document is already in use.");
  6317. cm.doc = doc;
  6318. doc.cm = cm;
  6319. estimateLineHeights(cm);
  6320. loadMode(cm);
  6321. if (!cm.options.lineWrapping) findMaxLine(cm);
  6322. cm.options.mode = doc.modeOption;
  6323. regChange(cm);
  6324. }
  6325. // LINE UTILITIES
  6326. // Find the line object corresponding to the given line number.
  6327. function getLine(doc, n) {
  6328. n -= doc.first;
  6329. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  6330. for (var chunk = doc; !chunk.lines;) {
  6331. for (var i = 0;; ++i) {
  6332. var child = chunk.children[i], sz = child.chunkSize();
  6333. if (n < sz) { chunk = child; break; }
  6334. n -= sz;
  6335. }
  6336. }
  6337. return chunk.lines[n];
  6338. }
  6339. // Get the part of a document between two positions, as an array of
  6340. // strings.
  6341. function getBetween(doc, start, end) {
  6342. var out = [], n = start.line;
  6343. doc.iter(start.line, end.line + 1, function(line) {
  6344. var text = line.text;
  6345. if (n == end.line) text = text.slice(0, end.ch);
  6346. if (n == start.line) text = text.slice(start.ch);
  6347. out.push(text);
  6348. ++n;
  6349. });
  6350. return out;
  6351. }
  6352. // Get the lines between from and to, as array of strings.
  6353. function getLines(doc, from, to) {
  6354. var out = [];
  6355. doc.iter(from, to, function(line) { out.push(line.text); });
  6356. return out;
  6357. }
  6358. // Update the height of a line, propagating the height change
  6359. // upwards to parent nodes.
  6360. function updateLineHeight(line, height) {
  6361. var diff = height - line.height;
  6362. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  6363. }
  6364. // Given a line object, find its line number by walking up through
  6365. // its parent links.
  6366. function lineNo(line) {
  6367. if (line.parent == null) return null;
  6368. var cur = line.parent, no = indexOf(cur.lines, line);
  6369. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  6370. for (var i = 0;; ++i) {
  6371. if (chunk.children[i] == cur) break;
  6372. no += chunk.children[i].chunkSize();
  6373. }
  6374. }
  6375. return no + cur.first;
  6376. }
  6377. // Find the line at the given vertical position, using the height
  6378. // information in the document tree.
  6379. function lineAtHeight(chunk, h) {
  6380. var n = chunk.first;
  6381. outer: do {
  6382. for (var i = 0; i < chunk.children.length; ++i) {
  6383. var child = chunk.children[i], ch = child.height;
  6384. if (h < ch) { chunk = child; continue outer; }
  6385. h -= ch;
  6386. n += child.chunkSize();
  6387. }
  6388. return n;
  6389. } while (!chunk.lines);
  6390. for (var i = 0; i < chunk.lines.length; ++i) {
  6391. var line = chunk.lines[i], lh = line.height;
  6392. if (h < lh) break;
  6393. h -= lh;
  6394. }
  6395. return n + i;
  6396. }
  6397. // Find the height above the given line.
  6398. function heightAtLine(lineObj) {
  6399. lineObj = visualLine(lineObj);
  6400. var h = 0, chunk = lineObj.parent;
  6401. for (var i = 0; i < chunk.lines.length; ++i) {
  6402. var line = chunk.lines[i];
  6403. if (line == lineObj) break;
  6404. else h += line.height;
  6405. }
  6406. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  6407. for (var i = 0; i < p.children.length; ++i) {
  6408. var cur = p.children[i];
  6409. if (cur == chunk) break;
  6410. else h += cur.height;
  6411. }
  6412. }
  6413. return h;
  6414. }
  6415. // Get the bidi ordering for the given line (and cache it). Returns
  6416. // false for lines that are fully left-to-right, and an array of
  6417. // BidiSpan objects otherwise.
  6418. function getOrder(line) {
  6419. var order = line.order;
  6420. if (order == null) order = line.order = bidiOrdering(line.text);
  6421. return order;
  6422. }
  6423. // HISTORY
  6424. function History(startGen) {
  6425. // Arrays of change events and selections. Doing something adds an
  6426. // event to done and clears undo. Undoing moves events from done
  6427. // to undone, redoing moves them in the other direction.
  6428. this.done = []; this.undone = [];
  6429. this.undoDepth = Infinity;
  6430. // Used to track when changes can be merged into a single undo
  6431. // event
  6432. this.lastModTime = this.lastSelTime = 0;
  6433. this.lastOp = this.lastSelOp = null;
  6434. this.lastOrigin = this.lastSelOrigin = null;
  6435. // Used by the isClean() method
  6436. this.generation = this.maxGeneration = startGen || 1;
  6437. }
  6438. // Create a history change event from an updateDoc-style change
  6439. // object.
  6440. function historyChangeFromChange(doc, change) {
  6441. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  6442. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  6443. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  6444. return histChange;
  6445. }
  6446. // Pop all selection events off the end of a history array. Stop at
  6447. // a change event.
  6448. function clearSelectionEvents(array) {
  6449. while (array.length) {
  6450. var last = lst(array);
  6451. if (last.ranges) array.pop();
  6452. else break;
  6453. }
  6454. }
  6455. // Find the top change event in the history. Pop off selection
  6456. // events that are in the way.
  6457. function lastChangeEvent(hist, force) {
  6458. if (force) {
  6459. clearSelectionEvents(hist.done);
  6460. return lst(hist.done);
  6461. } else if (hist.done.length && !lst(hist.done).ranges) {
  6462. return lst(hist.done);
  6463. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  6464. hist.done.pop();
  6465. return lst(hist.done);
  6466. }
  6467. }
  6468. // Register a change in the history. Merges changes that are within
  6469. // a single operation, ore are close together with an origin that
  6470. // allows merging (starting with "+") into a single event.
  6471. function addChangeToHistory(doc, change, selAfter, opId) {
  6472. var hist = doc.history;
  6473. hist.undone.length = 0;
  6474. var time = +new Date, cur;
  6475. if ((hist.lastOp == opId ||
  6476. hist.lastOrigin == change.origin && change.origin &&
  6477. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  6478. change.origin.charAt(0) == "*")) &&
  6479. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  6480. // Merge this change into the last event
  6481. var last = lst(cur.changes);
  6482. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  6483. // Optimized case for simple insertion -- don't want to add
  6484. // new changesets for every character typed
  6485. last.to = changeEnd(change);
  6486. } else {
  6487. // Add new sub-event
  6488. cur.changes.push(historyChangeFromChange(doc, change));
  6489. }
  6490. } else {
  6491. // Can not be merged, start a new event.
  6492. var before = lst(hist.done);
  6493. if (!before || !before.ranges)
  6494. pushSelectionToHistory(doc.sel, hist.done);
  6495. cur = {changes: [historyChangeFromChange(doc, change)],
  6496. generation: hist.generation};
  6497. hist.done.push(cur);
  6498. while (hist.done.length > hist.undoDepth) {
  6499. hist.done.shift();
  6500. if (!hist.done[0].ranges) hist.done.shift();
  6501. }
  6502. }
  6503. hist.done.push(selAfter);
  6504. hist.generation = ++hist.maxGeneration;
  6505. hist.lastModTime = hist.lastSelTime = time;
  6506. hist.lastOp = hist.lastSelOp = opId;
  6507. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  6508. if (!last) signal(doc, "historyAdded");
  6509. }
  6510. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  6511. var ch = origin.charAt(0);
  6512. return ch == "*" ||
  6513. ch == "+" &&
  6514. prev.ranges.length == sel.ranges.length &&
  6515. prev.somethingSelected() == sel.somethingSelected() &&
  6516. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  6517. }
  6518. // Called whenever the selection changes, sets the new selection as
  6519. // the pending selection in the history, and pushes the old pending
  6520. // selection into the 'done' array when it was significantly
  6521. // different (in number of selected ranges, emptiness, or time).
  6522. function addSelectionToHistory(doc, sel, opId, options) {
  6523. var hist = doc.history, origin = options && options.origin;
  6524. // A new event is started when the previous origin does not match
  6525. // the current, or the origins don't allow matching. Origins
  6526. // starting with * are always merged, those starting with + are
  6527. // merged when similar and close together in time.
  6528. if (opId == hist.lastSelOp ||
  6529. (origin && hist.lastSelOrigin == origin &&
  6530. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  6531. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  6532. hist.done[hist.done.length - 1] = sel;
  6533. else
  6534. pushSelectionToHistory(sel, hist.done);
  6535. hist.lastSelTime = +new Date;
  6536. hist.lastSelOrigin = origin;
  6537. hist.lastSelOp = opId;
  6538. if (options && options.clearRedo !== false)
  6539. clearSelectionEvents(hist.undone);
  6540. }
  6541. function pushSelectionToHistory(sel, dest) {
  6542. var top = lst(dest);
  6543. if (!(top && top.ranges && top.equals(sel)))
  6544. dest.push(sel);
  6545. }
  6546. // Used to store marked span information in the history.
  6547. function attachLocalSpans(doc, change, from, to) {
  6548. var existing = change["spans_" + doc.id], n = 0;
  6549. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  6550. if (line.markedSpans)
  6551. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  6552. ++n;
  6553. });
  6554. }
  6555. // When un/re-doing restores text containing marked spans, those
  6556. // that have been explicitly cleared should not be restored.
  6557. function removeClearedSpans(spans) {
  6558. if (!spans) return null;
  6559. for (var i = 0, out; i < spans.length; ++i) {
  6560. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  6561. else if (out) out.push(spans[i]);
  6562. }
  6563. return !out ? spans : out.length ? out : null;
  6564. }
  6565. // Retrieve and filter the old marked spans stored in a change event.
  6566. function getOldSpans(doc, change) {
  6567. var found = change["spans_" + doc.id];
  6568. if (!found) return null;
  6569. for (var i = 0, nw = []; i < change.text.length; ++i)
  6570. nw.push(removeClearedSpans(found[i]));
  6571. return nw;
  6572. }
  6573. // Used both to provide a JSON-safe object in .getHistory, and, when
  6574. // detaching a document, to split the history in two
  6575. function copyHistoryArray(events, newGroup, instantiateSel) {
  6576. for (var i = 0, copy = []; i < events.length; ++i) {
  6577. var event = events[i];
  6578. if (event.ranges) {
  6579. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  6580. continue;
  6581. }
  6582. var changes = event.changes, newChanges = [];
  6583. copy.push({changes: newChanges});
  6584. for (var j = 0; j < changes.length; ++j) {
  6585. var change = changes[j], m;
  6586. newChanges.push({from: change.from, to: change.to, text: change.text});
  6587. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  6588. if (indexOf(newGroup, Number(m[1])) > -1) {
  6589. lst(newChanges)[prop] = change[prop];
  6590. delete change[prop];
  6591. }
  6592. }
  6593. }
  6594. }
  6595. return copy;
  6596. }
  6597. // Rebasing/resetting history to deal with externally-sourced changes
  6598. function rebaseHistSelSingle(pos, from, to, diff) {
  6599. if (to < pos.line) {
  6600. pos.line += diff;
  6601. } else if (from < pos.line) {
  6602. pos.line = from;
  6603. pos.ch = 0;
  6604. }
  6605. }
  6606. // Tries to rebase an array of history events given a change in the
  6607. // document. If the change touches the same lines as the event, the
  6608. // event, and everything 'behind' it, is discarded. If the change is
  6609. // before the event, the event's positions are updated. Uses a
  6610. // copy-on-write scheme for the positions, to avoid having to
  6611. // reallocate them all on every rebase, but also avoid problems with
  6612. // shared position objects being unsafely updated.
  6613. function rebaseHistArray(array, from, to, diff) {
  6614. for (var i = 0; i < array.length; ++i) {
  6615. var sub = array[i], ok = true;
  6616. if (sub.ranges) {
  6617. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  6618. for (var j = 0; j < sub.ranges.length; j++) {
  6619. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  6620. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  6621. }
  6622. continue;
  6623. }
  6624. for (var j = 0; j < sub.changes.length; ++j) {
  6625. var cur = sub.changes[j];
  6626. if (to < cur.from.line) {
  6627. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  6628. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  6629. } else if (from <= cur.to.line) {
  6630. ok = false;
  6631. break;
  6632. }
  6633. }
  6634. if (!ok) {
  6635. array.splice(0, i + 1);
  6636. i = 0;
  6637. }
  6638. }
  6639. }
  6640. function rebaseHist(hist, change) {
  6641. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  6642. rebaseHistArray(hist.done, from, to, diff);
  6643. rebaseHistArray(hist.undone, from, to, diff);
  6644. }
  6645. // EVENT UTILITIES
  6646. // Due to the fact that we still support jurassic IE versions, some
  6647. // compatibility wrappers are needed.
  6648. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  6649. if (e.preventDefault) e.preventDefault();
  6650. else e.returnValue = false;
  6651. };
  6652. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  6653. if (e.stopPropagation) e.stopPropagation();
  6654. else e.cancelBubble = true;
  6655. };
  6656. function e_defaultPrevented(e) {
  6657. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  6658. }
  6659. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  6660. function e_target(e) {return e.target || e.srcElement;}
  6661. function e_button(e) {
  6662. var b = e.which;
  6663. if (b == null) {
  6664. if (e.button & 1) b = 1;
  6665. else if (e.button & 2) b = 3;
  6666. else if (e.button & 4) b = 2;
  6667. }
  6668. if (mac && e.ctrlKey && b == 1) b = 3;
  6669. return b;
  6670. }
  6671. // EVENT HANDLING
  6672. // Lightweight event framework. on/off also work on DOM nodes,
  6673. // registering native DOM handlers.
  6674. var on = CodeMirror.on = function(emitter, type, f) {
  6675. if (emitter.addEventListener)
  6676. emitter.addEventListener(type, f, false);
  6677. else if (emitter.attachEvent)
  6678. emitter.attachEvent("on" + type, f);
  6679. else {
  6680. var map = emitter._handlers || (emitter._handlers = {});
  6681. var arr = map[type] || (map[type] = []);
  6682. arr.push(f);
  6683. }
  6684. };
  6685. var off = CodeMirror.off = function(emitter, type, f) {
  6686. if (emitter.removeEventListener)
  6687. emitter.removeEventListener(type, f, false);
  6688. else if (emitter.detachEvent)
  6689. emitter.detachEvent("on" + type, f);
  6690. else {
  6691. var arr = emitter._handlers && emitter._handlers[type];
  6692. if (!arr) return;
  6693. for (var i = 0; i < arr.length; ++i)
  6694. if (arr[i] == f) { arr.splice(i, 1); break; }
  6695. }
  6696. };
  6697. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  6698. var arr = emitter._handlers && emitter._handlers[type];
  6699. if (!arr) return;
  6700. var args = Array.prototype.slice.call(arguments, 2);
  6701. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  6702. };
  6703. var orphanDelayedCallbacks = null;
  6704. // Often, we want to signal events at a point where we are in the
  6705. // middle of some work, but don't want the handler to start calling
  6706. // other methods on the editor, which might be in an inconsistent
  6707. // state or simply not expect any other events to happen.
  6708. // signalLater looks whether there are any handlers, and schedules
  6709. // them to be executed when the last operation ends, or, if no
  6710. // operation is active, when a timeout fires.
  6711. function signalLater(emitter, type /*, values...*/) {
  6712. var arr = emitter._handlers && emitter._handlers[type];
  6713. if (!arr) return;
  6714. var args = Array.prototype.slice.call(arguments, 2), list;
  6715. if (operationGroup) {
  6716. list = operationGroup.delayedCallbacks;
  6717. } else if (orphanDelayedCallbacks) {
  6718. list = orphanDelayedCallbacks;
  6719. } else {
  6720. list = orphanDelayedCallbacks = [];
  6721. setTimeout(fireOrphanDelayed, 0);
  6722. }
  6723. function bnd(f) {return function(){f.apply(null, args);};};
  6724. for (var i = 0; i < arr.length; ++i)
  6725. list.push(bnd(arr[i]));
  6726. }
  6727. function fireOrphanDelayed() {
  6728. var delayed = orphanDelayedCallbacks;
  6729. orphanDelayedCallbacks = null;
  6730. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  6731. }
  6732. // The DOM events that CodeMirror handles can be overridden by
  6733. // registering a (non-DOM) handler on the editor for the event name,
  6734. // and preventDefault-ing the event in that handler.
  6735. function signalDOMEvent(cm, e, override) {
  6736. if (typeof e == "string")
  6737. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  6738. signal(cm, override || e.type, cm, e);
  6739. return e_defaultPrevented(e) || e.codemirrorIgnore;
  6740. }
  6741. function signalCursorActivity(cm) {
  6742. var arr = cm._handlers && cm._handlers.cursorActivity;
  6743. if (!arr) return;
  6744. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  6745. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  6746. set.push(arr[i]);
  6747. }
  6748. function hasHandler(emitter, type) {
  6749. var arr = emitter._handlers && emitter._handlers[type];
  6750. return arr && arr.length > 0;
  6751. }
  6752. // Add on and off methods to a constructor's prototype, to make
  6753. // registering events on such objects more convenient.
  6754. function eventMixin(ctor) {
  6755. ctor.prototype.on = function(type, f) {on(this, type, f);};
  6756. ctor.prototype.off = function(type, f) {off(this, type, f);};
  6757. }
  6758. // MISC UTILITIES
  6759. // Number of pixels added to scroller and sizer to hide scrollbar
  6760. var scrollerGap = 30;
  6761. // Returned or thrown by various protocols to signal 'I'm not
  6762. // handling this'.
  6763. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  6764. // Reused option objects for setSelection & friends
  6765. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  6766. function Delayed() {this.id = null;}
  6767. Delayed.prototype.set = function(ms, f) {
  6768. clearTimeout(this.id);
  6769. this.id = setTimeout(f, ms);
  6770. };
  6771. // Counts the column offset in a string, taking tabs into account.
  6772. // Used mostly to find indentation.
  6773. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  6774. if (end == null) {
  6775. end = string.search(/[^\s\u00a0]/);
  6776. if (end == -1) end = string.length;
  6777. }
  6778. for (var i = startIndex || 0, n = startValue || 0;;) {
  6779. var nextTab = string.indexOf("\t", i);
  6780. if (nextTab < 0 || nextTab >= end)
  6781. return n + (end - i);
  6782. n += nextTab - i;
  6783. n += tabSize - (n % tabSize);
  6784. i = nextTab + 1;
  6785. }
  6786. };
  6787. // The inverse of countColumn -- find the offset that corresponds to
  6788. // a particular column.
  6789. function findColumn(string, goal, tabSize) {
  6790. for (var pos = 0, col = 0;;) {
  6791. var nextTab = string.indexOf("\t", pos);
  6792. if (nextTab == -1) nextTab = string.length;
  6793. var skipped = nextTab - pos;
  6794. if (nextTab == string.length || col + skipped >= goal)
  6795. return pos + Math.min(skipped, goal - col);
  6796. col += nextTab - pos;
  6797. col += tabSize - (col % tabSize);
  6798. pos = nextTab + 1;
  6799. if (col >= goal) return pos;
  6800. }
  6801. }
  6802. var spaceStrs = [""];
  6803. function spaceStr(n) {
  6804. while (spaceStrs.length <= n)
  6805. spaceStrs.push(lst(spaceStrs) + " ");
  6806. return spaceStrs[n];
  6807. }
  6808. function lst(arr) { return arr[arr.length-1]; }
  6809. var selectInput = function(node) { node.select(); };
  6810. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  6811. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  6812. else if (ie) // Suppress mysterious IE10 errors
  6813. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  6814. function indexOf(array, elt) {
  6815. for (var i = 0; i < array.length; ++i)
  6816. if (array[i] == elt) return i;
  6817. return -1;
  6818. }
  6819. function map(array, f) {
  6820. var out = [];
  6821. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  6822. return out;
  6823. }
  6824. function createObj(base, props) {
  6825. var inst;
  6826. if (Object.create) {
  6827. inst = Object.create(base);
  6828. } else {
  6829. var ctor = function() {};
  6830. ctor.prototype = base;
  6831. inst = new ctor();
  6832. }
  6833. if (props) copyObj(props, inst);
  6834. return inst;
  6835. };
  6836. function copyObj(obj, target, overwrite) {
  6837. if (!target) target = {};
  6838. for (var prop in obj)
  6839. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  6840. target[prop] = obj[prop];
  6841. return target;
  6842. }
  6843. function bind(f) {
  6844. var args = Array.prototype.slice.call(arguments, 1);
  6845. return function(){return f.apply(null, args);};
  6846. }
  6847. var nonASCIISingleCaseWordChar = /[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  6848. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  6849. return /\w/.test(ch) || ch > "\x80" &&
  6850. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  6851. };
  6852. function isWordChar(ch, helper) {
  6853. if (!helper) return isWordCharBasic(ch);
  6854. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  6855. return helper.test(ch);
  6856. }
  6857. function isEmpty(obj) {
  6858. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  6859. return true;
  6860. }
  6861. // Extending unicode characters. A series of a non-extending char +
  6862. // any number of extending chars is treated as a single unit as far
  6863. // as editing and measuring is concerned. This is not fully correct,
  6864. // since some scripts/fonts/browsers also treat other configurations
  6865. // of code points as a group.
  6866. 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]/;
  6867. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  6868. // DOM UTILITIES
  6869. function elt(tag, content, className, style) {
  6870. var e = document.createElement(tag);
  6871. if (className) e.className = className;
  6872. if (style) e.style.cssText = style;
  6873. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  6874. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  6875. return e;
  6876. }
  6877. var range;
  6878. if (document.createRange) range = function(node, start, end) {
  6879. var r = document.createRange();
  6880. r.setEnd(node, end);
  6881. r.setStart(node, start);
  6882. return r;
  6883. };
  6884. else range = function(node, start, end) {
  6885. var r = document.body.createTextRange();
  6886. try { r.moveToElementText(node.parentNode); }
  6887. catch(e) { return r; }
  6888. r.collapse(true);
  6889. r.moveEnd("character", end);
  6890. r.moveStart("character", start);
  6891. return r;
  6892. };
  6893. function removeChildren(e) {
  6894. for (var count = e.childNodes.length; count > 0; --count)
  6895. e.removeChild(e.firstChild);
  6896. return e;
  6897. }
  6898. function removeChildrenAndAdd(parent, e) {
  6899. return removeChildren(parent).appendChild(e);
  6900. }
  6901. var contains = CodeMirror.contains = function(parent, child) {
  6902. if (parent.contains)
  6903. return parent.contains(child);
  6904. while (child = child.parentNode) {
  6905. if (child.nodeType == 11) child = child.host;
  6906. if (child == parent) return true;
  6907. }
  6908. };
  6909. function activeElt() { return document.activeElement; }
  6910. // Older versions of IE throws unspecified error when touching
  6911. // document.activeElement in some cases (during loading, in iframe)
  6912. if (ie && ie_version < 11) activeElt = function() {
  6913. try { return document.activeElement; }
  6914. catch(e) { return document.body; }
  6915. };
  6916. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  6917. var rmClass = CodeMirror.rmClass = function(node, cls) {
  6918. var current = node.className;
  6919. var match = classTest(cls).exec(current);
  6920. if (match) {
  6921. var after = current.slice(match.index + match[0].length);
  6922. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  6923. }
  6924. };
  6925. var addClass = CodeMirror.addClass = function(node, cls) {
  6926. var current = node.className;
  6927. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  6928. };
  6929. function joinClasses(a, b) {
  6930. var as = a.split(" ");
  6931. for (var i = 0; i < as.length; i++)
  6932. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  6933. return b;
  6934. }
  6935. // WINDOW-WIDE EVENTS
  6936. // These must be handled carefully, because naively registering a
  6937. // handler for each editor will cause the editors to never be
  6938. // garbage collected.
  6939. function forEachCodeMirror(f) {
  6940. if (!document.body.getElementsByClassName) return;
  6941. var byClass = document.body.getElementsByClassName("CodeMirror");
  6942. for (var i = 0; i < byClass.length; i++) {
  6943. var cm = byClass[i].CodeMirror;
  6944. if (cm) f(cm);
  6945. }
  6946. }
  6947. var globalsRegistered = false;
  6948. function ensureGlobalHandlers() {
  6949. if (globalsRegistered) return;
  6950. registerGlobalHandlers();
  6951. globalsRegistered = true;
  6952. }
  6953. function registerGlobalHandlers() {
  6954. // When the window resizes, we need to refresh active editors.
  6955. var resizeTimer;
  6956. on(window, "resize", function() {
  6957. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  6958. resizeTimer = null;
  6959. forEachCodeMirror(onResize);
  6960. }, 100);
  6961. });
  6962. // When the window loses focus, we want to show the editor as blurred
  6963. on(window, "blur", function() {
  6964. forEachCodeMirror(onBlur);
  6965. });
  6966. }
  6967. // FEATURE DETECTION
  6968. // Detect drag-and-drop
  6969. var dragAndDrop = function() {
  6970. // There is *some* kind of drag-and-drop support in IE6-8, but I
  6971. // couldn't get it to work yet.
  6972. if (ie && ie_version < 9) return false;
  6973. var div = elt('div');
  6974. return "draggable" in div || "dragDrop" in div;
  6975. }();
  6976. var zwspSupported;
  6977. function zeroWidthElement(measure) {
  6978. if (zwspSupported == null) {
  6979. var test = elt("span", "\u200b");
  6980. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  6981. if (measure.firstChild.offsetHeight != 0)
  6982. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  6983. }
  6984. if (zwspSupported) return elt("span", "\u200b");
  6985. else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  6986. }
  6987. // Feature-detect IE's crummy client rect reporting for bidi text
  6988. var badBidiRects;
  6989. function hasBadBidiRects(measure) {
  6990. if (badBidiRects != null) return badBidiRects;
  6991. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  6992. var r0 = range(txt, 0, 1).getBoundingClientRect();
  6993. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  6994. var r1 = range(txt, 1, 2).getBoundingClientRect();
  6995. return badBidiRects = (r1.right - r0.right < 3);
  6996. }
  6997. // See if "".split is the broken IE version, if so, provide an
  6998. // alternative way to split lines.
  6999. var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7000. var pos = 0, result = [], l = string.length;
  7001. while (pos <= l) {
  7002. var nl = string.indexOf("\n", pos);
  7003. if (nl == -1) nl = string.length;
  7004. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7005. var rt = line.indexOf("\r");
  7006. if (rt != -1) {
  7007. result.push(line.slice(0, rt));
  7008. pos += rt + 1;
  7009. } else {
  7010. result.push(line);
  7011. pos = nl + 1;
  7012. }
  7013. }
  7014. return result;
  7015. } : function(string){return string.split(/\r\n?|\n/);};
  7016. var hasSelection = window.getSelection ? function(te) {
  7017. try { return te.selectionStart != te.selectionEnd; }
  7018. catch(e) { return false; }
  7019. } : function(te) {
  7020. try {var range = te.ownerDocument.selection.createRange();}
  7021. catch(e) {}
  7022. if (!range || range.parentElement() != te) return false;
  7023. return range.compareEndPoints("StartToEnd", range) != 0;
  7024. };
  7025. var hasCopyEvent = (function() {
  7026. var e = elt("div");
  7027. if ("oncopy" in e) return true;
  7028. e.setAttribute("oncopy", "return;");
  7029. return typeof e.oncopy == "function";
  7030. })();
  7031. var badZoomedRects = null;
  7032. function hasBadZoomedRects(measure) {
  7033. if (badZoomedRects != null) return badZoomedRects;
  7034. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7035. var normal = node.getBoundingClientRect();
  7036. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7037. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7038. }
  7039. // KEY NAMES
  7040. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7041. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7042. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7043. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
  7044. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7045. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7046. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
  7047. CodeMirror.keyNames = keyNames;
  7048. (function() {
  7049. // Number keys
  7050. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7051. // Alphabetic keys
  7052. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7053. // Function keys
  7054. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7055. })();
  7056. // BIDI HELPERS
  7057. function iterateBidiSections(order, from, to, f) {
  7058. if (!order) return f(from, to, "ltr");
  7059. var found = false;
  7060. for (var i = 0; i < order.length; ++i) {
  7061. var part = order[i];
  7062. if (part.from < to && part.to > from || from == to && part.to == from) {
  7063. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7064. found = true;
  7065. }
  7066. }
  7067. if (!found) f(from, to, "ltr");
  7068. }
  7069. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7070. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7071. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7072. function lineRight(line) {
  7073. var order = getOrder(line);
  7074. if (!order) return line.text.length;
  7075. return bidiRight(lst(order));
  7076. }
  7077. function lineStart(cm, lineN) {
  7078. var line = getLine(cm.doc, lineN);
  7079. var visual = visualLine(line);
  7080. if (visual != line) lineN = lineNo(visual);
  7081. var order = getOrder(visual);
  7082. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7083. return Pos(lineN, ch);
  7084. }
  7085. function lineEnd(cm, lineN) {
  7086. var merged, line = getLine(cm.doc, lineN);
  7087. while (merged = collapsedSpanAtEnd(line)) {
  7088. line = merged.find(1, true).line;
  7089. lineN = null;
  7090. }
  7091. var order = getOrder(line);
  7092. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7093. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7094. }
  7095. function lineStartSmart(cm, pos) {
  7096. var start = lineStart(cm, pos.line);
  7097. var line = getLine(cm.doc, start.line);
  7098. var order = getOrder(line);
  7099. if (!order || order[0].level == 0) {
  7100. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7101. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7102. return Pos(start.line, inWS ? 0 : firstNonWS);
  7103. }
  7104. return start;
  7105. }
  7106. function compareBidiLevel(order, a, b) {
  7107. var linedir = order[0].level;
  7108. if (a == linedir) return true;
  7109. if (b == linedir) return false;
  7110. return a < b;
  7111. }
  7112. var bidiOther;
  7113. function getBidiPartAt(order, pos) {
  7114. bidiOther = null;
  7115. for (var i = 0, found; i < order.length; ++i) {
  7116. var cur = order[i];
  7117. if (cur.from < pos && cur.to > pos) return i;
  7118. if ((cur.from == pos || cur.to == pos)) {
  7119. if (found == null) {
  7120. found = i;
  7121. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7122. if (cur.from != cur.to) bidiOther = found;
  7123. return i;
  7124. } else {
  7125. if (cur.from != cur.to) bidiOther = i;
  7126. return found;
  7127. }
  7128. }
  7129. }
  7130. return found;
  7131. }
  7132. function moveInLine(line, pos, dir, byUnit) {
  7133. if (!byUnit) return pos + dir;
  7134. do pos += dir;
  7135. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7136. return pos;
  7137. }
  7138. // This is needed in order to move 'visually' through bi-directional
  7139. // text -- i.e., pressing left should make the cursor go left, even
  7140. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7141. // LTR text touch each other. This often requires the cursor offset
  7142. // to move more than one unit, in order to visually move one unit.
  7143. function moveVisually(line, start, dir, byUnit) {
  7144. var bidi = getOrder(line);
  7145. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7146. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7147. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7148. for (;;) {
  7149. if (target > part.from && target < part.to) return target;
  7150. if (target == part.from || target == part.to) {
  7151. if (getBidiPartAt(bidi, target) == pos) return target;
  7152. part = bidi[pos += dir];
  7153. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7154. } else {
  7155. part = bidi[pos += dir];
  7156. if (!part) return null;
  7157. if ((dir > 0) == part.level % 2)
  7158. target = moveInLine(line, part.to, -1, byUnit);
  7159. else
  7160. target = moveInLine(line, part.from, 1, byUnit);
  7161. }
  7162. }
  7163. }
  7164. function moveLogically(line, start, dir, byUnit) {
  7165. var target = start + dir;
  7166. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7167. return target < 0 || target > line.text.length ? null : target;
  7168. }
  7169. // Bidirectional ordering algorithm
  7170. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7171. // that this (partially) implements.
  7172. // One-char codes used for character types:
  7173. // L (L): Left-to-Right
  7174. // R (R): Right-to-Left
  7175. // r (AL): Right-to-Left Arabic
  7176. // 1 (EN): European Number
  7177. // + (ES): European Number Separator
  7178. // % (ET): European Number Terminator
  7179. // n (AN): Arabic Number
  7180. // , (CS): Common Number Separator
  7181. // m (NSM): Non-Spacing Mark
  7182. // b (BN): Boundary Neutral
  7183. // s (B): Paragraph Separator
  7184. // t (S): Segment Separator
  7185. // w (WS): Whitespace
  7186. // N (ON): Other Neutrals
  7187. // Returns null if characters are ordered as they appear
  7188. // (left-to-right), or an array of sections ({from, to, level}
  7189. // objects) in the order in which they occur visually.
  7190. var bidiOrdering = (function() {
  7191. // Character types for codepoints 0 to 0xff
  7192. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7193. // Character types for codepoints 0x600 to 0x6ff
  7194. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7195. function charType(code) {
  7196. if (code <= 0xf7) return lowTypes.charAt(code);
  7197. else if (0x590 <= code && code <= 0x5f4) return "R";
  7198. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7199. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7200. else if (0x2000 <= code && code <= 0x200b) return "w";
  7201. else if (code == 0x200c) return "b";
  7202. else return "L";
  7203. }
  7204. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7205. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7206. // Browsers seem to always treat the boundaries of block elements as being L.
  7207. var outerType = "L";
  7208. function BidiSpan(level, from, to) {
  7209. this.level = level;
  7210. this.from = from; this.to = to;
  7211. }
  7212. return function(str) {
  7213. if (!bidiRE.test(str)) return false;
  7214. var len = str.length, types = [];
  7215. for (var i = 0, type; i < len; ++i)
  7216. types.push(type = charType(str.charCodeAt(i)));
  7217. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7218. // change the type of the NSM to the type of the previous
  7219. // character. If the NSM is at the start of the level run, it will
  7220. // get the type of sor.
  7221. for (var i = 0, prev = outerType; i < len; ++i) {
  7222. var type = types[i];
  7223. if (type == "m") types[i] = prev;
  7224. else prev = type;
  7225. }
  7226. // W2. Search backwards from each instance of a European number
  7227. // until the first strong type (R, L, AL, or sor) is found. If an
  7228. // AL is found, change the type of the European number to Arabic
  7229. // number.
  7230. // W3. Change all ALs to R.
  7231. for (var i = 0, cur = outerType; i < len; ++i) {
  7232. var type = types[i];
  7233. if (type == "1" && cur == "r") types[i] = "n";
  7234. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7235. }
  7236. // W4. A single European separator between two European numbers
  7237. // changes to a European number. A single common separator between
  7238. // two numbers of the same type changes to that type.
  7239. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7240. var type = types[i];
  7241. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  7242. else if (type == "," && prev == types[i+1] &&
  7243. (prev == "1" || prev == "n")) types[i] = prev;
  7244. prev = type;
  7245. }
  7246. // W5. A sequence of European terminators adjacent to European
  7247. // numbers changes to all European numbers.
  7248. // W6. Otherwise, separators and terminators change to Other
  7249. // Neutral.
  7250. for (var i = 0; i < len; ++i) {
  7251. var type = types[i];
  7252. if (type == ",") types[i] = "N";
  7253. else if (type == "%") {
  7254. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  7255. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7256. for (var j = i; j < end; ++j) types[j] = replace;
  7257. i = end - 1;
  7258. }
  7259. }
  7260. // W7. Search backwards from each instance of a European number
  7261. // until the first strong type (R, L, or sor) is found. If an L is
  7262. // found, then change the type of the European number to L.
  7263. for (var i = 0, cur = outerType; i < len; ++i) {
  7264. var type = types[i];
  7265. if (cur == "L" && type == "1") types[i] = "L";
  7266. else if (isStrong.test(type)) cur = type;
  7267. }
  7268. // N1. A sequence of neutrals takes the direction of the
  7269. // surrounding strong text if the text on both sides has the same
  7270. // direction. European and Arabic numbers act as if they were R in
  7271. // terms of their influence on neutrals. Start-of-level-run (sor)
  7272. // and end-of-level-run (eor) are used at level run boundaries.
  7273. // N2. Any remaining neutrals take the embedding direction.
  7274. for (var i = 0; i < len; ++i) {
  7275. if (isNeutral.test(types[i])) {
  7276. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  7277. var before = (i ? types[i-1] : outerType) == "L";
  7278. var after = (end < len ? types[end] : outerType) == "L";
  7279. var replace = before || after ? "L" : "R";
  7280. for (var j = i; j < end; ++j) types[j] = replace;
  7281. i = end - 1;
  7282. }
  7283. }
  7284. // Here we depart from the documented algorithm, in order to avoid
  7285. // building up an actual levels array. Since there are only three
  7286. // levels (0, 1, 2) in an implementation that doesn't take
  7287. // explicit embedding into account, we can build up the order on
  7288. // the fly, without following the level-based algorithm.
  7289. var order = [], m;
  7290. for (var i = 0; i < len;) {
  7291. if (countsAsLeft.test(types[i])) {
  7292. var start = i;
  7293. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  7294. order.push(new BidiSpan(0, start, i));
  7295. } else {
  7296. var pos = i, at = order.length;
  7297. for (++i; i < len && types[i] != "L"; ++i) {}
  7298. for (var j = pos; j < i;) {
  7299. if (countsAsNum.test(types[j])) {
  7300. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  7301. var nstart = j;
  7302. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  7303. order.splice(at, 0, new BidiSpan(2, nstart, j));
  7304. pos = j;
  7305. } else ++j;
  7306. }
  7307. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  7308. }
  7309. }
  7310. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  7311. order[0].from = m[0].length;
  7312. order.unshift(new BidiSpan(0, 0, m[0].length));
  7313. }
  7314. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  7315. lst(order).to -= m[0].length;
  7316. order.push(new BidiSpan(0, len - m[0].length, len));
  7317. }
  7318. if (order[0].level != lst(order).level)
  7319. order.push(new BidiSpan(order[0].level, len, len));
  7320. return order;
  7321. };
  7322. })();
  7323. // THE END
  7324. CodeMirror.version = "4.13.0";
  7325. return CodeMirror;
  7326. });