codemirror.js 347 KB

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