codemirror.js 345 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890
  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 || window).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 userAgent = navigator.userAgent;
  21. var platform = navigator.platform;
  22. var gecko = /gecko\/\d/i.test(userAgent);
  23. var ie_upto10 = /MSIE \d/.test(userAgent);
  24. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  25. var ie = ie_upto10 || ie_11up;
  26. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  27. var webkit = /WebKit\//.test(userAgent);
  28. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  29. var chrome = /Chrome\//.test(userAgent);
  30. var presto = /Opera\//.test(userAgent);
  31. var safari = /Apple Computer/.test(navigator.vendor);
  32. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  33. var phantom = /PhantomJS/.test(userAgent);
  34. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(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(userAgent);
  37. var mac = ios || /Mac/.test(platform);
  38. var windows = /win/i.test(platform);
  39. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  40. if (presto_version) presto_version = Number(presto_version[1]);
  41. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  42. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  43. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  44. var captureRightClick = gecko || (ie && ie_version >= 9);
  45. // Optimize some code when these features are not used.
  46. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  47. // EDITOR CONSTRUCTOR
  48. // A CodeMirror instance represents an editor. This is the object
  49. // that user code is usually dealing with.
  50. function CodeMirror(place, options) {
  51. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  52. this.options = options = options ? copyObj(options) : {};
  53. // Determine effective options based on given values and defaults.
  54. copyObj(defaults, options, false);
  55. setGuttersForLineNumbers(options);
  56. var doc = options.value;
  57. if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
  58. this.doc = doc;
  59. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  60. var display = this.display = new Display(place, doc, input);
  61. display.wrapper.CodeMirror = this;
  62. updateGutters(this);
  63. themeChanged(this);
  64. if (options.lineWrapping)
  65. this.display.wrapper.className += " CodeMirror-wrap";
  66. if (options.autofocus && !mobile) display.input.focus();
  67. initScrollbars(this);
  68. this.state = {
  69. keyMaps: [], // stores maps added by addKeyMap
  70. overlays: [], // highlighting overlays, as added by addOverlay
  71. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  72. overwrite: false,
  73. delayingBlurEvent: false,
  74. focused: false,
  75. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  76. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  77. selectingText: false,
  78. draggingText: false,
  79. highlight: new Delayed(), // stores highlight worker timeout
  80. keySeq: null, // Unfinished key sequence
  81. specialChars: null
  82. };
  83. var cm = this;
  84. // Override magic textarea content restore that IE sometimes does
  85. // on our hidden textarea on reload
  86. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  87. registerEventHandlers(this);
  88. ensureGlobalHandlers();
  89. startOperation(this);
  90. this.curOp.forceUpdate = true;
  91. attachDoc(this, doc);
  92. if ((options.autofocus && !mobile) || cm.hasFocus())
  93. setTimeout(bind(onFocus, this), 20);
  94. else
  95. onBlur(this);
  96. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  97. optionHandlers[opt](this, options[opt], Init);
  98. maybeUpdateLineNumberWidth(this);
  99. if (options.finishInit) options.finishInit(this);
  100. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  101. endOperation(this);
  102. // Suppress optimizelegibility in Webkit, since it breaks text
  103. // measuring on line wrapping boundaries.
  104. if (webkit && options.lineWrapping &&
  105. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  106. display.lineDiv.style.textRendering = "auto";
  107. }
  108. // DISPLAY CONSTRUCTOR
  109. // The display handles the DOM integration, both for input reading
  110. // and content drawing. It holds references to DOM nodes and
  111. // display-related state.
  112. function Display(place, doc, input) {
  113. var d = this;
  114. this.input = input;
  115. // Covers bottom-right square when both scrollbars are present.
  116. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  117. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  118. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  119. // and h scrollbar is present.
  120. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  121. d.gutterFiller.setAttribute("cm-not-content", "true");
  122. // Will contain the actual code, positioned to cover the viewport.
  123. d.lineDiv = elt("div", null, "CodeMirror-code");
  124. // Elements are added to these to represent selection and cursors.
  125. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  126. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  127. // A visibility: hidden element used to find the size of things.
  128. d.measure = elt("div", null, "CodeMirror-measure");
  129. // When lines outside of the viewport are measured, they are drawn in this.
  130. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  131. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  132. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  133. null, "position: relative; outline: none");
  134. // Moved around its parent to cover visible view.
  135. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  136. // Set to the height of the document, allowing scrolling.
  137. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  138. d.sizerWidth = null;
  139. // Behavior of elts with overflow: auto and padding is
  140. // inconsistent across browsers. This is used to ensure the
  141. // scrollable area is big enough.
  142. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  143. // Will contain the gutters, if any.
  144. d.gutters = elt("div", null, "CodeMirror-gutters");
  145. d.lineGutter = null;
  146. // Actual scrollable element.
  147. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  148. d.scroller.setAttribute("tabIndex", "-1");
  149. // The element in which the editor lives.
  150. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  151. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  152. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  153. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  154. if (place) {
  155. if (place.appendChild) place.appendChild(d.wrapper);
  156. else place(d.wrapper);
  157. }
  158. // Current rendered range (may be bigger than the view window).
  159. d.viewFrom = d.viewTo = doc.first;
  160. d.reportedViewFrom = d.reportedViewTo = doc.first;
  161. // Information about the rendered lines.
  162. d.view = [];
  163. d.renderedView = null;
  164. // Holds info about a single rendered line when it was rendered
  165. // for measurement, while not in view.
  166. d.externalMeasured = null;
  167. // Empty space (in pixels) above the view
  168. d.viewOffset = 0;
  169. d.lastWrapHeight = d.lastWrapWidth = 0;
  170. d.updateLineNumbers = null;
  171. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  172. d.scrollbarsClipped = false;
  173. // Used to only resize the line number gutter when necessary (when
  174. // the amount of lines crosses a boundary that makes its width change)
  175. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  176. // Set to true when a non-horizontal-scrolling line widget is
  177. // added. As an optimization, line widget aligning is skipped when
  178. // this is false.
  179. d.alignWidgets = false;
  180. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  181. // Tracks the maximum line length so that the horizontal scrollbar
  182. // can be kept static when scrolling.
  183. d.maxLine = null;
  184. d.maxLineLength = 0;
  185. d.maxLineChanged = false;
  186. // Used for measuring wheel scrolling granularity
  187. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  188. // True when shift is held down.
  189. d.shift = false;
  190. // Used to track whether anything happened since the context menu
  191. // was opened.
  192. d.selForContextMenu = null;
  193. d.activeTouch = null;
  194. input.init(d);
  195. }
  196. // STATE UPDATES
  197. // Used to get the editor into a consistent state again when options change.
  198. function loadMode(cm) {
  199. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  200. resetModeState(cm);
  201. }
  202. function resetModeState(cm) {
  203. cm.doc.iter(function(line) {
  204. if (line.stateAfter) line.stateAfter = null;
  205. if (line.styles) line.styles = null;
  206. });
  207. cm.doc.frontier = cm.doc.first;
  208. startWorker(cm, 100);
  209. cm.state.modeGen++;
  210. if (cm.curOp) regChange(cm);
  211. }
  212. function wrappingChanged(cm) {
  213. if (cm.options.lineWrapping) {
  214. addClass(cm.display.wrapper, "CodeMirror-wrap");
  215. cm.display.sizer.style.minWidth = "";
  216. cm.display.sizerWidth = null;
  217. } else {
  218. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  219. findMaxLine(cm);
  220. }
  221. estimateLineHeights(cm);
  222. regChange(cm);
  223. clearCaches(cm);
  224. setTimeout(function(){updateScrollbars(cm);}, 100);
  225. }
  226. // Returns a function that estimates the height of a line, to use as
  227. // first approximation until the line becomes visible (and is thus
  228. // properly measurable).
  229. function estimateHeight(cm) {
  230. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  231. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  232. return function(line) {
  233. if (lineIsHidden(cm.doc, line)) return 0;
  234. var widgetsHeight = 0;
  235. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  236. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  237. }
  238. if (wrapping)
  239. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  240. else
  241. return widgetsHeight + th;
  242. };
  243. }
  244. function estimateLineHeights(cm) {
  245. var doc = cm.doc, est = estimateHeight(cm);
  246. doc.iter(function(line) {
  247. var estHeight = est(line);
  248. if (estHeight != line.height) updateLineHeight(line, estHeight);
  249. });
  250. }
  251. function themeChanged(cm) {
  252. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  253. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  254. clearCaches(cm);
  255. }
  256. function guttersChanged(cm) {
  257. updateGutters(cm);
  258. regChange(cm);
  259. setTimeout(function(){alignHorizontally(cm);}, 20);
  260. }
  261. // Rebuild the gutter elements, ensure the margin to the left of the
  262. // code matches their width.
  263. function updateGutters(cm) {
  264. var gutters = cm.display.gutters, specs = cm.options.gutters;
  265. removeChildren(gutters);
  266. for (var i = 0; i < specs.length; ++i) {
  267. var gutterClass = specs[i];
  268. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  269. if (gutterClass == "CodeMirror-linenumbers") {
  270. cm.display.lineGutter = gElt;
  271. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  272. }
  273. }
  274. gutters.style.display = i ? "" : "none";
  275. updateGutterSpace(cm);
  276. }
  277. function updateGutterSpace(cm) {
  278. var width = cm.display.gutters.offsetWidth;
  279. cm.display.sizer.style.marginLeft = width + "px";
  280. }
  281. // Compute the character length of a line, taking into account
  282. // collapsed ranges (see markText) that might hide parts, and join
  283. // other lines onto it.
  284. function lineLength(line) {
  285. if (line.height == 0) return 0;
  286. var len = line.text.length, merged, cur = line;
  287. while (merged = collapsedSpanAtStart(cur)) {
  288. var found = merged.find(0, true);
  289. cur = found.from.line;
  290. len += found.from.ch - found.to.ch;
  291. }
  292. cur = line;
  293. while (merged = collapsedSpanAtEnd(cur)) {
  294. var found = merged.find(0, true);
  295. len -= cur.text.length - found.from.ch;
  296. cur = found.to.line;
  297. len += cur.text.length - found.to.ch;
  298. }
  299. return len;
  300. }
  301. // Find the longest line in the document.
  302. function findMaxLine(cm) {
  303. var d = cm.display, doc = cm.doc;
  304. d.maxLine = getLine(doc, doc.first);
  305. d.maxLineLength = lineLength(d.maxLine);
  306. d.maxLineChanged = true;
  307. doc.iter(function(line) {
  308. var len = lineLength(line);
  309. if (len > d.maxLineLength) {
  310. d.maxLineLength = len;
  311. d.maxLine = line;
  312. }
  313. });
  314. }
  315. // Make sure the gutters options contains the element
  316. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  317. function setGuttersForLineNumbers(options) {
  318. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  319. if (found == -1 && options.lineNumbers) {
  320. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  321. } else if (found > -1 && !options.lineNumbers) {
  322. options.gutters = options.gutters.slice(0);
  323. options.gutters.splice(found, 1);
  324. }
  325. }
  326. // SCROLLBARS
  327. // Prepare DOM reads needed to update the scrollbars. Done in one
  328. // shot to minimize update/measure roundtrips.
  329. function measureForScrollbars(cm) {
  330. var d = cm.display, gutterW = d.gutters.offsetWidth;
  331. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  332. return {
  333. clientHeight: d.scroller.clientHeight,
  334. viewHeight: d.wrapper.clientHeight,
  335. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  336. viewWidth: d.wrapper.clientWidth,
  337. barLeft: cm.options.fixedGutter ? gutterW : 0,
  338. docHeight: docH,
  339. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  340. nativeBarWidth: d.nativeBarWidth,
  341. gutterWidth: gutterW
  342. };
  343. }
  344. function NativeScrollbars(place, scroll, cm) {
  345. this.cm = cm;
  346. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  347. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  348. place(vert); place(horiz);
  349. on(vert, "scroll", function() {
  350. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  351. });
  352. on(horiz, "scroll", function() {
  353. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  354. });
  355. this.checkedZeroWidth = false;
  356. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  357. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  358. }
  359. NativeScrollbars.prototype = copyObj({
  360. update: function(measure) {
  361. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  362. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  363. var sWidth = measure.nativeBarWidth;
  364. if (needsV) {
  365. this.vert.style.display = "block";
  366. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  367. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  368. // A bug in IE8 can cause this value to be negative, so guard it.
  369. this.vert.firstChild.style.height =
  370. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  371. } else {
  372. this.vert.style.display = "";
  373. this.vert.firstChild.style.height = "0";
  374. }
  375. if (needsH) {
  376. this.horiz.style.display = "block";
  377. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  378. this.horiz.style.left = measure.barLeft + "px";
  379. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  380. this.horiz.firstChild.style.width =
  381. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  382. } else {
  383. this.horiz.style.display = "";
  384. this.horiz.firstChild.style.width = "0";
  385. }
  386. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  387. if (sWidth == 0) this.zeroWidthHack();
  388. this.checkedZeroWidth = true;
  389. }
  390. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  391. },
  392. setScrollLeft: function(pos) {
  393. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  394. if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
  395. },
  396. setScrollTop: function(pos) {
  397. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  398. if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
  399. },
  400. zeroWidthHack: function() {
  401. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  402. this.horiz.style.height = this.vert.style.width = w;
  403. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  404. this.disableHoriz = new Delayed;
  405. this.disableVert = new Delayed;
  406. },
  407. enableZeroWidthBar: function(bar, delay) {
  408. bar.style.pointerEvents = "auto";
  409. function maybeDisable() {
  410. // To find out whether the scrollbar is still visible, we
  411. // check whether the element under the pixel in the bottom
  412. // left corner of the scrollbar box is the scrollbar box
  413. // itself (when the bar is still visible) or its filler child
  414. // (when the bar is hidden). If it is still visible, we keep
  415. // it enabled, if it's hidden, we disable pointer events.
  416. var box = bar.getBoundingClientRect();
  417. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
  418. if (elt != bar) bar.style.pointerEvents = "none";
  419. else delay.set(1000, maybeDisable);
  420. }
  421. delay.set(1000, maybeDisable);
  422. },
  423. clear: function() {
  424. var parent = this.horiz.parentNode;
  425. parent.removeChild(this.horiz);
  426. parent.removeChild(this.vert);
  427. }
  428. }, NativeScrollbars.prototype);
  429. function NullScrollbars() {}
  430. NullScrollbars.prototype = copyObj({
  431. update: function() { return {bottom: 0, right: 0}; },
  432. setScrollLeft: function() {},
  433. setScrollTop: function() {},
  434. clear: function() {}
  435. }, NullScrollbars.prototype);
  436. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  437. function initScrollbars(cm) {
  438. if (cm.display.scrollbars) {
  439. cm.display.scrollbars.clear();
  440. if (cm.display.scrollbars.addClass)
  441. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  442. }
  443. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  444. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  445. // Prevent clicks in the scrollbars from killing focus
  446. on(node, "mousedown", function() {
  447. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  448. });
  449. node.setAttribute("cm-not-content", "true");
  450. }, function(pos, axis) {
  451. if (axis == "horizontal") setScrollLeft(cm, pos);
  452. else setScrollTop(cm, pos);
  453. }, cm);
  454. if (cm.display.scrollbars.addClass)
  455. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  456. }
  457. function updateScrollbars(cm, measure) {
  458. if (!measure) measure = measureForScrollbars(cm);
  459. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  460. updateScrollbarsInner(cm, measure);
  461. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  462. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  463. updateHeightsInViewport(cm);
  464. updateScrollbarsInner(cm, measureForScrollbars(cm));
  465. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  466. }
  467. }
  468. // Re-synchronize the fake scrollbars with the actual size of the
  469. // content.
  470. function updateScrollbarsInner(cm, measure) {
  471. var d = cm.display;
  472. var sizes = d.scrollbars.update(measure);
  473. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  474. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  475. if (sizes.right && sizes.bottom) {
  476. d.scrollbarFiller.style.display = "block";
  477. d.scrollbarFiller.style.height = sizes.bottom + "px";
  478. d.scrollbarFiller.style.width = sizes.right + "px";
  479. } else d.scrollbarFiller.style.display = "";
  480. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  481. d.gutterFiller.style.display = "block";
  482. d.gutterFiller.style.height = sizes.bottom + "px";
  483. d.gutterFiller.style.width = measure.gutterWidth + "px";
  484. } else d.gutterFiller.style.display = "";
  485. }
  486. // Compute the lines that are visible in a given viewport (defaults
  487. // the the current scroll position). viewport may contain top,
  488. // height, and ensure (see op.scrollToPos) properties.
  489. function visibleLines(display, doc, viewport) {
  490. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  491. top = Math.floor(top - paddingTop(display));
  492. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  493. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  494. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  495. // forces those lines into the viewport (if possible).
  496. if (viewport && viewport.ensure) {
  497. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  498. if (ensureFrom < from) {
  499. from = ensureFrom;
  500. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  501. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  502. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  503. to = ensureTo;
  504. }
  505. }
  506. return {from: from, to: Math.max(to, from + 1)};
  507. }
  508. // LINE NUMBERS
  509. // Re-align line numbers and gutter marks to compensate for
  510. // horizontal scrolling.
  511. function alignHorizontally(cm) {
  512. var display = cm.display, view = display.view;
  513. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  514. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  515. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  516. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  517. if (cm.options.fixedGutter && view[i].gutter)
  518. view[i].gutter.style.left = left;
  519. var align = view[i].alignable;
  520. if (align) for (var j = 0; j < align.length; j++)
  521. align[j].style.left = left;
  522. }
  523. if (cm.options.fixedGutter)
  524. display.gutters.style.left = (comp + gutterW) + "px";
  525. }
  526. // Used to ensure that the line number gutter is still the right
  527. // size for the current document size. Returns true when an update
  528. // is needed.
  529. function maybeUpdateLineNumberWidth(cm) {
  530. if (!cm.options.lineNumbers) return false;
  531. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  532. if (last.length != display.lineNumChars) {
  533. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  534. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  535. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  536. display.lineGutter.style.width = "";
  537. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  538. display.lineNumWidth = display.lineNumInnerWidth + padding;
  539. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  540. display.lineGutter.style.width = display.lineNumWidth + "px";
  541. updateGutterSpace(cm);
  542. return true;
  543. }
  544. return false;
  545. }
  546. function lineNumberFor(options, i) {
  547. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  548. }
  549. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  550. // but using getBoundingClientRect to get a sub-pixel-accurate
  551. // result.
  552. function compensateForHScroll(display) {
  553. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  554. }
  555. // DISPLAY DRAWING
  556. function DisplayUpdate(cm, viewport, force) {
  557. var display = cm.display;
  558. this.viewport = viewport;
  559. // Store some values that we'll need later (but don't want to force a relayout for)
  560. this.visible = visibleLines(display, cm.doc, viewport);
  561. this.editorIsHidden = !display.wrapper.offsetWidth;
  562. this.wrapperHeight = display.wrapper.clientHeight;
  563. this.wrapperWidth = display.wrapper.clientWidth;
  564. this.oldDisplayWidth = displayWidth(cm);
  565. this.force = force;
  566. this.dims = getDimensions(cm);
  567. this.events = [];
  568. }
  569. DisplayUpdate.prototype.signal = function(emitter, type) {
  570. if (hasHandler(emitter, type))
  571. this.events.push(arguments);
  572. };
  573. DisplayUpdate.prototype.finish = function() {
  574. for (var i = 0; i < this.events.length; i++)
  575. signal.apply(null, this.events[i]);
  576. };
  577. function maybeClipScrollbars(cm) {
  578. var display = cm.display;
  579. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  580. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  581. display.heightForcer.style.height = scrollGap(cm) + "px";
  582. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  583. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  584. display.scrollbarsClipped = true;
  585. }
  586. }
  587. // Does the actual updating of the line display. Bails out
  588. // (returning false) when there is nothing to be done and forced is
  589. // false.
  590. function updateDisplayIfNeeded(cm, update) {
  591. var display = cm.display, doc = cm.doc;
  592. if (update.editorIsHidden) {
  593. resetView(cm);
  594. return false;
  595. }
  596. // Bail out if the visible area is already rendered and nothing changed.
  597. if (!update.force &&
  598. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  599. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  600. display.renderedView == display.view && countDirtyView(cm) == 0)
  601. return false;
  602. if (maybeUpdateLineNumberWidth(cm)) {
  603. resetView(cm);
  604. update.dims = getDimensions(cm);
  605. }
  606. // Compute a suitable new viewport (from & to)
  607. var end = doc.first + doc.size;
  608. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  609. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  610. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  611. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  612. if (sawCollapsedSpans) {
  613. from = visualLineNo(cm.doc, from);
  614. to = visualLineEndNo(cm.doc, to);
  615. }
  616. var different = from != display.viewFrom || to != display.viewTo ||
  617. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  618. adjustView(cm, from, to);
  619. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  620. // Position the mover div to align with the current scroll position
  621. cm.display.mover.style.top = display.viewOffset + "px";
  622. var toUpdate = countDirtyView(cm);
  623. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  624. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  625. return false;
  626. // For big changes, we hide the enclosing element during the
  627. // update, since that speeds up the operations on most browsers.
  628. var focused = activeElt();
  629. if (toUpdate > 4) display.lineDiv.style.display = "none";
  630. patchDisplay(cm, display.updateLineNumbers, update.dims);
  631. if (toUpdate > 4) display.lineDiv.style.display = "";
  632. display.renderedView = display.view;
  633. // There might have been a widget with a focused element that got
  634. // hidden or updated, if so re-focus it.
  635. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  636. // Prevent selection and cursors from interfering with the scroll
  637. // width and height.
  638. removeChildren(display.cursorDiv);
  639. removeChildren(display.selectionDiv);
  640. display.gutters.style.height = display.sizer.style.minHeight = 0;
  641. if (different) {
  642. display.lastWrapHeight = update.wrapperHeight;
  643. display.lastWrapWidth = update.wrapperWidth;
  644. startWorker(cm, 400);
  645. }
  646. display.updateLineNumbers = null;
  647. return true;
  648. }
  649. function postUpdateDisplay(cm, update) {
  650. var viewport = update.viewport;
  651. for (var first = true;; first = false) {
  652. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  653. // Clip forced viewport to actual scrollable area.
  654. if (viewport && viewport.top != null)
  655. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  656. // Updated line heights might result in the drawn area not
  657. // actually covering the viewport. Keep looping until it does.
  658. update.visible = visibleLines(cm.display, cm.doc, viewport);
  659. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  660. break;
  661. }
  662. if (!updateDisplayIfNeeded(cm, update)) break;
  663. updateHeightsInViewport(cm);
  664. var barMeasure = measureForScrollbars(cm);
  665. updateSelection(cm);
  666. setDocumentHeight(cm, barMeasure);
  667. updateScrollbars(cm, barMeasure);
  668. }
  669. update.signal(cm, "update", cm);
  670. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  671. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  672. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  673. }
  674. }
  675. function updateDisplaySimple(cm, viewport) {
  676. var update = new DisplayUpdate(cm, viewport);
  677. if (updateDisplayIfNeeded(cm, update)) {
  678. updateHeightsInViewport(cm);
  679. postUpdateDisplay(cm, update);
  680. var barMeasure = measureForScrollbars(cm);
  681. updateSelection(cm);
  682. setDocumentHeight(cm, barMeasure);
  683. updateScrollbars(cm, barMeasure);
  684. update.finish();
  685. }
  686. }
  687. function setDocumentHeight(cm, measure) {
  688. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  689. var total = measure.docHeight + cm.display.barHeight;
  690. cm.display.heightForcer.style.top = total + "px";
  691. cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
  692. }
  693. // Read the actual heights of the rendered lines, and update their
  694. // stored heights to match.
  695. function updateHeightsInViewport(cm) {
  696. var display = cm.display;
  697. var prevBottom = display.lineDiv.offsetTop;
  698. for (var i = 0; i < display.view.length; i++) {
  699. var cur = display.view[i], height;
  700. if (cur.hidden) continue;
  701. if (ie && ie_version < 8) {
  702. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  703. height = bot - prevBottom;
  704. prevBottom = bot;
  705. } else {
  706. var box = cur.node.getBoundingClientRect();
  707. height = box.bottom - box.top;
  708. }
  709. var diff = cur.line.height - height;
  710. if (height < 2) height = textHeight(display);
  711. if (diff > .001 || diff < -.001) {
  712. updateLineHeight(cur.line, height);
  713. updateWidgetHeight(cur.line);
  714. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  715. updateWidgetHeight(cur.rest[j]);
  716. }
  717. }
  718. }
  719. // Read and store the height of line widgets associated with the
  720. // given line.
  721. function updateWidgetHeight(line) {
  722. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  723. line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
  724. }
  725. // Do a bulk-read of the DOM positions and sizes needed to draw the
  726. // view, so that we don't interleave reading and writing to the DOM.
  727. function getDimensions(cm) {
  728. var d = cm.display, left = {}, width = {};
  729. var gutterLeft = d.gutters.clientLeft;
  730. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  731. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  732. width[cm.options.gutters[i]] = n.clientWidth;
  733. }
  734. return {fixedPos: compensateForHScroll(d),
  735. gutterTotalWidth: d.gutters.offsetWidth,
  736. gutterLeft: left,
  737. gutterWidth: width,
  738. wrapperWidth: d.wrapper.clientWidth};
  739. }
  740. // Sync the actual display DOM structure with display.view, removing
  741. // nodes for lines that are no longer in view, and creating the ones
  742. // that are not there yet, and updating the ones that are out of
  743. // date.
  744. function patchDisplay(cm, updateNumbersFrom, dims) {
  745. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  746. var container = display.lineDiv, cur = container.firstChild;
  747. function rm(node) {
  748. var next = node.nextSibling;
  749. // Works around a throw-scroll bug in OS X Webkit
  750. if (webkit && mac && cm.display.currentWheelTarget == node)
  751. node.style.display = "none";
  752. else
  753. node.parentNode.removeChild(node);
  754. return next;
  755. }
  756. var view = display.view, lineN = display.viewFrom;
  757. // Loop over the elements in the view, syncing cur (the DOM nodes
  758. // in display.lineDiv) with the view as we go.
  759. for (var i = 0; i < view.length; i++) {
  760. var lineView = view[i];
  761. if (lineView.hidden) {
  762. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  763. var node = buildLineElement(cm, lineView, lineN, dims);
  764. container.insertBefore(node, cur);
  765. } else { // Already drawn
  766. while (cur != lineView.node) cur = rm(cur);
  767. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  768. updateNumbersFrom <= lineN && lineView.lineNumber;
  769. if (lineView.changes) {
  770. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  771. updateLineForChanges(cm, lineView, lineN, dims);
  772. }
  773. if (updateNumber) {
  774. removeChildren(lineView.lineNumber);
  775. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  776. }
  777. cur = lineView.node.nextSibling;
  778. }
  779. lineN += lineView.size;
  780. }
  781. while (cur) cur = rm(cur);
  782. }
  783. // When an aspect of a line changes, a string is added to
  784. // lineView.changes. This updates the relevant part of the line's
  785. // DOM structure.
  786. function updateLineForChanges(cm, lineView, lineN, dims) {
  787. for (var j = 0; j < lineView.changes.length; j++) {
  788. var type = lineView.changes[j];
  789. if (type == "text") updateLineText(cm, lineView);
  790. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  791. else if (type == "class") updateLineClasses(lineView);
  792. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  793. }
  794. lineView.changes = null;
  795. }
  796. // Lines with gutter elements, widgets or a background class need to
  797. // be wrapped, and have the extra elements added to the wrapper div
  798. function ensureLineWrapped(lineView) {
  799. if (lineView.node == lineView.text) {
  800. lineView.node = elt("div", null, null, "position: relative");
  801. if (lineView.text.parentNode)
  802. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  803. lineView.node.appendChild(lineView.text);
  804. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  805. }
  806. return lineView.node;
  807. }
  808. function updateLineBackground(lineView) {
  809. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  810. if (cls) cls += " CodeMirror-linebackground";
  811. if (lineView.background) {
  812. if (cls) lineView.background.className = cls;
  813. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  814. } else if (cls) {
  815. var wrap = ensureLineWrapped(lineView);
  816. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  817. }
  818. }
  819. // Wrapper around buildLineContent which will reuse the structure
  820. // in display.externalMeasured when possible.
  821. function getLineContent(cm, lineView) {
  822. var ext = cm.display.externalMeasured;
  823. if (ext && ext.line == lineView.line) {
  824. cm.display.externalMeasured = null;
  825. lineView.measure = ext.measure;
  826. return ext.built;
  827. }
  828. return buildLineContent(cm, lineView);
  829. }
  830. // Redraw the line's text. Interacts with the background and text
  831. // classes because the mode may output tokens that influence these
  832. // classes.
  833. function updateLineText(cm, lineView) {
  834. var cls = lineView.text.className;
  835. var built = getLineContent(cm, lineView);
  836. if (lineView.text == lineView.node) lineView.node = built.pre;
  837. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  838. lineView.text = built.pre;
  839. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  840. lineView.bgClass = built.bgClass;
  841. lineView.textClass = built.textClass;
  842. updateLineClasses(lineView);
  843. } else if (cls) {
  844. lineView.text.className = cls;
  845. }
  846. }
  847. function updateLineClasses(lineView) {
  848. updateLineBackground(lineView);
  849. if (lineView.line.wrapClass)
  850. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  851. else if (lineView.node != lineView.text)
  852. lineView.node.className = "";
  853. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  854. lineView.text.className = textClass || "";
  855. }
  856. function updateLineGutter(cm, lineView, lineN, dims) {
  857. if (lineView.gutter) {
  858. lineView.node.removeChild(lineView.gutter);
  859. lineView.gutter = null;
  860. }
  861. if (lineView.gutterBackground) {
  862. lineView.node.removeChild(lineView.gutterBackground);
  863. lineView.gutterBackground = null;
  864. }
  865. if (lineView.line.gutterClass) {
  866. var wrap = ensureLineWrapped(lineView);
  867. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  868. "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  869. "px; width: " + dims.gutterTotalWidth + "px");
  870. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  871. }
  872. var markers = lineView.line.gutterMarkers;
  873. if (cm.options.lineNumbers || markers) {
  874. var wrap = ensureLineWrapped(lineView);
  875. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  876. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
  877. cm.display.input.setUneditable(gutterWrap);
  878. wrap.insertBefore(gutterWrap, lineView.text);
  879. if (lineView.line.gutterClass)
  880. gutterWrap.className += " " + lineView.line.gutterClass;
  881. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  882. lineView.lineNumber = gutterWrap.appendChild(
  883. elt("div", lineNumberFor(cm.options, lineN),
  884. "CodeMirror-linenumber CodeMirror-gutter-elt",
  885. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  886. + cm.display.lineNumInnerWidth + "px"));
  887. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  888. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  889. if (found)
  890. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  891. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  892. }
  893. }
  894. }
  895. function updateLineWidgets(cm, lineView, dims) {
  896. if (lineView.alignable) lineView.alignable = null;
  897. for (var node = lineView.node.firstChild, next; node; node = next) {
  898. var next = node.nextSibling;
  899. if (node.className == "CodeMirror-linewidget")
  900. lineView.node.removeChild(node);
  901. }
  902. insertLineWidgets(cm, lineView, dims);
  903. }
  904. // Build a line's DOM representation from scratch
  905. function buildLineElement(cm, lineView, lineN, dims) {
  906. var built = getLineContent(cm, lineView);
  907. lineView.text = lineView.node = built.pre;
  908. if (built.bgClass) lineView.bgClass = built.bgClass;
  909. if (built.textClass) lineView.textClass = built.textClass;
  910. updateLineClasses(lineView);
  911. updateLineGutter(cm, lineView, lineN, dims);
  912. insertLineWidgets(cm, lineView, dims);
  913. return lineView.node;
  914. }
  915. // A lineView may contain multiple logical lines (when merged by
  916. // collapsed spans). The widgets for all of them need to be drawn.
  917. function insertLineWidgets(cm, lineView, dims) {
  918. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  919. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  920. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  921. }
  922. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  923. if (!line.widgets) return;
  924. var wrap = ensureLineWrapped(lineView);
  925. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  926. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  927. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  928. positionLineWidget(widget, node, lineView, dims);
  929. cm.display.input.setUneditable(node);
  930. if (allowAbove && widget.above)
  931. wrap.insertBefore(node, lineView.gutter || lineView.text);
  932. else
  933. wrap.appendChild(node);
  934. signalLater(widget, "redraw");
  935. }
  936. }
  937. function positionLineWidget(widget, node, lineView, dims) {
  938. if (widget.noHScroll) {
  939. (lineView.alignable || (lineView.alignable = [])).push(node);
  940. var width = dims.wrapperWidth;
  941. node.style.left = dims.fixedPos + "px";
  942. if (!widget.coverGutter) {
  943. width -= dims.gutterTotalWidth;
  944. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  945. }
  946. node.style.width = width + "px";
  947. }
  948. if (widget.coverGutter) {
  949. node.style.zIndex = 5;
  950. node.style.position = "relative";
  951. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  952. }
  953. }
  954. // POSITION OBJECT
  955. // A Pos instance represents a position within the text.
  956. var Pos = CodeMirror.Pos = function(line, ch) {
  957. if (!(this instanceof Pos)) return new Pos(line, ch);
  958. this.line = line; this.ch = ch;
  959. };
  960. // Compare two positions, return 0 if they are the same, a negative
  961. // number when a is less, and a positive number otherwise.
  962. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  963. function copyPos(x) {return Pos(x.line, x.ch);}
  964. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  965. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  966. // INPUT HANDLING
  967. function ensureFocus(cm) {
  968. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  969. }
  970. // This will be set to an array of strings when copying, so that,
  971. // when pasting, we know what kind of selections the copied text
  972. // was made out of.
  973. var lastCopied = null;
  974. function applyTextInput(cm, inserted, deleted, sel, origin) {
  975. var doc = cm.doc;
  976. cm.display.shift = false;
  977. if (!sel) sel = doc.sel;
  978. var paste = cm.state.pasteIncoming || origin == "paste";
  979. var textLines = doc.splitLines(inserted), multiPaste = null;
  980. // When pasing N lines into N selections, insert one line per selection
  981. if (paste && sel.ranges.length > 1) {
  982. if (lastCopied && lastCopied.join("\n") == inserted) {
  983. if (sel.ranges.length % lastCopied.length == 0) {
  984. multiPaste = [];
  985. for (var i = 0; i < lastCopied.length; i++)
  986. multiPaste.push(doc.splitLines(lastCopied[i]));
  987. }
  988. } else if (textLines.length == sel.ranges.length) {
  989. multiPaste = map(textLines, function(l) { return [l]; });
  990. }
  991. }
  992. // Normal behavior is to insert the new text into every selection
  993. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  994. var range = sel.ranges[i];
  995. var from = range.from(), to = range.to();
  996. if (range.empty()) {
  997. if (deleted && deleted > 0) // Handle deletion
  998. from = Pos(from.line, from.ch - deleted);
  999. else if (cm.state.overwrite && !paste) // Handle overwrite
  1000. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  1001. }
  1002. var updateInput = cm.curOp.updateInput;
  1003. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  1004. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  1005. makeChange(cm.doc, changeEvent);
  1006. signalLater(cm, "inputRead", cm, changeEvent);
  1007. }
  1008. if (inserted && !paste)
  1009. triggerElectric(cm, inserted);
  1010. ensureCursorVisible(cm);
  1011. cm.curOp.updateInput = updateInput;
  1012. cm.curOp.typing = true;
  1013. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  1014. }
  1015. function handlePaste(e, cm) {
  1016. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1017. if (pasted) {
  1018. e.preventDefault();
  1019. if (!cm.isReadOnly() && !cm.options.disableInput)
  1020. runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
  1021. return true;
  1022. }
  1023. }
  1024. function triggerElectric(cm, inserted) {
  1025. // When an 'electric' character is inserted, immediately trigger a reindent
  1026. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  1027. var sel = cm.doc.sel;
  1028. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  1029. var range = sel.ranges[i];
  1030. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  1031. var mode = cm.getModeAt(range.head);
  1032. var indented = false;
  1033. if (mode.electricChars) {
  1034. for (var j = 0; j < mode.electricChars.length; j++)
  1035. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  1036. indented = indentLine(cm, range.head.line, "smart");
  1037. break;
  1038. }
  1039. } else if (mode.electricInput) {
  1040. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  1041. indented = indentLine(cm, range.head.line, "smart");
  1042. }
  1043. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  1044. }
  1045. }
  1046. function copyableRanges(cm) {
  1047. var text = [], ranges = [];
  1048. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1049. var line = cm.doc.sel.ranges[i].head.line;
  1050. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  1051. ranges.push(lineRange);
  1052. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1053. }
  1054. return {text: text, ranges: ranges};
  1055. }
  1056. function disableBrowserMagic(field) {
  1057. field.setAttribute("autocorrect", "off");
  1058. field.setAttribute("autocapitalize", "off");
  1059. field.setAttribute("spellcheck", "false");
  1060. }
  1061. // TEXTAREA INPUT STYLE
  1062. function TextareaInput(cm) {
  1063. this.cm = cm;
  1064. // See input.poll and input.reset
  1065. this.prevInput = "";
  1066. // Flag that indicates whether we expect input to appear real soon
  1067. // now (after some event like 'keypress' or 'input') and are
  1068. // polling intensively.
  1069. this.pollingFast = false;
  1070. // Self-resetting timeout for the poller
  1071. this.polling = new Delayed();
  1072. // Tracks when input.reset has punted to just putting a short
  1073. // string into the textarea instead of the full selection.
  1074. this.inaccurateSelection = false;
  1075. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1076. this.hasSelection = false;
  1077. this.composing = null;
  1078. };
  1079. function hiddenTextarea() {
  1080. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  1081. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1082. // The textarea is kept positioned near the cursor to prevent the
  1083. // fact that it'll be scrolled into view on input from scrolling
  1084. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1085. // very slow. So make the area wide instead.
  1086. if (webkit) te.style.width = "1000px";
  1087. else te.setAttribute("wrap", "off");
  1088. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1089. if (ios) te.style.border = "1px solid black";
  1090. disableBrowserMagic(te);
  1091. return div;
  1092. }
  1093. TextareaInput.prototype = copyObj({
  1094. init: function(display) {
  1095. var input = this, cm = this.cm;
  1096. // Wraps and hides input textarea
  1097. var div = this.wrapper = hiddenTextarea();
  1098. // The semihidden textarea that is focused when the editor is
  1099. // focused, and receives input.
  1100. var te = this.textarea = div.firstChild;
  1101. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1102. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1103. if (ios) te.style.width = "0px";
  1104. on(te, "input", function() {
  1105. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1106. input.poll();
  1107. });
  1108. on(te, "paste", function(e) {
  1109. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  1110. cm.state.pasteIncoming = true;
  1111. input.fastPoll();
  1112. });
  1113. function prepareCopyCut(e) {
  1114. if (signalDOMEvent(cm, e)) return
  1115. if (cm.somethingSelected()) {
  1116. lastCopied = cm.getSelections();
  1117. if (input.inaccurateSelection) {
  1118. input.prevInput = "";
  1119. input.inaccurateSelection = false;
  1120. te.value = lastCopied.join("\n");
  1121. selectInput(te);
  1122. }
  1123. } else if (!cm.options.lineWiseCopyCut) {
  1124. return;
  1125. } else {
  1126. var ranges = copyableRanges(cm);
  1127. lastCopied = ranges.text;
  1128. if (e.type == "cut") {
  1129. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1130. } else {
  1131. input.prevInput = "";
  1132. te.value = ranges.text.join("\n");
  1133. selectInput(te);
  1134. }
  1135. }
  1136. if (e.type == "cut") cm.state.cutIncoming = true;
  1137. }
  1138. on(te, "cut", prepareCopyCut);
  1139. on(te, "copy", prepareCopyCut);
  1140. on(display.scroller, "paste", function(e) {
  1141. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
  1142. cm.state.pasteIncoming = true;
  1143. input.focus();
  1144. });
  1145. // Prevent normal selection in the editor (we handle our own)
  1146. on(display.lineSpace, "selectstart", function(e) {
  1147. if (!eventInWidget(display, e)) e_preventDefault(e);
  1148. });
  1149. on(te, "compositionstart", function() {
  1150. var start = cm.getCursor("from");
  1151. if (input.composing) input.composing.range.clear()
  1152. input.composing = {
  1153. start: start,
  1154. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  1155. };
  1156. });
  1157. on(te, "compositionend", function() {
  1158. if (input.composing) {
  1159. input.poll();
  1160. input.composing.range.clear();
  1161. input.composing = null;
  1162. }
  1163. });
  1164. },
  1165. prepareSelection: function() {
  1166. // Redraw the selection and/or cursor
  1167. var cm = this.cm, display = cm.display, doc = cm.doc;
  1168. var result = prepareSelection(cm);
  1169. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1170. if (cm.options.moveInputWithCursor) {
  1171. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1172. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1173. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1174. headPos.top + lineOff.top - wrapOff.top));
  1175. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1176. headPos.left + lineOff.left - wrapOff.left));
  1177. }
  1178. return result;
  1179. },
  1180. showSelection: function(drawn) {
  1181. var cm = this.cm, display = cm.display;
  1182. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1183. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1184. if (drawn.teTop != null) {
  1185. this.wrapper.style.top = drawn.teTop + "px";
  1186. this.wrapper.style.left = drawn.teLeft + "px";
  1187. }
  1188. },
  1189. // Reset the input to correspond to the selection (or to be empty,
  1190. // when not typing and nothing is selected)
  1191. reset: function(typing) {
  1192. if (this.contextMenuPending) return;
  1193. var minimal, selected, cm = this.cm, doc = cm.doc;
  1194. if (cm.somethingSelected()) {
  1195. this.prevInput = "";
  1196. var range = doc.sel.primary();
  1197. minimal = hasCopyEvent &&
  1198. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1199. var content = minimal ? "-" : selected || cm.getSelection();
  1200. this.textarea.value = content;
  1201. if (cm.state.focused) selectInput(this.textarea);
  1202. if (ie && ie_version >= 9) this.hasSelection = content;
  1203. } else if (!typing) {
  1204. this.prevInput = this.textarea.value = "";
  1205. if (ie && ie_version >= 9) this.hasSelection = null;
  1206. }
  1207. this.inaccurateSelection = minimal;
  1208. },
  1209. getField: function() { return this.textarea; },
  1210. supportsTouch: function() { return false; },
  1211. focus: function() {
  1212. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1213. try { this.textarea.focus(); }
  1214. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  1215. }
  1216. },
  1217. blur: function() { this.textarea.blur(); },
  1218. resetPosition: function() {
  1219. this.wrapper.style.top = this.wrapper.style.left = 0;
  1220. },
  1221. receivedFocus: function() { this.slowPoll(); },
  1222. // Poll for input changes, using the normal rate of polling. This
  1223. // runs as long as the editor is focused.
  1224. slowPoll: function() {
  1225. var input = this;
  1226. if (input.pollingFast) return;
  1227. input.polling.set(this.cm.options.pollInterval, function() {
  1228. input.poll();
  1229. if (input.cm.state.focused) input.slowPoll();
  1230. });
  1231. },
  1232. // When an event has just come in that is likely to add or change
  1233. // something in the input textarea, we poll faster, to ensure that
  1234. // the change appears on the screen quickly.
  1235. fastPoll: function() {
  1236. var missed = false, input = this;
  1237. input.pollingFast = true;
  1238. function p() {
  1239. var changed = input.poll();
  1240. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  1241. else {input.pollingFast = false; input.slowPoll();}
  1242. }
  1243. input.polling.set(20, p);
  1244. },
  1245. // Read input from the textarea, and update the document to match.
  1246. // When something is selected, it is present in the textarea, and
  1247. // selected (unless it is huge, in which case a placeholder is
  1248. // used). When nothing is selected, the cursor sits after previously
  1249. // seen text (can be empty), which is stored in prevInput (we must
  1250. // not reset the textarea when typing, because that breaks IME).
  1251. poll: function() {
  1252. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1253. // Since this is called a *lot*, try to bail out as cheaply as
  1254. // possible when it is clear that nothing happened. hasSelection
  1255. // will be the case when there is a lot of text in the textarea,
  1256. // in which case reading its value would be expensive.
  1257. if (this.contextMenuPending || !cm.state.focused ||
  1258. (hasSelection(input) && !prevInput && !this.composing) ||
  1259. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  1260. return false;
  1261. var text = input.value;
  1262. // If nothing changed, bail.
  1263. if (text == prevInput && !cm.somethingSelected()) return false;
  1264. // Work around nonsensical selection resetting in IE9/10, and
  1265. // inexplicable appearance of private area unicode characters on
  1266. // some key combos in Mac (#2689).
  1267. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1268. mac && /[\uf700-\uf7ff]/.test(text)) {
  1269. cm.display.input.reset();
  1270. return false;
  1271. }
  1272. if (cm.doc.sel == cm.display.selForContextMenu) {
  1273. var first = text.charCodeAt(0);
  1274. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  1275. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  1276. }
  1277. // Find the part of the input that is actually new
  1278. var same = 0, l = Math.min(prevInput.length, text.length);
  1279. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1280. var self = this;
  1281. runInOp(cm, function() {
  1282. applyTextInput(cm, text.slice(same), prevInput.length - same,
  1283. null, self.composing ? "*compose" : null);
  1284. // Don't leave long text in the textarea, since it makes further polling slow
  1285. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1286. else self.prevInput = text;
  1287. if (self.composing) {
  1288. self.composing.range.clear();
  1289. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  1290. {className: "CodeMirror-composing"});
  1291. }
  1292. });
  1293. return true;
  1294. },
  1295. ensurePolled: function() {
  1296. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1297. },
  1298. onKeyPress: function() {
  1299. if (ie && ie_version >= 9) this.hasSelection = null;
  1300. this.fastPoll();
  1301. },
  1302. onContextMenu: function(e) {
  1303. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1304. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1305. if (!pos || presto) return; // Opera is difficult.
  1306. // Reset the current text selection only if the click is done outside of the selection
  1307. // and 'resetSelectionOnContextMenu' option is true.
  1308. var reset = cm.options.resetSelectionOnContextMenu;
  1309. if (reset && cm.doc.sel.contains(pos) == -1)
  1310. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1311. var oldCSS = te.style.cssText;
  1312. input.wrapper.style.position = "absolute";
  1313. te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1314. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
  1315. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1316. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1317. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1318. display.input.focus();
  1319. if (webkit) window.scrollTo(null, oldScrollY);
  1320. display.input.reset();
  1321. // Adds "Select all" to context menu in FF
  1322. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1323. input.contextMenuPending = true;
  1324. display.selForContextMenu = cm.doc.sel;
  1325. clearTimeout(display.detectingSelectAll);
  1326. // Select-all will be greyed out if there's nothing to select, so
  1327. // this adds a zero-width space so that we can later check whether
  1328. // it got selected.
  1329. function prepareSelectAllHack() {
  1330. if (te.selectionStart != null) {
  1331. var selected = cm.somethingSelected();
  1332. var extval = "\u200b" + (selected ? te.value : "");
  1333. te.value = "\u21da"; // Used to catch context-menu undo
  1334. te.value = extval;
  1335. input.prevInput = selected ? "" : "\u200b";
  1336. te.selectionStart = 1; te.selectionEnd = extval.length;
  1337. // Re-set this, in case some other handler touched the
  1338. // selection in the meantime.
  1339. display.selForContextMenu = cm.doc.sel;
  1340. }
  1341. }
  1342. function rehide() {
  1343. input.contextMenuPending = false;
  1344. input.wrapper.style.position = "relative";
  1345. te.style.cssText = oldCSS;
  1346. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1347. // Try to detect the user choosing select-all
  1348. if (te.selectionStart != null) {
  1349. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1350. var i = 0, poll = function() {
  1351. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  1352. te.selectionEnd > 0 && input.prevInput == "\u200b")
  1353. operation(cm, commands.selectAll)(cm);
  1354. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1355. else display.input.reset();
  1356. };
  1357. display.detectingSelectAll = setTimeout(poll, 200);
  1358. }
  1359. }
  1360. if (ie && ie_version >= 9) prepareSelectAllHack();
  1361. if (captureRightClick) {
  1362. e_stop(e);
  1363. var mouseup = function() {
  1364. off(window, "mouseup", mouseup);
  1365. setTimeout(rehide, 20);
  1366. };
  1367. on(window, "mouseup", mouseup);
  1368. } else {
  1369. setTimeout(rehide, 50);
  1370. }
  1371. },
  1372. readOnlyChanged: function(val) {
  1373. if (!val) this.reset();
  1374. },
  1375. setUneditable: nothing,
  1376. needsContentAttribute: false
  1377. }, TextareaInput.prototype);
  1378. // CONTENTEDITABLE INPUT STYLE
  1379. function ContentEditableInput(cm) {
  1380. this.cm = cm;
  1381. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1382. this.polling = new Delayed();
  1383. this.gracePeriod = false;
  1384. }
  1385. ContentEditableInput.prototype = copyObj({
  1386. init: function(display) {
  1387. var input = this, cm = input.cm;
  1388. var div = input.div = display.lineDiv;
  1389. disableBrowserMagic(div);
  1390. on(div, "paste", function(e) {
  1391. if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
  1392. })
  1393. on(div, "compositionstart", function(e) {
  1394. var data = e.data;
  1395. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  1396. if (!data) return;
  1397. var prim = cm.doc.sel.primary();
  1398. var line = cm.getLine(prim.head.line);
  1399. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1400. if (found > -1 && found <= prim.head.ch)
  1401. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1402. Pos(prim.head.line, found + data.length));
  1403. });
  1404. on(div, "compositionupdate", function(e) {
  1405. input.composing.data = e.data;
  1406. });
  1407. on(div, "compositionend", function(e) {
  1408. var ours = input.composing;
  1409. if (!ours) return;
  1410. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1411. ours.data = e.data;
  1412. // Need a small delay to prevent other code (input event,
  1413. // selection polling) from doing damage when fired right after
  1414. // compositionend.
  1415. setTimeout(function() {
  1416. if (!ours.handled)
  1417. input.applyComposition(ours);
  1418. if (input.composing == ours)
  1419. input.composing = null;
  1420. }, 50);
  1421. });
  1422. on(div, "touchstart", function() {
  1423. input.forceCompositionEnd();
  1424. });
  1425. on(div, "input", function() {
  1426. if (input.composing) return;
  1427. if (cm.isReadOnly() || !input.pollContent())
  1428. runInOp(input.cm, function() {regChange(cm);});
  1429. });
  1430. function onCopyCut(e) {
  1431. if (signalDOMEvent(cm, e)) return
  1432. if (cm.somethingSelected()) {
  1433. lastCopied = cm.getSelections();
  1434. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1435. } else if (!cm.options.lineWiseCopyCut) {
  1436. return;
  1437. } else {
  1438. var ranges = copyableRanges(cm);
  1439. lastCopied = ranges.text;
  1440. if (e.type == "cut") {
  1441. cm.operation(function() {
  1442. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1443. cm.replaceSelection("", null, "cut");
  1444. });
  1445. }
  1446. }
  1447. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1448. if (e.clipboardData && !ios) {
  1449. e.preventDefault();
  1450. e.clipboardData.clearData();
  1451. e.clipboardData.setData("text/plain", lastCopied.join("\n"));
  1452. } else {
  1453. // Old-fashioned briefly-focus-a-textarea hack
  1454. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1455. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1456. te.value = lastCopied.join("\n");
  1457. var hadFocus = document.activeElement;
  1458. selectInput(te);
  1459. setTimeout(function() {
  1460. cm.display.lineSpace.removeChild(kludge);
  1461. hadFocus.focus();
  1462. }, 50);
  1463. }
  1464. }
  1465. on(div, "copy", onCopyCut);
  1466. on(div, "cut", onCopyCut);
  1467. },
  1468. prepareSelection: function() {
  1469. var result = prepareSelection(this.cm, false);
  1470. result.focus = this.cm.state.focused;
  1471. return result;
  1472. },
  1473. showSelection: function(info) {
  1474. if (!info || !this.cm.display.view.length) return;
  1475. if (info.focus) this.showPrimarySelection();
  1476. this.showMultipleSelections(info);
  1477. },
  1478. showPrimarySelection: function() {
  1479. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1480. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1481. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1482. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1483. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1484. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1485. return;
  1486. var start = posToDOM(this.cm, prim.from());
  1487. var end = posToDOM(this.cm, prim.to());
  1488. if (!start && !end) return;
  1489. var view = this.cm.display.view;
  1490. var old = sel.rangeCount && sel.getRangeAt(0);
  1491. if (!start) {
  1492. start = {node: view[0].measure.map[2], offset: 0};
  1493. } else if (!end) { // FIXME dangerously hacky
  1494. var measure = view[view.length - 1].measure;
  1495. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1496. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  1497. }
  1498. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1499. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1500. if (rng) {
  1501. if (!gecko && this.cm.state.focused) {
  1502. sel.collapse(start.node, start.offset);
  1503. if (!rng.collapsed) sel.addRange(rng);
  1504. } else {
  1505. sel.removeAllRanges();
  1506. sel.addRange(rng);
  1507. }
  1508. if (old && sel.anchorNode == null) sel.addRange(old);
  1509. else if (gecko) this.startGracePeriod();
  1510. }
  1511. this.rememberSelection();
  1512. },
  1513. startGracePeriod: function() {
  1514. var input = this;
  1515. clearTimeout(this.gracePeriod);
  1516. this.gracePeriod = setTimeout(function() {
  1517. input.gracePeriod = false;
  1518. if (input.selectionChanged())
  1519. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  1520. }, 20);
  1521. },
  1522. showMultipleSelections: function(info) {
  1523. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1524. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1525. },
  1526. rememberSelection: function() {
  1527. var sel = window.getSelection();
  1528. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1529. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1530. },
  1531. selectionInEditor: function() {
  1532. var sel = window.getSelection();
  1533. if (!sel.rangeCount) return false;
  1534. var node = sel.getRangeAt(0).commonAncestorContainer;
  1535. return contains(this.div, node);
  1536. },
  1537. focus: function() {
  1538. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1539. },
  1540. blur: function() { this.div.blur(); },
  1541. getField: function() { return this.div; },
  1542. supportsTouch: function() { return true; },
  1543. receivedFocus: function() {
  1544. var input = this;
  1545. if (this.selectionInEditor())
  1546. this.pollSelection();
  1547. else
  1548. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  1549. function poll() {
  1550. if (input.cm.state.focused) {
  1551. input.pollSelection();
  1552. input.polling.set(input.cm.options.pollInterval, poll);
  1553. }
  1554. }
  1555. this.polling.set(this.cm.options.pollInterval, poll);
  1556. },
  1557. selectionChanged: function() {
  1558. var sel = window.getSelection();
  1559. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1560. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  1561. },
  1562. pollSelection: function() {
  1563. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  1564. var sel = window.getSelection(), cm = this.cm;
  1565. this.rememberSelection();
  1566. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1567. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1568. if (anchor && head) runInOp(cm, function() {
  1569. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1570. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1571. });
  1572. }
  1573. },
  1574. pollContent: function() {
  1575. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1576. var from = sel.from(), to = sel.to();
  1577. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1578. var fromIndex;
  1579. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1580. var fromLine = lineNo(display.view[0].line);
  1581. var fromNode = display.view[0].node;
  1582. } else {
  1583. var fromLine = lineNo(display.view[fromIndex].line);
  1584. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1585. }
  1586. var toIndex = findViewIndex(cm, to.line);
  1587. if (toIndex == display.view.length - 1) {
  1588. var toLine = display.viewTo - 1;
  1589. var toNode = display.lineDiv.lastChild;
  1590. } else {
  1591. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1592. var toNode = display.view[toIndex + 1].node.previousSibling;
  1593. }
  1594. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1595. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1596. while (newText.length > 1 && oldText.length > 1) {
  1597. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1598. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1599. else break;
  1600. }
  1601. var cutFront = 0, cutEnd = 0;
  1602. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1603. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1604. ++cutFront;
  1605. var newBot = lst(newText), oldBot = lst(oldText);
  1606. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1607. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1608. while (cutEnd < maxCutEnd &&
  1609. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1610. ++cutEnd;
  1611. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1612. newText[0] = newText[0].slice(cutFront);
  1613. var chFrom = Pos(fromLine, cutFront);
  1614. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1615. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1616. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1617. return true;
  1618. }
  1619. },
  1620. ensurePolled: function() {
  1621. this.forceCompositionEnd();
  1622. },
  1623. reset: function() {
  1624. this.forceCompositionEnd();
  1625. },
  1626. forceCompositionEnd: function() {
  1627. if (!this.composing || this.composing.handled) return;
  1628. this.applyComposition(this.composing);
  1629. this.composing.handled = true;
  1630. this.div.blur();
  1631. this.div.focus();
  1632. },
  1633. applyComposition: function(composing) {
  1634. if (this.cm.isReadOnly())
  1635. operation(this.cm, regChange)(this.cm)
  1636. else if (composing.data && composing.data != composing.startData)
  1637. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1638. },
  1639. setUneditable: function(node) {
  1640. node.contentEditable = "false"
  1641. },
  1642. onKeyPress: function(e) {
  1643. e.preventDefault();
  1644. if (!this.cm.isReadOnly())
  1645. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1646. },
  1647. readOnlyChanged: function(val) {
  1648. this.div.contentEditable = String(val != "nocursor")
  1649. },
  1650. onContextMenu: nothing,
  1651. resetPosition: nothing,
  1652. needsContentAttribute: true
  1653. }, ContentEditableInput.prototype);
  1654. function posToDOM(cm, pos) {
  1655. var view = findViewForLine(cm, pos.line);
  1656. if (!view || view.hidden) return null;
  1657. var line = getLine(cm.doc, pos.line);
  1658. var info = mapFromLineView(view, line, pos.line);
  1659. var order = getOrder(line), side = "left";
  1660. if (order) {
  1661. var partPos = getBidiPartAt(order, pos.ch);
  1662. side = partPos % 2 ? "right" : "left";
  1663. }
  1664. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  1665. result.offset = result.collapse == "right" ? result.end : result.start;
  1666. return result;
  1667. }
  1668. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1669. function domToPos(cm, node, offset) {
  1670. var lineNode;
  1671. if (node == cm.display.lineDiv) {
  1672. lineNode = cm.display.lineDiv.childNodes[offset];
  1673. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1674. node = null; offset = 0;
  1675. } else {
  1676. for (lineNode = node;; lineNode = lineNode.parentNode) {
  1677. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1678. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1679. }
  1680. }
  1681. for (var i = 0; i < cm.display.view.length; i++) {
  1682. var lineView = cm.display.view[i];
  1683. if (lineView.node == lineNode)
  1684. return locateNodeInLineView(lineView, node, offset);
  1685. }
  1686. }
  1687. function locateNodeInLineView(lineView, node, offset) {
  1688. var wrapper = lineView.text.firstChild, bad = false;
  1689. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1690. if (node == wrapper) {
  1691. bad = true;
  1692. node = wrapper.childNodes[offset];
  1693. offset = 0;
  1694. if (!node) {
  1695. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1696. return badPos(Pos(lineNo(line), line.text.length), bad);
  1697. }
  1698. }
  1699. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1700. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1701. textNode = node.firstChild;
  1702. if (offset) offset = textNode.nodeValue.length;
  1703. }
  1704. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1705. var measure = lineView.measure, maps = measure.maps;
  1706. function find(textNode, topNode, offset) {
  1707. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1708. var map = i < 0 ? measure.map : maps[i];
  1709. for (var j = 0; j < map.length; j += 3) {
  1710. var curNode = map[j + 2];
  1711. if (curNode == textNode || curNode == topNode) {
  1712. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1713. var ch = map[j] + offset;
  1714. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1715. return Pos(line, ch);
  1716. }
  1717. }
  1718. }
  1719. }
  1720. var found = find(textNode, topNode, offset);
  1721. if (found) return badPos(found, bad);
  1722. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1723. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1724. found = find(after, after.firstChild, 0);
  1725. if (found)
  1726. return badPos(Pos(found.line, found.ch - dist), bad);
  1727. else
  1728. dist += after.textContent.length;
  1729. }
  1730. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1731. found = find(before, before.firstChild, -1);
  1732. if (found)
  1733. return badPos(Pos(found.line, found.ch + dist), bad);
  1734. else
  1735. dist += after.textContent.length;
  1736. }
  1737. }
  1738. function domTextBetween(cm, from, to, fromLine, toLine) {
  1739. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  1740. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  1741. function walk(node) {
  1742. if (node.nodeType == 1) {
  1743. var cmText = node.getAttribute("cm-text");
  1744. if (cmText != null) {
  1745. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1746. text += cmText;
  1747. return;
  1748. }
  1749. var markerID = node.getAttribute("cm-marker"), range;
  1750. if (markerID) {
  1751. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1752. if (found.length && (range = found[0].find()))
  1753. text += getBetween(cm.doc, range.from, range.to).join(lineSep);
  1754. return;
  1755. }
  1756. if (node.getAttribute("contenteditable") == "false") return;
  1757. for (var i = 0; i < node.childNodes.length; i++)
  1758. walk(node.childNodes[i]);
  1759. if (/^(pre|div|p)$/i.test(node.nodeName))
  1760. closing = true;
  1761. } else if (node.nodeType == 3) {
  1762. var val = node.nodeValue;
  1763. if (!val) return;
  1764. if (closing) {
  1765. text += lineSep;
  1766. closing = false;
  1767. }
  1768. text += val;
  1769. }
  1770. }
  1771. for (;;) {
  1772. walk(from);
  1773. if (from == to) break;
  1774. from = from.nextSibling;
  1775. }
  1776. return text;
  1777. }
  1778. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  1779. // SELECTION / CURSOR
  1780. // Selection objects are immutable. A new one is created every time
  1781. // the selection changes. A selection is one or more non-overlapping
  1782. // (and non-touching) ranges, sorted, and an integer that indicates
  1783. // which one is the primary selection (the one that's scrolled into
  1784. // view, that getCursor returns, etc).
  1785. function Selection(ranges, primIndex) {
  1786. this.ranges = ranges;
  1787. this.primIndex = primIndex;
  1788. }
  1789. Selection.prototype = {
  1790. primary: function() { return this.ranges[this.primIndex]; },
  1791. equals: function(other) {
  1792. if (other == this) return true;
  1793. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1794. for (var i = 0; i < this.ranges.length; i++) {
  1795. var here = this.ranges[i], there = other.ranges[i];
  1796. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1797. }
  1798. return true;
  1799. },
  1800. deepCopy: function() {
  1801. for (var out = [], i = 0; i < this.ranges.length; i++)
  1802. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1803. return new Selection(out, this.primIndex);
  1804. },
  1805. somethingSelected: function() {
  1806. for (var i = 0; i < this.ranges.length; i++)
  1807. if (!this.ranges[i].empty()) return true;
  1808. return false;
  1809. },
  1810. contains: function(pos, end) {
  1811. if (!end) end = pos;
  1812. for (var i = 0; i < this.ranges.length; i++) {
  1813. var range = this.ranges[i];
  1814. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1815. return i;
  1816. }
  1817. return -1;
  1818. }
  1819. };
  1820. function Range(anchor, head) {
  1821. this.anchor = anchor; this.head = head;
  1822. }
  1823. Range.prototype = {
  1824. from: function() { return minPos(this.anchor, this.head); },
  1825. to: function() { return maxPos(this.anchor, this.head); },
  1826. empty: function() {
  1827. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1828. }
  1829. };
  1830. // Take an unsorted, potentially overlapping set of ranges, and
  1831. // build a selection out of it. 'Consumes' ranges array (modifying
  1832. // it).
  1833. function normalizeSelection(ranges, primIndex) {
  1834. var prim = ranges[primIndex];
  1835. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1836. primIndex = indexOf(ranges, prim);
  1837. for (var i = 1; i < ranges.length; i++) {
  1838. var cur = ranges[i], prev = ranges[i - 1];
  1839. if (cmp(prev.to(), cur.from()) >= 0) {
  1840. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1841. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1842. if (i <= primIndex) --primIndex;
  1843. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1844. }
  1845. }
  1846. return new Selection(ranges, primIndex);
  1847. }
  1848. function simpleSelection(anchor, head) {
  1849. return new Selection([new Range(anchor, head || anchor)], 0);
  1850. }
  1851. // Most of the external API clips given positions to make sure they
  1852. // actually exist within the document.
  1853. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1854. function clipPos(doc, pos) {
  1855. if (pos.line < doc.first) return Pos(doc.first, 0);
  1856. var last = doc.first + doc.size - 1;
  1857. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1858. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1859. }
  1860. function clipToLen(pos, linelen) {
  1861. var ch = pos.ch;
  1862. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1863. else if (ch < 0) return Pos(pos.line, 0);
  1864. else return pos;
  1865. }
  1866. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1867. function clipPosArray(doc, array) {
  1868. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1869. return out;
  1870. }
  1871. // SELECTION UPDATES
  1872. // The 'scroll' parameter given to many of these indicated whether
  1873. // the new cursor position should be scrolled into view after
  1874. // modifying the selection.
  1875. // If shift is held or the extend flag is set, extends a range to
  1876. // include a given position (and optionally a second position).
  1877. // Otherwise, simply returns the range between the given positions.
  1878. // Used for cursor motion and such.
  1879. function extendRange(doc, range, head, other) {
  1880. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1881. var anchor = range.anchor;
  1882. if (other) {
  1883. var posBefore = cmp(head, anchor) < 0;
  1884. if (posBefore != (cmp(other, anchor) < 0)) {
  1885. anchor = head;
  1886. head = other;
  1887. } else if (posBefore != (cmp(head, other) < 0)) {
  1888. head = other;
  1889. }
  1890. }
  1891. return new Range(anchor, head);
  1892. } else {
  1893. return new Range(other || head, head);
  1894. }
  1895. }
  1896. // Extend the primary selection range, discard the rest.
  1897. function extendSelection(doc, head, other, options) {
  1898. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1899. }
  1900. // Extend all selections (pos is an array of selections with length
  1901. // equal the number of selections)
  1902. function extendSelections(doc, heads, options) {
  1903. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1904. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1905. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1906. setSelection(doc, newSel, options);
  1907. }
  1908. // Updates a single range in the selection.
  1909. function replaceOneSelection(doc, i, range, options) {
  1910. var ranges = doc.sel.ranges.slice(0);
  1911. ranges[i] = range;
  1912. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1913. }
  1914. // Reset the selection to a single range.
  1915. function setSimpleSelection(doc, anchor, head, options) {
  1916. setSelection(doc, simpleSelection(anchor, head), options);
  1917. }
  1918. // Give beforeSelectionChange handlers a change to influence a
  1919. // selection update.
  1920. function filterSelectionChange(doc, sel, options) {
  1921. var obj = {
  1922. ranges: sel.ranges,
  1923. update: function(ranges) {
  1924. this.ranges = [];
  1925. for (var i = 0; i < ranges.length; i++)
  1926. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1927. clipPos(doc, ranges[i].head));
  1928. },
  1929. origin: options && options.origin
  1930. };
  1931. signal(doc, "beforeSelectionChange", doc, obj);
  1932. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1933. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1934. else return sel;
  1935. }
  1936. function setSelectionReplaceHistory(doc, sel, options) {
  1937. var done = doc.history.done, last = lst(done);
  1938. if (last && last.ranges) {
  1939. done[done.length - 1] = sel;
  1940. setSelectionNoUndo(doc, sel, options);
  1941. } else {
  1942. setSelection(doc, sel, options);
  1943. }
  1944. }
  1945. // Set a new selection.
  1946. function setSelection(doc, sel, options) {
  1947. setSelectionNoUndo(doc, sel, options);
  1948. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1949. }
  1950. function setSelectionNoUndo(doc, sel, options) {
  1951. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1952. sel = filterSelectionChange(doc, sel, options);
  1953. var bias = options && options.bias ||
  1954. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1955. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1956. if (!(options && options.scroll === false) && doc.cm)
  1957. ensureCursorVisible(doc.cm);
  1958. }
  1959. function setSelectionInner(doc, sel) {
  1960. if (sel.equals(doc.sel)) return;
  1961. doc.sel = sel;
  1962. if (doc.cm) {
  1963. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1964. signalCursorActivity(doc.cm);
  1965. }
  1966. signalLater(doc, "cursorActivity", doc);
  1967. }
  1968. // Verify that the selection does not partially select any atomic
  1969. // marked ranges.
  1970. function reCheckSelection(doc) {
  1971. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1972. }
  1973. // Return a selection that does not partially select any atomic
  1974. // ranges.
  1975. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1976. var out;
  1977. for (var i = 0; i < sel.ranges.length; i++) {
  1978. var range = sel.ranges[i];
  1979. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  1980. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  1981. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  1982. if (out || newAnchor != range.anchor || newHead != range.head) {
  1983. if (!out) out = sel.ranges.slice(0, i);
  1984. out[i] = new Range(newAnchor, newHead);
  1985. }
  1986. }
  1987. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1988. }
  1989. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  1990. var line = getLine(doc, pos.line);
  1991. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  1992. var sp = line.markedSpans[i], m = sp.marker;
  1993. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  1994. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  1995. if (mayClear) {
  1996. signal(m, "beforeCursorEnter");
  1997. if (m.explicitlyCleared) {
  1998. if (!line.markedSpans) break;
  1999. else {--i; continue;}
  2000. }
  2001. }
  2002. if (!m.atomic) continue;
  2003. if (oldPos) {
  2004. var near = m.find(dir < 0 ? 1 : -1), diff;
  2005. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) near = movePos(doc, near, -dir, line);
  2006. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  2007. return skipAtomicInner(doc, near, pos, dir, mayClear);
  2008. }
  2009. var far = m.find(dir < 0 ? -1 : 1);
  2010. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) far = movePos(doc, far, dir, line);
  2011. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
  2012. }
  2013. }
  2014. return pos;
  2015. }
  2016. // Ensure a given position is not inside an atomic range.
  2017. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  2018. var dir = bias || 1;
  2019. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  2020. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  2021. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  2022. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  2023. if (!found) {
  2024. doc.cantEdit = true;
  2025. return Pos(doc.first, 0);
  2026. }
  2027. return found;
  2028. }
  2029. function movePos(doc, pos, dir, line) {
  2030. if (dir < 0 && pos.ch == 0) {
  2031. if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
  2032. else return null;
  2033. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  2034. if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
  2035. else return null;
  2036. } else {
  2037. return new Pos(pos.line, pos.ch + dir);
  2038. }
  2039. }
  2040. // SELECTION DRAWING
  2041. function updateSelection(cm) {
  2042. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2043. }
  2044. function prepareSelection(cm, primary) {
  2045. var doc = cm.doc, result = {};
  2046. var curFragment = result.cursors = document.createDocumentFragment();
  2047. var selFragment = result.selection = document.createDocumentFragment();
  2048. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2049. if (primary === false && i == doc.sel.primIndex) continue;
  2050. var range = doc.sel.ranges[i];
  2051. var collapsed = range.empty();
  2052. if (collapsed || cm.options.showCursorWhenSelecting)
  2053. drawSelectionCursor(cm, range.head, curFragment);
  2054. if (!collapsed)
  2055. drawSelectionRange(cm, range, selFragment);
  2056. }
  2057. return result;
  2058. }
  2059. // Draws a cursor for the given range
  2060. function drawSelectionCursor(cm, head, output) {
  2061. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2062. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2063. cursor.style.left = pos.left + "px";
  2064. cursor.style.top = pos.top + "px";
  2065. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2066. if (pos.other) {
  2067. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2068. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2069. otherCursor.style.display = "";
  2070. otherCursor.style.left = pos.other.left + "px";
  2071. otherCursor.style.top = pos.other.top + "px";
  2072. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2073. }
  2074. }
  2075. // Draws the given range as a highlighted selection
  2076. function drawSelectionRange(cm, range, output) {
  2077. var display = cm.display, doc = cm.doc;
  2078. var fragment = document.createDocumentFragment();
  2079. var padding = paddingH(cm.display), leftSide = padding.left;
  2080. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2081. function add(left, top, width, bottom) {
  2082. if (top < 0) top = 0;
  2083. top = Math.round(top);
  2084. bottom = Math.round(bottom);
  2085. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  2086. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  2087. "px; height: " + (bottom - top) + "px"));
  2088. }
  2089. function drawForLine(line, fromArg, toArg) {
  2090. var lineObj = getLine(doc, line);
  2091. var lineLen = lineObj.text.length;
  2092. var start, end;
  2093. function coords(ch, bias) {
  2094. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2095. }
  2096. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  2097. var leftPos = coords(from, "left"), rightPos, left, right;
  2098. if (from == to) {
  2099. rightPos = leftPos;
  2100. left = right = leftPos.left;
  2101. } else {
  2102. rightPos = coords(to - 1, "right");
  2103. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2104. left = leftPos.left;
  2105. right = rightPos.right;
  2106. }
  2107. if (fromArg == null && from == 0) left = leftSide;
  2108. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2109. add(left, leftPos.top, null, leftPos.bottom);
  2110. left = leftSide;
  2111. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2112. }
  2113. if (toArg == null && to == lineLen) right = rightSide;
  2114. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2115. start = leftPos;
  2116. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2117. end = rightPos;
  2118. if (left < leftSide + 1) left = leftSide;
  2119. add(left, rightPos.top, right - left, rightPos.bottom);
  2120. });
  2121. return {start: start, end: end};
  2122. }
  2123. var sFrom = range.from(), sTo = range.to();
  2124. if (sFrom.line == sTo.line) {
  2125. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2126. } else {
  2127. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2128. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2129. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2130. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2131. if (singleVLine) {
  2132. if (leftEnd.top < rightStart.top - 2) {
  2133. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2134. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2135. } else {
  2136. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2137. }
  2138. }
  2139. if (leftEnd.bottom < rightStart.top)
  2140. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2141. }
  2142. output.appendChild(fragment);
  2143. }
  2144. // Cursor-blinking
  2145. function restartBlink(cm) {
  2146. if (!cm.state.focused) return;
  2147. var display = cm.display;
  2148. clearInterval(display.blinker);
  2149. var on = true;
  2150. display.cursorDiv.style.visibility = "";
  2151. if (cm.options.cursorBlinkRate > 0)
  2152. display.blinker = setInterval(function() {
  2153. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2154. }, cm.options.cursorBlinkRate);
  2155. else if (cm.options.cursorBlinkRate < 0)
  2156. display.cursorDiv.style.visibility = "hidden";
  2157. }
  2158. // HIGHLIGHT WORKER
  2159. function startWorker(cm, time) {
  2160. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2161. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2162. }
  2163. function highlightWorker(cm) {
  2164. var doc = cm.doc;
  2165. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2166. if (doc.frontier >= cm.display.viewTo) return;
  2167. var end = +new Date + cm.options.workTime;
  2168. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2169. var changedLines = [];
  2170. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  2171. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2172. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  2173. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  2174. line.styles = highlighted.styles;
  2175. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2176. if (newCls) line.styleClasses = newCls;
  2177. else if (oldCls) line.styleClasses = null;
  2178. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2179. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2180. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2181. if (ischange) changedLines.push(doc.frontier);
  2182. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  2183. } else {
  2184. if (line.text.length <= cm.options.maxHighlightLength)
  2185. processLine(cm, line.text, state);
  2186. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2187. }
  2188. ++doc.frontier;
  2189. if (+new Date > end) {
  2190. startWorker(cm, cm.options.workDelay);
  2191. return true;
  2192. }
  2193. });
  2194. if (changedLines.length) runInOp(cm, function() {
  2195. for (var i = 0; i < changedLines.length; i++)
  2196. regLineChange(cm, changedLines[i], "text");
  2197. });
  2198. }
  2199. // Finds the line to start with when starting a parse. Tries to
  2200. // find a line with a stateAfter, so that it can start with a
  2201. // valid state. If that fails, it returns the line with the
  2202. // smallest indentation, which tends to need the least context to
  2203. // parse correctly.
  2204. function findStartLine(cm, n, precise) {
  2205. var minindent, minline, doc = cm.doc;
  2206. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2207. for (var search = n; search > lim; --search) {
  2208. if (search <= doc.first) return doc.first;
  2209. var line = getLine(doc, search - 1);
  2210. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2211. var indented = countColumn(line.text, null, cm.options.tabSize);
  2212. if (minline == null || minindent > indented) {
  2213. minline = search - 1;
  2214. minindent = indented;
  2215. }
  2216. }
  2217. return minline;
  2218. }
  2219. function getStateBefore(cm, n, precise) {
  2220. var doc = cm.doc, display = cm.display;
  2221. if (!doc.mode.startState) return true;
  2222. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  2223. if (!state) state = startState(doc.mode);
  2224. else state = copyState(doc.mode, state);
  2225. doc.iter(pos, n, function(line) {
  2226. processLine(cm, line.text, state);
  2227. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2228. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2229. ++pos;
  2230. });
  2231. if (precise) doc.frontier = pos;
  2232. return state;
  2233. }
  2234. // POSITION MEASUREMENT
  2235. function paddingTop(display) {return display.lineSpace.offsetTop;}
  2236. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  2237. function paddingH(display) {
  2238. if (display.cachedPaddingH) return display.cachedPaddingH;
  2239. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2240. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2241. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2242. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2243. return data;
  2244. }
  2245. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2246. function displayWidth(cm) {
  2247. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2248. }
  2249. function displayHeight(cm) {
  2250. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2251. }
  2252. // Ensure the lineView.wrapping.heights array is populated. This is
  2253. // an array of bottom offsets for the lines that make up a drawn
  2254. // line. When lineWrapping is on, there might be more than one
  2255. // height.
  2256. function ensureLineHeights(cm, lineView, rect) {
  2257. var wrapping = cm.options.lineWrapping;
  2258. var curWidth = wrapping && displayWidth(cm);
  2259. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2260. var heights = lineView.measure.heights = [];
  2261. if (wrapping) {
  2262. lineView.measure.width = curWidth;
  2263. var rects = lineView.text.firstChild.getClientRects();
  2264. for (var i = 0; i < rects.length - 1; i++) {
  2265. var cur = rects[i], next = rects[i + 1];
  2266. if (Math.abs(cur.bottom - next.bottom) > 2)
  2267. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2268. }
  2269. }
  2270. heights.push(rect.bottom - rect.top);
  2271. }
  2272. }
  2273. // Find a line map (mapping character offsets to text nodes) and a
  2274. // measurement cache for the given line number. (A line view might
  2275. // contain multiple lines when collapsed ranges are present.)
  2276. function mapFromLineView(lineView, line, lineN) {
  2277. if (lineView.line == line)
  2278. return {map: lineView.measure.map, cache: lineView.measure.cache};
  2279. for (var i = 0; i < lineView.rest.length; i++)
  2280. if (lineView.rest[i] == line)
  2281. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  2282. for (var i = 0; i < lineView.rest.length; i++)
  2283. if (lineNo(lineView.rest[i]) > lineN)
  2284. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  2285. }
  2286. // Render a line into the hidden node display.externalMeasured. Used
  2287. // when measurement is needed for a line that's not in the viewport.
  2288. function updateExternalMeasurement(cm, line) {
  2289. line = visualLine(line);
  2290. var lineN = lineNo(line);
  2291. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2292. view.lineN = lineN;
  2293. var built = view.built = buildLineContent(cm, view);
  2294. view.text = built.pre;
  2295. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2296. return view;
  2297. }
  2298. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2299. // for a given character.
  2300. function measureChar(cm, line, ch, bias) {
  2301. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2302. }
  2303. // Find a line view that corresponds to the given line number.
  2304. function findViewForLine(cm, lineN) {
  2305. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2306. return cm.display.view[findViewIndex(cm, lineN)];
  2307. var ext = cm.display.externalMeasured;
  2308. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2309. return ext;
  2310. }
  2311. // Measurement can be split in two steps, the set-up work that
  2312. // applies to the whole line, and the measurement of the actual
  2313. // character. Functions like coordsChar, that need to do a lot of
  2314. // measurements in a row, can thus ensure that the set-up work is
  2315. // only done once.
  2316. function prepareMeasureForLine(cm, line) {
  2317. var lineN = lineNo(line);
  2318. var view = findViewForLine(cm, lineN);
  2319. if (view && !view.text) {
  2320. view = null;
  2321. } else if (view && view.changes) {
  2322. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2323. cm.curOp.forceUpdate = true;
  2324. }
  2325. if (!view)
  2326. view = updateExternalMeasurement(cm, line);
  2327. var info = mapFromLineView(view, line, lineN);
  2328. return {
  2329. line: line, view: view, rect: null,
  2330. map: info.map, cache: info.cache, before: info.before,
  2331. hasHeights: false
  2332. };
  2333. }
  2334. // Given a prepared measurement object, measures the position of an
  2335. // actual character (or fetches it from the cache).
  2336. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2337. if (prepared.before) ch = -1;
  2338. var key = ch + (bias || ""), found;
  2339. if (prepared.cache.hasOwnProperty(key)) {
  2340. found = prepared.cache[key];
  2341. } else {
  2342. if (!prepared.rect)
  2343. prepared.rect = prepared.view.text.getBoundingClientRect();
  2344. if (!prepared.hasHeights) {
  2345. ensureLineHeights(cm, prepared.view, prepared.rect);
  2346. prepared.hasHeights = true;
  2347. }
  2348. found = measureCharInner(cm, prepared, ch, bias);
  2349. if (!found.bogus) prepared.cache[key] = found;
  2350. }
  2351. return {left: found.left, right: found.right,
  2352. top: varHeight ? found.rtop : found.top,
  2353. bottom: varHeight ? found.rbottom : found.bottom};
  2354. }
  2355. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2356. function nodeAndOffsetInLineMap(map, ch, bias) {
  2357. var node, start, end, collapse;
  2358. // First, search the line map for the text node corresponding to,
  2359. // or closest to, the target character.
  2360. for (var i = 0; i < map.length; i += 3) {
  2361. var mStart = map[i], mEnd = map[i + 1];
  2362. if (ch < mStart) {
  2363. start = 0; end = 1;
  2364. collapse = "left";
  2365. } else if (ch < mEnd) {
  2366. start = ch - mStart;
  2367. end = start + 1;
  2368. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2369. end = mEnd - mStart;
  2370. start = end - 1;
  2371. if (ch >= mEnd) collapse = "right";
  2372. }
  2373. if (start != null) {
  2374. node = map[i + 2];
  2375. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2376. collapse = bias;
  2377. if (bias == "left" && start == 0)
  2378. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2379. node = map[(i -= 3) + 2];
  2380. collapse = "left";
  2381. }
  2382. if (bias == "right" && start == mEnd - mStart)
  2383. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2384. node = map[(i += 3) + 2];
  2385. collapse = "right";
  2386. }
  2387. break;
  2388. }
  2389. }
  2390. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  2391. }
  2392. function measureCharInner(cm, prepared, ch, bias) {
  2393. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2394. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2395. var rect;
  2396. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2397. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2398. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  2399. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  2400. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2401. rect = node.parentNode.getBoundingClientRect();
  2402. } else if (ie && cm.options.lineWrapping) {
  2403. var rects = range(node, start, end).getClientRects();
  2404. if (rects.length)
  2405. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2406. else
  2407. rect = nullRect;
  2408. } else {
  2409. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  2410. }
  2411. if (rect.left || rect.right || start == 0) break;
  2412. end = start;
  2413. start = start - 1;
  2414. collapse = "right";
  2415. }
  2416. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2417. } else { // If it is a widget, simply get the box for the whole widget.
  2418. if (start > 0) collapse = bias = "right";
  2419. var rects;
  2420. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2421. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2422. else
  2423. rect = node.getBoundingClientRect();
  2424. }
  2425. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2426. var rSpan = node.parentNode.getClientRects()[0];
  2427. if (rSpan)
  2428. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  2429. else
  2430. rect = nullRect;
  2431. }
  2432. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2433. var mid = (rtop + rbot) / 2;
  2434. var heights = prepared.view.measure.heights;
  2435. for (var i = 0; i < heights.length - 1; i++)
  2436. if (mid < heights[i]) break;
  2437. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2438. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2439. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2440. top: top, bottom: bot};
  2441. if (!rect.left && !rect.right) result.bogus = true;
  2442. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2443. return result;
  2444. }
  2445. // Work around problem with bounding client rects on ranges being
  2446. // returned incorrectly when zoomed on IE10 and below.
  2447. function maybeUpdateRectForZooming(measure, rect) {
  2448. if (!window.screen || screen.logicalXDPI == null ||
  2449. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2450. return rect;
  2451. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2452. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2453. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2454. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  2455. }
  2456. function clearLineMeasurementCacheFor(lineView) {
  2457. if (lineView.measure) {
  2458. lineView.measure.cache = {};
  2459. lineView.measure.heights = null;
  2460. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2461. lineView.measure.caches[i] = {};
  2462. }
  2463. }
  2464. function clearLineMeasurementCache(cm) {
  2465. cm.display.externalMeasure = null;
  2466. removeChildren(cm.display.lineMeasure);
  2467. for (var i = 0; i < cm.display.view.length; i++)
  2468. clearLineMeasurementCacheFor(cm.display.view[i]);
  2469. }
  2470. function clearCaches(cm) {
  2471. clearLineMeasurementCache(cm);
  2472. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2473. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2474. cm.display.lineNumChars = null;
  2475. }
  2476. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2477. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2478. // Converts a {top, bottom, left, right} box from line-local
  2479. // coordinates into another coordinate system. Context may be one of
  2480. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2481. // or "page".
  2482. function intoCoordSystem(cm, lineObj, rect, context) {
  2483. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2484. var size = widgetHeight(lineObj.widgets[i]);
  2485. rect.top += size; rect.bottom += size;
  2486. }
  2487. if (context == "line") return rect;
  2488. if (!context) context = "local";
  2489. var yOff = heightAtLine(lineObj);
  2490. if (context == "local") yOff += paddingTop(cm.display);
  2491. else yOff -= cm.display.viewOffset;
  2492. if (context == "page" || context == "window") {
  2493. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2494. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2495. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2496. rect.left += xOff; rect.right += xOff;
  2497. }
  2498. rect.top += yOff; rect.bottom += yOff;
  2499. return rect;
  2500. }
  2501. // Coverts a box from "div" coords to another coordinate system.
  2502. // Context may be "window", "page", "div", or "local"/null.
  2503. function fromCoordSystem(cm, coords, context) {
  2504. if (context == "div") return coords;
  2505. var left = coords.left, top = coords.top;
  2506. // First move into "page" coordinate system
  2507. if (context == "page") {
  2508. left -= pageScrollX();
  2509. top -= pageScrollY();
  2510. } else if (context == "local" || !context) {
  2511. var localBox = cm.display.sizer.getBoundingClientRect();
  2512. left += localBox.left;
  2513. top += localBox.top;
  2514. }
  2515. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2516. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  2517. }
  2518. function charCoords(cm, pos, context, lineObj, bias) {
  2519. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2520. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2521. }
  2522. // Returns a box for a given cursor position, which may have an
  2523. // 'other' property containing the position of the secondary cursor
  2524. // on a bidi boundary.
  2525. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2526. lineObj = lineObj || getLine(cm.doc, pos.line);
  2527. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2528. function get(ch, right) {
  2529. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2530. if (right) m.left = m.right; else m.right = m.left;
  2531. return intoCoordSystem(cm, lineObj, m, context);
  2532. }
  2533. function getBidi(ch, partPos) {
  2534. var part = order[partPos], right = part.level % 2;
  2535. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2536. part = order[--partPos];
  2537. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2538. right = true;
  2539. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2540. part = order[++partPos];
  2541. ch = bidiLeft(part) - part.level % 2;
  2542. right = false;
  2543. }
  2544. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2545. return get(ch, right);
  2546. }
  2547. var order = getOrder(lineObj), ch = pos.ch;
  2548. if (!order) return get(ch);
  2549. var partPos = getBidiPartAt(order, ch);
  2550. var val = getBidi(ch, partPos);
  2551. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2552. return val;
  2553. }
  2554. // Used to cheaply estimate the coordinates for a position. Used for
  2555. // intermediate scroll updates.
  2556. function estimateCoords(cm, pos) {
  2557. var left = 0, pos = clipPos(cm.doc, pos);
  2558. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2559. var lineObj = getLine(cm.doc, pos.line);
  2560. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2561. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  2562. }
  2563. // Positions returned by coordsChar contain some extra information.
  2564. // xRel is the relative x position of the input coordinates compared
  2565. // to the found position (so xRel > 0 means the coordinates are to
  2566. // the right of the character position, for example). When outside
  2567. // is true, that means the coordinates lie outside the line's
  2568. // vertical range.
  2569. function PosWithInfo(line, ch, outside, xRel) {
  2570. var pos = Pos(line, ch);
  2571. pos.xRel = xRel;
  2572. if (outside) pos.outside = true;
  2573. return pos;
  2574. }
  2575. // Compute the character position closest to the given coordinates.
  2576. // Input must be lineSpace-local ("div" coordinate system).
  2577. function coordsChar(cm, x, y) {
  2578. var doc = cm.doc;
  2579. y += cm.display.viewOffset;
  2580. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2581. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2582. if (lineN > last)
  2583. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2584. if (x < 0) x = 0;
  2585. var lineObj = getLine(doc, lineN);
  2586. for (;;) {
  2587. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2588. var merged = collapsedSpanAtEnd(lineObj);
  2589. var mergedPos = merged && merged.find(0, true);
  2590. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2591. lineN = lineNo(lineObj = mergedPos.to.line);
  2592. else
  2593. return found;
  2594. }
  2595. }
  2596. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2597. var innerOff = y - heightAtLine(lineObj);
  2598. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2599. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2600. function getX(ch) {
  2601. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2602. wrongLine = true;
  2603. if (innerOff > sp.bottom) return sp.left - adjust;
  2604. else if (innerOff < sp.top) return sp.left + adjust;
  2605. else wrongLine = false;
  2606. return sp.left;
  2607. }
  2608. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2609. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2610. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2611. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2612. // Do a binary search between these bounds.
  2613. for (;;) {
  2614. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2615. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2616. var xDiff = x - (ch == from ? fromX : toX);
  2617. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  2618. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  2619. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2620. return pos;
  2621. }
  2622. var step = Math.ceil(dist / 2), middle = from + step;
  2623. if (bidi) {
  2624. middle = from;
  2625. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2626. }
  2627. var middleX = getX(middle);
  2628. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  2629. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  2630. }
  2631. }
  2632. var measureText;
  2633. // Compute the default text height.
  2634. function textHeight(display) {
  2635. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2636. if (measureText == null) {
  2637. measureText = elt("pre");
  2638. // Measure a bunch of lines, for browsers that compute
  2639. // fractional heights.
  2640. for (var i = 0; i < 49; ++i) {
  2641. measureText.appendChild(document.createTextNode("x"));
  2642. measureText.appendChild(elt("br"));
  2643. }
  2644. measureText.appendChild(document.createTextNode("x"));
  2645. }
  2646. removeChildrenAndAdd(display.measure, measureText);
  2647. var height = measureText.offsetHeight / 50;
  2648. if (height > 3) display.cachedTextHeight = height;
  2649. removeChildren(display.measure);
  2650. return height || 1;
  2651. }
  2652. // Compute the default character width.
  2653. function charWidth(display) {
  2654. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2655. var anchor = elt("span", "xxxxxxxxxx");
  2656. var pre = elt("pre", [anchor]);
  2657. removeChildrenAndAdd(display.measure, pre);
  2658. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2659. if (width > 2) display.cachedCharWidth = width;
  2660. return width || 10;
  2661. }
  2662. // OPERATIONS
  2663. // Operations are used to wrap a series of changes to the editor
  2664. // state in such a way that each change won't have to update the
  2665. // cursor and display (which would be awkward, slow, and
  2666. // error-prone). Instead, display updates are batched and then all
  2667. // combined and executed at once.
  2668. var operationGroup = null;
  2669. var nextOpId = 0;
  2670. // Start a new operation.
  2671. function startOperation(cm) {
  2672. cm.curOp = {
  2673. cm: cm,
  2674. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2675. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2676. forceUpdate: false, // Used to force a redraw
  2677. updateInput: null, // Whether to reset the input textarea
  2678. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2679. changeObjs: null, // Accumulated changes, for firing change events
  2680. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2681. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2682. selectionChanged: false, // Whether the selection needs to be redrawn
  2683. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2684. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2685. scrollToPos: null, // Used to scroll to a specific position
  2686. focus: false,
  2687. id: ++nextOpId // Unique ID
  2688. };
  2689. if (operationGroup) {
  2690. operationGroup.ops.push(cm.curOp);
  2691. } else {
  2692. cm.curOp.ownsGroup = operationGroup = {
  2693. ops: [cm.curOp],
  2694. delayedCallbacks: []
  2695. };
  2696. }
  2697. }
  2698. function fireCallbacksForOps(group) {
  2699. // Calls delayed callbacks and cursorActivity handlers until no
  2700. // new ones appear
  2701. var callbacks = group.delayedCallbacks, i = 0;
  2702. do {
  2703. for (; i < callbacks.length; i++)
  2704. callbacks[i].call(null);
  2705. for (var j = 0; j < group.ops.length; j++) {
  2706. var op = group.ops[j];
  2707. if (op.cursorActivityHandlers)
  2708. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2709. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  2710. }
  2711. } while (i < callbacks.length);
  2712. }
  2713. // Finish an operation, updating the display and signalling delayed events
  2714. function endOperation(cm) {
  2715. var op = cm.curOp, group = op.ownsGroup;
  2716. if (!group) return;
  2717. try { fireCallbacksForOps(group); }
  2718. finally {
  2719. operationGroup = null;
  2720. for (var i = 0; i < group.ops.length; i++)
  2721. group.ops[i].cm.curOp = null;
  2722. endOperations(group);
  2723. }
  2724. }
  2725. // The DOM updates done when an operation finishes are batched so
  2726. // that the minimum number of relayouts are required.
  2727. function endOperations(group) {
  2728. var ops = group.ops;
  2729. for (var i = 0; i < ops.length; i++) // Read DOM
  2730. endOperation_R1(ops[i]);
  2731. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2732. endOperation_W1(ops[i]);
  2733. for (var i = 0; i < ops.length; i++) // Read DOM
  2734. endOperation_R2(ops[i]);
  2735. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2736. endOperation_W2(ops[i]);
  2737. for (var i = 0; i < ops.length; i++) // Read DOM
  2738. endOperation_finish(ops[i]);
  2739. }
  2740. function endOperation_R1(op) {
  2741. var cm = op.cm, display = cm.display;
  2742. maybeClipScrollbars(cm);
  2743. if (op.updateMaxLine) findMaxLine(cm);
  2744. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2745. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2746. op.scrollToPos.to.line >= display.viewTo) ||
  2747. display.maxLineChanged && cm.options.lineWrapping;
  2748. op.update = op.mustUpdate &&
  2749. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  2750. }
  2751. function endOperation_W1(op) {
  2752. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2753. }
  2754. function endOperation_R2(op) {
  2755. var cm = op.cm, display = cm.display;
  2756. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2757. op.barMeasure = measureForScrollbars(cm);
  2758. // If the max line changed since it was last measured, measure it,
  2759. // and ensure the document's width matches it.
  2760. // updateDisplay_W2 will use these properties to do the actual resizing
  2761. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2762. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2763. cm.display.sizerWidth = op.adjustWidthTo;
  2764. op.barMeasure.scrollWidth =
  2765. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2766. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2767. }
  2768. if (op.updatedDisplay || op.selectionChanged)
  2769. op.preparedSelection = display.input.prepareSelection();
  2770. }
  2771. function endOperation_W2(op) {
  2772. var cm = op.cm;
  2773. if (op.adjustWidthTo != null) {
  2774. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2775. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2776. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2777. cm.display.maxLineChanged = false;
  2778. }
  2779. if (op.preparedSelection)
  2780. cm.display.input.showSelection(op.preparedSelection);
  2781. if (op.updatedDisplay)
  2782. setDocumentHeight(cm, op.barMeasure);
  2783. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2784. updateScrollbars(cm, op.barMeasure);
  2785. if (op.selectionChanged) restartBlink(cm);
  2786. if (cm.state.focused && op.updateInput)
  2787. cm.display.input.reset(op.typing);
  2788. if (op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()))
  2789. ensureFocus(op.cm);
  2790. }
  2791. function endOperation_finish(op) {
  2792. var cm = op.cm, display = cm.display, doc = cm.doc;
  2793. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2794. // Abort mouse wheel delta measurement, when scrolling explicitly
  2795. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2796. display.wheelStartX = display.wheelStartY = null;
  2797. // Propagate the scroll position to the actual DOM scroller
  2798. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2799. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2800. display.scrollbars.setScrollTop(doc.scrollTop);
  2801. display.scroller.scrollTop = doc.scrollTop;
  2802. }
  2803. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2804. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
  2805. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2806. display.scroller.scrollLeft = doc.scrollLeft;
  2807. alignHorizontally(cm);
  2808. }
  2809. // If we need to scroll a specific position into view, do so.
  2810. if (op.scrollToPos) {
  2811. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2812. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2813. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2814. }
  2815. // Fire events for markers that are hidden/unidden by editing or
  2816. // undoing
  2817. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2818. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2819. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2820. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2821. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2822. if (display.wrapper.offsetHeight)
  2823. doc.scrollTop = cm.display.scroller.scrollTop;
  2824. // Fire change events, and delayed event handlers
  2825. if (op.changeObjs)
  2826. signal(cm, "changes", cm, op.changeObjs);
  2827. if (op.update)
  2828. op.update.finish();
  2829. }
  2830. // Run the given function in an operation
  2831. function runInOp(cm, f) {
  2832. if (cm.curOp) return f();
  2833. startOperation(cm);
  2834. try { return f(); }
  2835. finally { endOperation(cm); }
  2836. }
  2837. // Wraps a function in an operation. Returns the wrapped function.
  2838. function operation(cm, f) {
  2839. return function() {
  2840. if (cm.curOp) return f.apply(cm, arguments);
  2841. startOperation(cm);
  2842. try { return f.apply(cm, arguments); }
  2843. finally { endOperation(cm); }
  2844. };
  2845. }
  2846. // Used to add methods to editor and doc instances, wrapping them in
  2847. // operations.
  2848. function methodOp(f) {
  2849. return function() {
  2850. if (this.curOp) return f.apply(this, arguments);
  2851. startOperation(this);
  2852. try { return f.apply(this, arguments); }
  2853. finally { endOperation(this); }
  2854. };
  2855. }
  2856. function docMethodOp(f) {
  2857. return function() {
  2858. var cm = this.cm;
  2859. if (!cm || cm.curOp) return f.apply(this, arguments);
  2860. startOperation(cm);
  2861. try { return f.apply(this, arguments); }
  2862. finally { endOperation(cm); }
  2863. };
  2864. }
  2865. // VIEW TRACKING
  2866. // These objects are used to represent the visible (currently drawn)
  2867. // part of the document. A LineView may correspond to multiple
  2868. // logical lines, if those are connected by collapsed ranges.
  2869. function LineView(doc, line, lineN) {
  2870. // The starting line
  2871. this.line = line;
  2872. // Continuing lines, if any
  2873. this.rest = visualLineContinued(line);
  2874. // Number of logical lines in this visual line
  2875. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2876. this.node = this.text = null;
  2877. this.hidden = lineIsHidden(doc, line);
  2878. }
  2879. // Create a range of LineView objects for the given lines.
  2880. function buildViewArray(cm, from, to) {
  2881. var array = [], nextPos;
  2882. for (var pos = from; pos < to; pos = nextPos) {
  2883. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2884. nextPos = pos + view.size;
  2885. array.push(view);
  2886. }
  2887. return array;
  2888. }
  2889. // Updates the display.view data structure for a given change to the
  2890. // document. From and to are in pre-change coordinates. Lendiff is
  2891. // the amount of lines added or subtracted by the change. This is
  2892. // used for changes that span multiple lines, or change the way
  2893. // lines are divided into visual lines. regLineChange (below)
  2894. // registers single-line changes.
  2895. function regChange(cm, from, to, lendiff) {
  2896. if (from == null) from = cm.doc.first;
  2897. if (to == null) to = cm.doc.first + cm.doc.size;
  2898. if (!lendiff) lendiff = 0;
  2899. var display = cm.display;
  2900. if (lendiff && to < display.viewTo &&
  2901. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2902. display.updateLineNumbers = from;
  2903. cm.curOp.viewChanged = true;
  2904. if (from >= display.viewTo) { // Change after
  2905. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2906. resetView(cm);
  2907. } else if (to <= display.viewFrom) { // Change before
  2908. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2909. resetView(cm);
  2910. } else {
  2911. display.viewFrom += lendiff;
  2912. display.viewTo += lendiff;
  2913. }
  2914. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2915. resetView(cm);
  2916. } else if (from <= display.viewFrom) { // Top overlap
  2917. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2918. if (cut) {
  2919. display.view = display.view.slice(cut.index);
  2920. display.viewFrom = cut.lineN;
  2921. display.viewTo += lendiff;
  2922. } else {
  2923. resetView(cm);
  2924. }
  2925. } else if (to >= display.viewTo) { // Bottom overlap
  2926. var cut = viewCuttingPoint(cm, from, from, -1);
  2927. if (cut) {
  2928. display.view = display.view.slice(0, cut.index);
  2929. display.viewTo = cut.lineN;
  2930. } else {
  2931. resetView(cm);
  2932. }
  2933. } else { // Gap in the middle
  2934. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2935. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2936. if (cutTop && cutBot) {
  2937. display.view = display.view.slice(0, cutTop.index)
  2938. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2939. .concat(display.view.slice(cutBot.index));
  2940. display.viewTo += lendiff;
  2941. } else {
  2942. resetView(cm);
  2943. }
  2944. }
  2945. var ext = display.externalMeasured;
  2946. if (ext) {
  2947. if (to < ext.lineN)
  2948. ext.lineN += lendiff;
  2949. else if (from < ext.lineN + ext.size)
  2950. display.externalMeasured = null;
  2951. }
  2952. }
  2953. // Register a change to a single line. Type must be one of "text",
  2954. // "gutter", "class", "widget"
  2955. function regLineChange(cm, line, type) {
  2956. cm.curOp.viewChanged = true;
  2957. var display = cm.display, ext = cm.display.externalMeasured;
  2958. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2959. display.externalMeasured = null;
  2960. if (line < display.viewFrom || line >= display.viewTo) return;
  2961. var lineView = display.view[findViewIndex(cm, line)];
  2962. if (lineView.node == null) return;
  2963. var arr = lineView.changes || (lineView.changes = []);
  2964. if (indexOf(arr, type) == -1) arr.push(type);
  2965. }
  2966. // Clear the view.
  2967. function resetView(cm) {
  2968. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2969. cm.display.view = [];
  2970. cm.display.viewOffset = 0;
  2971. }
  2972. // Find the view element corresponding to a given line. Return null
  2973. // when the line isn't visible.
  2974. function findViewIndex(cm, n) {
  2975. if (n >= cm.display.viewTo) return null;
  2976. n -= cm.display.viewFrom;
  2977. if (n < 0) return null;
  2978. var view = cm.display.view;
  2979. for (var i = 0; i < view.length; i++) {
  2980. n -= view[i].size;
  2981. if (n < 0) return i;
  2982. }
  2983. }
  2984. function viewCuttingPoint(cm, oldN, newN, dir) {
  2985. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2986. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2987. return {index: index, lineN: newN};
  2988. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2989. n += view[i].size;
  2990. if (n != oldN) {
  2991. if (dir > 0) {
  2992. if (index == view.length - 1) return null;
  2993. diff = (n + view[index].size) - oldN;
  2994. index++;
  2995. } else {
  2996. diff = n - oldN;
  2997. }
  2998. oldN += diff; newN += diff;
  2999. }
  3000. while (visualLineNo(cm.doc, newN) != newN) {
  3001. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  3002. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3003. index += dir;
  3004. }
  3005. return {index: index, lineN: newN};
  3006. }
  3007. // Force the view to cover a given range, adding empty view element
  3008. // or clipping off existing ones as needed.
  3009. function adjustView(cm, from, to) {
  3010. var display = cm.display, view = display.view;
  3011. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3012. display.view = buildViewArray(cm, from, to);
  3013. display.viewFrom = from;
  3014. } else {
  3015. if (display.viewFrom > from)
  3016. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  3017. else if (display.viewFrom < from)
  3018. display.view = display.view.slice(findViewIndex(cm, from));
  3019. display.viewFrom = from;
  3020. if (display.viewTo < to)
  3021. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  3022. else if (display.viewTo > to)
  3023. display.view = display.view.slice(0, findViewIndex(cm, to));
  3024. }
  3025. display.viewTo = to;
  3026. }
  3027. // Count the number of lines in the view whose DOM representation is
  3028. // out of date (or nonexistent).
  3029. function countDirtyView(cm) {
  3030. var view = cm.display.view, dirty = 0;
  3031. for (var i = 0; i < view.length; i++) {
  3032. var lineView = view[i];
  3033. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  3034. }
  3035. return dirty;
  3036. }
  3037. // EVENT HANDLERS
  3038. // Attach the necessary event handlers when initializing the editor
  3039. function registerEventHandlers(cm) {
  3040. var d = cm.display;
  3041. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  3042. // Older IE's will not fire a second mousedown for a double click
  3043. if (ie && ie_version < 11)
  3044. on(d.scroller, "dblclick", operation(cm, function(e) {
  3045. if (signalDOMEvent(cm, e)) return;
  3046. var pos = posFromMouse(cm, e);
  3047. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  3048. e_preventDefault(e);
  3049. var word = cm.findWordAt(pos);
  3050. extendSelection(cm.doc, word.anchor, word.head);
  3051. }));
  3052. else
  3053. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  3054. // Some browsers fire contextmenu *after* opening the menu, at
  3055. // which point we can't mess with it anymore. Context menu is
  3056. // handled in onMouseDown for these browsers.
  3057. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  3058. // Used to suppress mouse event handling when a touch happens
  3059. var touchFinished, prevTouch = {end: 0};
  3060. function finishTouch() {
  3061. if (d.activeTouch) {
  3062. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  3063. prevTouch = d.activeTouch;
  3064. prevTouch.end = +new Date;
  3065. }
  3066. };
  3067. function isMouseLikeTouchEvent(e) {
  3068. if (e.touches.length != 1) return false;
  3069. var touch = e.touches[0];
  3070. return touch.radiusX <= 1 && touch.radiusY <= 1;
  3071. }
  3072. function farAway(touch, other) {
  3073. if (other.left == null) return true;
  3074. var dx = other.left - touch.left, dy = other.top - touch.top;
  3075. return dx * dx + dy * dy > 20 * 20;
  3076. }
  3077. on(d.scroller, "touchstart", function(e) {
  3078. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  3079. clearTimeout(touchFinished);
  3080. var now = +new Date;
  3081. d.activeTouch = {start: now, moved: false,
  3082. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  3083. if (e.touches.length == 1) {
  3084. d.activeTouch.left = e.touches[0].pageX;
  3085. d.activeTouch.top = e.touches[0].pageY;
  3086. }
  3087. }
  3088. });
  3089. on(d.scroller, "touchmove", function() {
  3090. if (d.activeTouch) d.activeTouch.moved = true;
  3091. });
  3092. on(d.scroller, "touchend", function(e) {
  3093. var touch = d.activeTouch;
  3094. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3095. !touch.moved && new Date - touch.start < 300) {
  3096. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3097. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3098. range = new Range(pos, pos);
  3099. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3100. range = cm.findWordAt(pos);
  3101. else // Triple tap
  3102. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3103. cm.setSelection(range.anchor, range.head);
  3104. cm.focus();
  3105. e_preventDefault(e);
  3106. }
  3107. finishTouch();
  3108. });
  3109. on(d.scroller, "touchcancel", finishTouch);
  3110. // Sync scrolling between fake scrollbars and real scrollable
  3111. // area, ensure viewport is updated when scrolling.
  3112. on(d.scroller, "scroll", function() {
  3113. if (d.scroller.clientHeight) {
  3114. setScrollTop(cm, d.scroller.scrollTop);
  3115. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3116. signal(cm, "scroll", cm);
  3117. }
  3118. });
  3119. // Listen to wheel events in order to try and update the viewport on time.
  3120. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  3121. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  3122. // Prevent wrapper from ever scrolling
  3123. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3124. d.dragFunctions = {
  3125. enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  3126. over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  3127. start: function(e){onDragStart(cm, e);},
  3128. drop: operation(cm, onDrop),
  3129. leave: function() {clearDragCursor(cm);}
  3130. };
  3131. var inp = d.input.getField();
  3132. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  3133. on(inp, "keydown", operation(cm, onKeyDown));
  3134. on(inp, "keypress", operation(cm, onKeyPress));
  3135. on(inp, "focus", bind(onFocus, cm));
  3136. on(inp, "blur", bind(onBlur, cm));
  3137. }
  3138. function dragDropChanged(cm, value, old) {
  3139. var wasOn = old && old != CodeMirror.Init;
  3140. if (!value != !wasOn) {
  3141. var funcs = cm.display.dragFunctions;
  3142. var toggle = value ? on : off;
  3143. toggle(cm.display.scroller, "dragstart", funcs.start);
  3144. toggle(cm.display.scroller, "dragenter", funcs.enter);
  3145. toggle(cm.display.scroller, "dragover", funcs.over);
  3146. toggle(cm.display.scroller, "dragleave", funcs.leave);
  3147. toggle(cm.display.scroller, "drop", funcs.drop);
  3148. }
  3149. }
  3150. // Called when the window resizes
  3151. function onResize(cm) {
  3152. var d = cm.display;
  3153. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3154. return;
  3155. // Might be a text scaling operation, clear size caches.
  3156. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3157. d.scrollbarsClipped = false;
  3158. cm.setSize();
  3159. }
  3160. // MOUSE EVENTS
  3161. // Return true when the given mouse event happened in a widget
  3162. function eventInWidget(display, e) {
  3163. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3164. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3165. (n.parentNode == display.sizer && n != display.mover))
  3166. return true;
  3167. }
  3168. }
  3169. // Given a mouse event, find the corresponding position. If liberal
  3170. // is false, it checks whether a gutter or scrollbar was clicked,
  3171. // and returns null if it was. forRect is used by rectangular
  3172. // selections, and tries to estimate a character position even for
  3173. // coordinates beyond the right of the text.
  3174. function posFromMouse(cm, e, liberal, forRect) {
  3175. var display = cm.display;
  3176. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3177. var x, y, space = display.lineSpace.getBoundingClientRect();
  3178. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3179. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3180. catch (e) { return null; }
  3181. var coords = coordsChar(cm, x, y), line;
  3182. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3183. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3184. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3185. }
  3186. return coords;
  3187. }
  3188. // A mouse down can be a single click, double click, triple click,
  3189. // start of selection drag, start of text drag, new cursor
  3190. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3191. // middle-click-paste. Or it might be a click on something we should
  3192. // not interfere with, such as a scrollbar or widget.
  3193. function onMouseDown(e) {
  3194. var cm = this, display = cm.display;
  3195. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
  3196. display.shift = e.shiftKey;
  3197. if (eventInWidget(display, e)) {
  3198. if (!webkit) {
  3199. // Briefly turn off draggability, to allow widgets to do
  3200. // normal dragging things.
  3201. display.scroller.draggable = false;
  3202. setTimeout(function(){display.scroller.draggable = true;}, 100);
  3203. }
  3204. return;
  3205. }
  3206. if (clickInGutter(cm, e)) return;
  3207. var start = posFromMouse(cm, e);
  3208. window.focus();
  3209. switch (e_button(e)) {
  3210. case 1:
  3211. // #3261: make sure, that we're not starting a second selection
  3212. if (cm.state.selectingText)
  3213. cm.state.selectingText(e);
  3214. else if (start)
  3215. leftButtonDown(cm, e, start);
  3216. else if (e_target(e) == display.scroller)
  3217. e_preventDefault(e);
  3218. break;
  3219. case 2:
  3220. if (webkit) cm.state.lastMiddleDown = +new Date;
  3221. if (start) extendSelection(cm.doc, start);
  3222. setTimeout(function() {display.input.focus();}, 20);
  3223. e_preventDefault(e);
  3224. break;
  3225. case 3:
  3226. if (captureRightClick) onContextMenu(cm, e);
  3227. else delayBlurEvent(cm);
  3228. break;
  3229. }
  3230. }
  3231. var lastClick, lastDoubleClick;
  3232. function leftButtonDown(cm, e, start) {
  3233. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3234. else cm.curOp.focus = activeElt();
  3235. var now = +new Date, type;
  3236. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3237. type = "triple";
  3238. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3239. type = "double";
  3240. lastDoubleClick = {time: now, pos: start};
  3241. } else {
  3242. type = "single";
  3243. lastClick = {time: now, pos: start};
  3244. }
  3245. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3246. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  3247. type == "single" && (contained = sel.contains(start)) > -1 &&
  3248. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  3249. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  3250. leftButtonStartDrag(cm, e, start, modifier);
  3251. else
  3252. leftButtonSelect(cm, e, start, type, modifier);
  3253. }
  3254. // Start a text drag. When it ends, see if any dragging actually
  3255. // happen, and treat as a click if it didn't.
  3256. function leftButtonStartDrag(cm, e, start, modifier) {
  3257. var display = cm.display, startTime = +new Date;
  3258. var dragEnd = operation(cm, function(e2) {
  3259. if (webkit) display.scroller.draggable = false;
  3260. cm.state.draggingText = false;
  3261. off(document, "mouseup", dragEnd);
  3262. off(display.scroller, "drop", dragEnd);
  3263. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3264. e_preventDefault(e2);
  3265. if (!modifier && +new Date - 200 < startTime)
  3266. extendSelection(cm.doc, start);
  3267. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  3268. if (webkit || ie && ie_version == 9)
  3269. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  3270. else
  3271. display.input.focus();
  3272. }
  3273. });
  3274. // Let the drag handler handle this.
  3275. if (webkit) display.scroller.draggable = true;
  3276. cm.state.draggingText = dragEnd;
  3277. // IE's approach to draggable
  3278. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3279. on(document, "mouseup", dragEnd);
  3280. on(display.scroller, "drop", dragEnd);
  3281. }
  3282. // Normal selection, as opposed to text dragging.
  3283. function leftButtonSelect(cm, e, start, type, addNew) {
  3284. var display = cm.display, doc = cm.doc;
  3285. e_preventDefault(e);
  3286. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3287. if (addNew && !e.shiftKey) {
  3288. ourIndex = doc.sel.contains(start);
  3289. if (ourIndex > -1)
  3290. ourRange = ranges[ourIndex];
  3291. else
  3292. ourRange = new Range(start, start);
  3293. } else {
  3294. ourRange = doc.sel.primary();
  3295. ourIndex = doc.sel.primIndex;
  3296. }
  3297. if (e.altKey) {
  3298. type = "rect";
  3299. if (!addNew) ourRange = new Range(start, start);
  3300. start = posFromMouse(cm, e, true, true);
  3301. ourIndex = -1;
  3302. } else if (type == "double") {
  3303. var word = cm.findWordAt(start);
  3304. if (cm.display.shift || doc.extend)
  3305. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3306. else
  3307. ourRange = word;
  3308. } else if (type == "triple") {
  3309. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3310. if (cm.display.shift || doc.extend)
  3311. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3312. else
  3313. ourRange = line;
  3314. } else {
  3315. ourRange = extendRange(doc, ourRange, start);
  3316. }
  3317. if (!addNew) {
  3318. ourIndex = 0;
  3319. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3320. startSel = doc.sel;
  3321. } else if (ourIndex == -1) {
  3322. ourIndex = ranges.length;
  3323. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3324. {scroll: false, origin: "*mouse"});
  3325. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  3326. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  3327. {scroll: false, origin: "*mouse"});
  3328. startSel = doc.sel;
  3329. } else {
  3330. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3331. }
  3332. var lastPos = start;
  3333. function extendTo(pos) {
  3334. if (cmp(lastPos, pos) == 0) return;
  3335. lastPos = pos;
  3336. if (type == "rect") {
  3337. var ranges = [], tabSize = cm.options.tabSize;
  3338. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3339. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3340. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3341. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3342. line <= end; line++) {
  3343. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3344. if (left == right)
  3345. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3346. else if (text.length > leftPos)
  3347. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3348. }
  3349. if (!ranges.length) ranges.push(new Range(start, start));
  3350. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3351. {origin: "*mouse", scroll: false});
  3352. cm.scrollIntoView(pos);
  3353. } else {
  3354. var oldRange = ourRange;
  3355. var anchor = oldRange.anchor, head = pos;
  3356. if (type != "single") {
  3357. if (type == "double")
  3358. var range = cm.findWordAt(pos);
  3359. else
  3360. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3361. if (cmp(range.anchor, anchor) > 0) {
  3362. head = range.head;
  3363. anchor = minPos(oldRange.from(), range.anchor);
  3364. } else {
  3365. head = range.anchor;
  3366. anchor = maxPos(oldRange.to(), range.head);
  3367. }
  3368. }
  3369. var ranges = startSel.ranges.slice(0);
  3370. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3371. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3372. }
  3373. }
  3374. var editorSize = display.wrapper.getBoundingClientRect();
  3375. // Used to ensure timeout re-tries don't fire when another extend
  3376. // happened in the meantime (clearTimeout isn't reliable -- at
  3377. // least on Chrome, the timeouts still happen even when cleared,
  3378. // if the clear happens after their scheduled firing time).
  3379. var counter = 0;
  3380. function extend(e) {
  3381. var curCount = ++counter;
  3382. var cur = posFromMouse(cm, e, true, type == "rect");
  3383. if (!cur) return;
  3384. if (cmp(cur, lastPos) != 0) {
  3385. cm.curOp.focus = activeElt();
  3386. extendTo(cur);
  3387. var visible = visibleLines(display, doc);
  3388. if (cur.line >= visible.to || cur.line < visible.from)
  3389. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  3390. } else {
  3391. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3392. if (outside) setTimeout(operation(cm, function() {
  3393. if (counter != curCount) return;
  3394. display.scroller.scrollTop += outside;
  3395. extend(e);
  3396. }), 50);
  3397. }
  3398. }
  3399. function done(e) {
  3400. cm.state.selectingText = false;
  3401. counter = Infinity;
  3402. e_preventDefault(e);
  3403. display.input.focus();
  3404. off(document, "mousemove", move);
  3405. off(document, "mouseup", up);
  3406. doc.history.lastSelOrigin = null;
  3407. }
  3408. var move = operation(cm, function(e) {
  3409. if (!e_button(e)) done(e);
  3410. else extend(e);
  3411. });
  3412. var up = operation(cm, done);
  3413. cm.state.selectingText = up;
  3414. on(document, "mousemove", move);
  3415. on(document, "mouseup", up);
  3416. }
  3417. // Determines whether an event happened in the gutter, and fires the
  3418. // handlers for the corresponding event.
  3419. function gutterEvent(cm, e, type, prevent) {
  3420. try { var mX = e.clientX, mY = e.clientY; }
  3421. catch(e) { return false; }
  3422. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3423. if (prevent) e_preventDefault(e);
  3424. var display = cm.display;
  3425. var lineBox = display.lineDiv.getBoundingClientRect();
  3426. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3427. mY -= lineBox.top - display.viewOffset;
  3428. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3429. var g = display.gutters.childNodes[i];
  3430. if (g && g.getBoundingClientRect().right >= mX) {
  3431. var line = lineAtHeight(cm.doc, mY);
  3432. var gutter = cm.options.gutters[i];
  3433. signal(cm, type, cm, line, gutter, e);
  3434. return e_defaultPrevented(e);
  3435. }
  3436. }
  3437. }
  3438. function clickInGutter(cm, e) {
  3439. return gutterEvent(cm, e, "gutterClick", true);
  3440. }
  3441. // Kludge to work around strange IE behavior where it'll sometimes
  3442. // re-fire a series of drag-related events right after the drop (#1551)
  3443. var lastDrop = 0;
  3444. function onDrop(e) {
  3445. var cm = this;
  3446. clearDragCursor(cm);
  3447. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3448. return;
  3449. e_preventDefault(e);
  3450. if (ie) lastDrop = +new Date;
  3451. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3452. if (!pos || cm.isReadOnly()) return;
  3453. // Might be a file drop, in which case we simply extract the text
  3454. // and insert it.
  3455. if (files && files.length && window.FileReader && window.File) {
  3456. var n = files.length, text = Array(n), read = 0;
  3457. var loadFile = function(file, i) {
  3458. if (cm.options.allowDropFileTypes &&
  3459. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  3460. return;
  3461. var reader = new FileReader;
  3462. reader.onload = operation(cm, function() {
  3463. var content = reader.result;
  3464. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
  3465. text[i] = content;
  3466. if (++read == n) {
  3467. pos = clipPos(cm.doc, pos);
  3468. var change = {from: pos, to: pos,
  3469. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  3470. origin: "paste"};
  3471. makeChange(cm.doc, change);
  3472. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3473. }
  3474. });
  3475. reader.readAsText(file);
  3476. };
  3477. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3478. } else { // Normal drop
  3479. // Don't do a replace if the drop happened inside of the selected text.
  3480. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3481. cm.state.draggingText(e);
  3482. // Ensure the editor is re-focused
  3483. setTimeout(function() {cm.display.input.focus();}, 20);
  3484. return;
  3485. }
  3486. try {
  3487. var text = e.dataTransfer.getData("Text");
  3488. if (text) {
  3489. if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
  3490. var selected = cm.listSelections();
  3491. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3492. if (selected) for (var i = 0; i < selected.length; ++i)
  3493. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3494. cm.replaceSelection(text, "around", "paste");
  3495. cm.display.input.focus();
  3496. }
  3497. }
  3498. catch(e){}
  3499. }
  3500. }
  3501. function onDragStart(cm, e) {
  3502. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3503. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3504. e.dataTransfer.setData("Text", cm.getSelection());
  3505. // Use dummy image instead of default browsers image.
  3506. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3507. if (e.dataTransfer.setDragImage && !safari) {
  3508. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3509. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3510. if (presto) {
  3511. img.width = img.height = 1;
  3512. cm.display.wrapper.appendChild(img);
  3513. // Force a relayout, or Opera won't use our image for some obscure reason
  3514. img._top = img.offsetTop;
  3515. }
  3516. e.dataTransfer.setDragImage(img, 0, 0);
  3517. if (presto) img.parentNode.removeChild(img);
  3518. }
  3519. }
  3520. function onDragOver(cm, e) {
  3521. var pos = posFromMouse(cm, e);
  3522. if (!pos) return;
  3523. var frag = document.createDocumentFragment();
  3524. drawSelectionCursor(cm, pos, frag);
  3525. if (!cm.display.dragCursor) {
  3526. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  3527. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  3528. }
  3529. removeChildrenAndAdd(cm.display.dragCursor, frag);
  3530. }
  3531. function clearDragCursor(cm) {
  3532. if (cm.display.dragCursor) {
  3533. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  3534. cm.display.dragCursor = null;
  3535. }
  3536. }
  3537. // SCROLL EVENTS
  3538. // Sync the scrollable area and scrollbars, ensure the viewport
  3539. // covers the visible area.
  3540. function setScrollTop(cm, val) {
  3541. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3542. cm.doc.scrollTop = val;
  3543. if (!gecko) updateDisplaySimple(cm, {top: val});
  3544. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3545. cm.display.scrollbars.setScrollTop(val);
  3546. if (gecko) updateDisplaySimple(cm);
  3547. startWorker(cm, 100);
  3548. }
  3549. // Sync scroller and scrollbar, ensure the gutter elements are
  3550. // aligned.
  3551. function setScrollLeft(cm, val, isScroller) {
  3552. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3553. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3554. cm.doc.scrollLeft = val;
  3555. alignHorizontally(cm);
  3556. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3557. cm.display.scrollbars.setScrollLeft(val);
  3558. }
  3559. // Since the delta values reported on mouse wheel events are
  3560. // unstandardized between browsers and even browser versions, and
  3561. // generally horribly unpredictable, this code starts by measuring
  3562. // the scroll effect that the first few mouse wheel events have,
  3563. // and, from that, detects the way it can convert deltas to pixel
  3564. // offsets afterwards.
  3565. //
  3566. // The reason we want to know the amount a wheel event will scroll
  3567. // is that it gives us a chance to update the display before the
  3568. // actual scrolling happens, reducing flickering.
  3569. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3570. // Fill in a browser-detected starting value on browsers where we
  3571. // know one. These don't have to be accurate -- the result of them
  3572. // being wrong would just be a slight flicker on the first wheel
  3573. // scroll (if it is large enough).
  3574. if (ie) wheelPixelsPerUnit = -.53;
  3575. else if (gecko) wheelPixelsPerUnit = 15;
  3576. else if (chrome) wheelPixelsPerUnit = -.7;
  3577. else if (safari) wheelPixelsPerUnit = -1/3;
  3578. var wheelEventDelta = function(e) {
  3579. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3580. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3581. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3582. else if (dy == null) dy = e.wheelDelta;
  3583. return {x: dx, y: dy};
  3584. };
  3585. CodeMirror.wheelEventPixels = function(e) {
  3586. var delta = wheelEventDelta(e);
  3587. delta.x *= wheelPixelsPerUnit;
  3588. delta.y *= wheelPixelsPerUnit;
  3589. return delta;
  3590. };
  3591. function onScrollWheel(cm, e) {
  3592. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3593. var display = cm.display, scroll = display.scroller;
  3594. // Quit if there's nothing to scroll here
  3595. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  3596. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  3597. if (!(dx && canScrollX || dy && canScrollY)) return;
  3598. // Webkit browsers on OS X abort momentum scrolls when the target
  3599. // of the scroll event is removed from the scrollable element.
  3600. // This hack (see related code in patchDisplay) makes sure the
  3601. // element is kept around.
  3602. if (dy && mac && webkit) {
  3603. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3604. for (var i = 0; i < view.length; i++) {
  3605. if (view[i].node == cur) {
  3606. cm.display.currentWheelTarget = cur;
  3607. break outer;
  3608. }
  3609. }
  3610. }
  3611. }
  3612. // On some browsers, horizontal scrolling will cause redraws to
  3613. // happen before the gutter has been realigned, causing it to
  3614. // wriggle around in a most unseemly way. When we have an
  3615. // estimated pixels/delta value, we just handle horizontal
  3616. // scrolling entirely here. It'll be slightly off from native, but
  3617. // better than glitching out.
  3618. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3619. if (dy && canScrollY)
  3620. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3621. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3622. // Only prevent default scrolling if vertical scrolling is
  3623. // actually possible. Otherwise, it causes vertical scroll
  3624. // jitter on OSX trackpads when deltaX is small and deltaY
  3625. // is large (issue #3579)
  3626. if (!dy || (dy && canScrollY))
  3627. e_preventDefault(e);
  3628. display.wheelStartX = null; // Abort measurement, if in progress
  3629. return;
  3630. }
  3631. // 'Project' the visible viewport to cover the area that is being
  3632. // scrolled into view (if we know enough to estimate it).
  3633. if (dy && wheelPixelsPerUnit != null) {
  3634. var pixels = dy * wheelPixelsPerUnit;
  3635. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3636. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3637. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3638. updateDisplaySimple(cm, {top: top, bottom: bot});
  3639. }
  3640. if (wheelSamples < 20) {
  3641. if (display.wheelStartX == null) {
  3642. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3643. display.wheelDX = dx; display.wheelDY = dy;
  3644. setTimeout(function() {
  3645. if (display.wheelStartX == null) return;
  3646. var movedX = scroll.scrollLeft - display.wheelStartX;
  3647. var movedY = scroll.scrollTop - display.wheelStartY;
  3648. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3649. (movedX && display.wheelDX && movedX / display.wheelDX);
  3650. display.wheelStartX = display.wheelStartY = null;
  3651. if (!sample) return;
  3652. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3653. ++wheelSamples;
  3654. }, 200);
  3655. } else {
  3656. display.wheelDX += dx; display.wheelDY += dy;
  3657. }
  3658. }
  3659. }
  3660. // KEY EVENTS
  3661. // Run a handler that was bound to a key.
  3662. function doHandleBinding(cm, bound, dropShift) {
  3663. if (typeof bound == "string") {
  3664. bound = commands[bound];
  3665. if (!bound) return false;
  3666. }
  3667. // Ensure previous input has been read, so that the handler sees a
  3668. // consistent view of the document
  3669. cm.display.input.ensurePolled();
  3670. var prevShift = cm.display.shift, done = false;
  3671. try {
  3672. if (cm.isReadOnly()) cm.state.suppressEdits = true;
  3673. if (dropShift) cm.display.shift = false;
  3674. done = bound(cm) != Pass;
  3675. } finally {
  3676. cm.display.shift = prevShift;
  3677. cm.state.suppressEdits = false;
  3678. }
  3679. return done;
  3680. }
  3681. function lookupKeyForEditor(cm, name, handle) {
  3682. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3683. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3684. if (result) return result;
  3685. }
  3686. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3687. || lookupKey(name, cm.options.keyMap, handle, cm);
  3688. }
  3689. var stopSeq = new Delayed;
  3690. function dispatchKey(cm, name, e, handle) {
  3691. var seq = cm.state.keySeq;
  3692. if (seq) {
  3693. if (isModifierKey(name)) return "handled";
  3694. stopSeq.set(50, function() {
  3695. if (cm.state.keySeq == seq) {
  3696. cm.state.keySeq = null;
  3697. cm.display.input.reset();
  3698. }
  3699. });
  3700. name = seq + " " + name;
  3701. }
  3702. var result = lookupKeyForEditor(cm, name, handle);
  3703. if (result == "multi")
  3704. cm.state.keySeq = name;
  3705. if (result == "handled")
  3706. signalLater(cm, "keyHandled", cm, name, e);
  3707. if (result == "handled" || result == "multi") {
  3708. e_preventDefault(e);
  3709. restartBlink(cm);
  3710. }
  3711. if (seq && !result && /\'$/.test(name)) {
  3712. e_preventDefault(e);
  3713. return true;
  3714. }
  3715. return !!result;
  3716. }
  3717. // Handle a key from the keydown event.
  3718. function handleKeyBinding(cm, e) {
  3719. var name = keyName(e, true);
  3720. if (!name) return false;
  3721. if (e.shiftKey && !cm.state.keySeq) {
  3722. // First try to resolve full name (including 'Shift-'). Failing
  3723. // that, see if there is a cursor-motion command (starting with
  3724. // 'go') bound to the keyname without 'Shift-'.
  3725. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3726. || dispatchKey(cm, name, e, function(b) {
  3727. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3728. return doHandleBinding(cm, b);
  3729. });
  3730. } else {
  3731. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3732. }
  3733. }
  3734. // Handle a key from the keypress event
  3735. function handleCharBinding(cm, e, ch) {
  3736. return dispatchKey(cm, "'" + ch + "'", e,
  3737. function(b) { return doHandleBinding(cm, b, true); });
  3738. }
  3739. var lastStoppedKey = null;
  3740. function onKeyDown(e) {
  3741. var cm = this;
  3742. cm.curOp.focus = activeElt();
  3743. if (signalDOMEvent(cm, e)) return;
  3744. // IE does strange things with escape.
  3745. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3746. var code = e.keyCode;
  3747. cm.display.shift = code == 16 || e.shiftKey;
  3748. var handled = handleKeyBinding(cm, e);
  3749. if (presto) {
  3750. lastStoppedKey = handled ? code : null;
  3751. // Opera has no cut event... we try to at least catch the key combo
  3752. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3753. cm.replaceSelection("", null, "cut");
  3754. }
  3755. // Turn mouse into crosshair when Alt is held on Mac.
  3756. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3757. showCrossHair(cm);
  3758. }
  3759. function showCrossHair(cm) {
  3760. var lineDiv = cm.display.lineDiv;
  3761. addClass(lineDiv, "CodeMirror-crosshair");
  3762. function up(e) {
  3763. if (e.keyCode == 18 || !e.altKey) {
  3764. rmClass(lineDiv, "CodeMirror-crosshair");
  3765. off(document, "keyup", up);
  3766. off(document, "mouseover", up);
  3767. }
  3768. }
  3769. on(document, "keyup", up);
  3770. on(document, "mouseover", up);
  3771. }
  3772. function onKeyUp(e) {
  3773. if (e.keyCode == 16) this.doc.sel.shift = false;
  3774. signalDOMEvent(this, e);
  3775. }
  3776. function onKeyPress(e) {
  3777. var cm = this;
  3778. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3779. var keyCode = e.keyCode, charCode = e.charCode;
  3780. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3781. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3782. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3783. if (handleCharBinding(cm, e, ch)) return;
  3784. cm.display.input.onKeyPress(e);
  3785. }
  3786. // FOCUS/BLUR EVENTS
  3787. function delayBlurEvent(cm) {
  3788. cm.state.delayingBlurEvent = true;
  3789. setTimeout(function() {
  3790. if (cm.state.delayingBlurEvent) {
  3791. cm.state.delayingBlurEvent = false;
  3792. onBlur(cm);
  3793. }
  3794. }, 100);
  3795. }
  3796. function onFocus(cm) {
  3797. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  3798. if (cm.options.readOnly == "nocursor") return;
  3799. if (!cm.state.focused) {
  3800. signal(cm, "focus", cm);
  3801. cm.state.focused = true;
  3802. addClass(cm.display.wrapper, "CodeMirror-focused");
  3803. // This test prevents this from firing when a context
  3804. // menu is closed (since the input reset would kill the
  3805. // select-all detection hack)
  3806. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3807. cm.display.input.reset();
  3808. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  3809. }
  3810. cm.display.input.receivedFocus();
  3811. }
  3812. restartBlink(cm);
  3813. }
  3814. function onBlur(cm) {
  3815. if (cm.state.delayingBlurEvent) return;
  3816. if (cm.state.focused) {
  3817. signal(cm, "blur", cm);
  3818. cm.state.focused = false;
  3819. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3820. }
  3821. clearInterval(cm.display.blinker);
  3822. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3823. }
  3824. // CONTEXT MENU HANDLING
  3825. // To make the context menu work, we need to briefly unhide the
  3826. // textarea (making it as unobtrusive as possible) to let the
  3827. // right-click take effect on it.
  3828. function onContextMenu(cm, e) {
  3829. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3830. if (signalDOMEvent(cm, e, "contextmenu")) return;
  3831. cm.display.input.onContextMenu(e);
  3832. }
  3833. function contextMenuInGutter(cm, e) {
  3834. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3835. return gutterEvent(cm, e, "gutterContextMenu", false);
  3836. }
  3837. // UPDATING
  3838. // Compute the position of the end of a change (its 'to' property
  3839. // refers to the pre-change end).
  3840. var changeEnd = CodeMirror.changeEnd = function(change) {
  3841. if (!change.text) return change.to;
  3842. return Pos(change.from.line + change.text.length - 1,
  3843. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3844. };
  3845. // Adjust a position to refer to the post-change position of the
  3846. // same text, or the end of the change if the change covers it.
  3847. function adjustForChange(pos, change) {
  3848. if (cmp(pos, change.from) < 0) return pos;
  3849. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3850. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3851. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3852. return Pos(line, ch);
  3853. }
  3854. function computeSelAfterChange(doc, change) {
  3855. var out = [];
  3856. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3857. var range = doc.sel.ranges[i];
  3858. out.push(new Range(adjustForChange(range.anchor, change),
  3859. adjustForChange(range.head, change)));
  3860. }
  3861. return normalizeSelection(out, doc.sel.primIndex);
  3862. }
  3863. function offsetPos(pos, old, nw) {
  3864. if (pos.line == old.line)
  3865. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3866. else
  3867. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3868. }
  3869. // Used by replaceSelections to allow moving the selection to the
  3870. // start or around the replaced test. Hint may be "start" or "around".
  3871. function computeReplacedSel(doc, changes, hint) {
  3872. var out = [];
  3873. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3874. for (var i = 0; i < changes.length; i++) {
  3875. var change = changes[i];
  3876. var from = offsetPos(change.from, oldPrev, newPrev);
  3877. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3878. oldPrev = change.to;
  3879. newPrev = to;
  3880. if (hint == "around") {
  3881. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3882. out[i] = new Range(inv ? to : from, inv ? from : to);
  3883. } else {
  3884. out[i] = new Range(from, from);
  3885. }
  3886. }
  3887. return new Selection(out, doc.sel.primIndex);
  3888. }
  3889. // Allow "beforeChange" event handlers to influence a change
  3890. function filterChange(doc, change, update) {
  3891. var obj = {
  3892. canceled: false,
  3893. from: change.from,
  3894. to: change.to,
  3895. text: change.text,
  3896. origin: change.origin,
  3897. cancel: function() { this.canceled = true; }
  3898. };
  3899. if (update) obj.update = function(from, to, text, origin) {
  3900. if (from) this.from = clipPos(doc, from);
  3901. if (to) this.to = clipPos(doc, to);
  3902. if (text) this.text = text;
  3903. if (origin !== undefined) this.origin = origin;
  3904. };
  3905. signal(doc, "beforeChange", doc, obj);
  3906. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3907. if (obj.canceled) return null;
  3908. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3909. }
  3910. // Apply a change to a document, and add it to the document's
  3911. // history, and propagating it to all linked documents.
  3912. function makeChange(doc, change, ignoreReadOnly) {
  3913. if (doc.cm) {
  3914. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3915. if (doc.cm.state.suppressEdits) return;
  3916. }
  3917. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3918. change = filterChange(doc, change, true);
  3919. if (!change) return;
  3920. }
  3921. // Possibly split or suppress the update based on the presence
  3922. // of read-only spans in its range.
  3923. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3924. if (split) {
  3925. for (var i = split.length - 1; i >= 0; --i)
  3926. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3927. } else {
  3928. makeChangeInner(doc, change);
  3929. }
  3930. }
  3931. function makeChangeInner(doc, change) {
  3932. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3933. var selAfter = computeSelAfterChange(doc, change);
  3934. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3935. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3936. var rebased = [];
  3937. linkedDocs(doc, function(doc, sharedHist) {
  3938. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3939. rebaseHist(doc.history, change);
  3940. rebased.push(doc.history);
  3941. }
  3942. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3943. });
  3944. }
  3945. // Revert a change stored in a document's history.
  3946. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3947. if (doc.cm && doc.cm.state.suppressEdits) return;
  3948. var hist = doc.history, event, selAfter = doc.sel;
  3949. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3950. // Verify that there is a useable event (so that ctrl-z won't
  3951. // needlessly clear selection events)
  3952. for (var i = 0; i < source.length; i++) {
  3953. event = source[i];
  3954. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3955. break;
  3956. }
  3957. if (i == source.length) return;
  3958. hist.lastOrigin = hist.lastSelOrigin = null;
  3959. for (;;) {
  3960. event = source.pop();
  3961. if (event.ranges) {
  3962. pushSelectionToHistory(event, dest);
  3963. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3964. setSelection(doc, event, {clearRedo: false});
  3965. return;
  3966. }
  3967. selAfter = event;
  3968. }
  3969. else break;
  3970. }
  3971. // Build up a reverse change object to add to the opposite history
  3972. // stack (redo when undoing, and vice versa).
  3973. var antiChanges = [];
  3974. pushSelectionToHistory(selAfter, dest);
  3975. dest.push({changes: antiChanges, generation: hist.generation});
  3976. hist.generation = event.generation || ++hist.maxGeneration;
  3977. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3978. for (var i = event.changes.length - 1; i >= 0; --i) {
  3979. var change = event.changes[i];
  3980. change.origin = type;
  3981. if (filter && !filterChange(doc, change, false)) {
  3982. source.length = 0;
  3983. return;
  3984. }
  3985. antiChanges.push(historyChangeFromChange(doc, change));
  3986. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3987. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3988. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  3989. var rebased = [];
  3990. // Propagate to the linked documents
  3991. linkedDocs(doc, function(doc, sharedHist) {
  3992. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3993. rebaseHist(doc.history, change);
  3994. rebased.push(doc.history);
  3995. }
  3996. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  3997. });
  3998. }
  3999. }
  4000. // Sub-views need their line numbers shifted when text is added
  4001. // above or below them in the parent document.
  4002. function shiftDoc(doc, distance) {
  4003. if (distance == 0) return;
  4004. doc.first += distance;
  4005. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  4006. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  4007. Pos(range.head.line + distance, range.head.ch));
  4008. }), doc.sel.primIndex);
  4009. if (doc.cm) {
  4010. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4011. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4012. regLineChange(doc.cm, l, "gutter");
  4013. }
  4014. }
  4015. // More lower-level change function, handling only a single document
  4016. // (not linked ones).
  4017. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4018. if (doc.cm && !doc.cm.curOp)
  4019. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  4020. if (change.to.line < doc.first) {
  4021. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4022. return;
  4023. }
  4024. if (change.from.line > doc.lastLine()) return;
  4025. // Clip the change to the size of this doc
  4026. if (change.from.line < doc.first) {
  4027. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4028. shiftDoc(doc, shift);
  4029. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4030. text: [lst(change.text)], origin: change.origin};
  4031. }
  4032. var last = doc.lastLine();
  4033. if (change.to.line > last) {
  4034. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4035. text: [change.text[0]], origin: change.origin};
  4036. }
  4037. change.removed = getBetween(doc, change.from, change.to);
  4038. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  4039. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  4040. else updateDoc(doc, change, spans);
  4041. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4042. }
  4043. // Handle the interaction of a change to a document with the editor
  4044. // that this document is part of.
  4045. function makeChangeSingleDocInEditor(cm, change, spans) {
  4046. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4047. var recomputeMaxLength = false, checkWidthStart = from.line;
  4048. if (!cm.options.lineWrapping) {
  4049. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4050. doc.iter(checkWidthStart, to.line + 1, function(line) {
  4051. if (line == display.maxLine) {
  4052. recomputeMaxLength = true;
  4053. return true;
  4054. }
  4055. });
  4056. }
  4057. if (doc.sel.contains(change.from, change.to) > -1)
  4058. signalCursorActivity(cm);
  4059. updateDoc(doc, change, spans, estimateHeight(cm));
  4060. if (!cm.options.lineWrapping) {
  4061. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  4062. var len = lineLength(line);
  4063. if (len > display.maxLineLength) {
  4064. display.maxLine = line;
  4065. display.maxLineLength = len;
  4066. display.maxLineChanged = true;
  4067. recomputeMaxLength = false;
  4068. }
  4069. });
  4070. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  4071. }
  4072. // Adjust frontier, schedule worker
  4073. doc.frontier = Math.min(doc.frontier, from.line);
  4074. startWorker(cm, 400);
  4075. var lendiff = change.text.length - (to.line - from.line) - 1;
  4076. // Remember that these lines changed, for updating the display
  4077. if (change.full)
  4078. regChange(cm);
  4079. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4080. regLineChange(cm, from.line, "text");
  4081. else
  4082. regChange(cm, from.line, to.line + 1, lendiff);
  4083. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4084. if (changeHandler || changesHandler) {
  4085. var obj = {
  4086. from: from, to: to,
  4087. text: change.text,
  4088. removed: change.removed,
  4089. origin: change.origin
  4090. };
  4091. if (changeHandler) signalLater(cm, "change", cm, obj);
  4092. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  4093. }
  4094. cm.display.selForContextMenu = null;
  4095. }
  4096. function replaceRange(doc, code, from, to, origin) {
  4097. if (!to) to = from;
  4098. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  4099. if (typeof code == "string") code = doc.splitLines(code);
  4100. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4101. }
  4102. // SCROLLING THINGS INTO VIEW
  4103. // If an editor sits on the top or bottom of the window, partially
  4104. // scrolled out of view, this ensures that the cursor is visible.
  4105. function maybeScrollWindow(cm, coords) {
  4106. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  4107. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4108. if (coords.top + box.top < 0) doScroll = true;
  4109. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  4110. if (doScroll != null && !phantom) {
  4111. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  4112. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  4113. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  4114. coords.left + "px; width: 2px;");
  4115. cm.display.lineSpace.appendChild(scrollNode);
  4116. scrollNode.scrollIntoView(doScroll);
  4117. cm.display.lineSpace.removeChild(scrollNode);
  4118. }
  4119. }
  4120. // Scroll a given position into view (immediately), verifying that
  4121. // it actually became visible (as line heights are accurately
  4122. // measured, the position of something may 'drift' during drawing).
  4123. function scrollPosIntoView(cm, pos, end, margin) {
  4124. if (margin == null) margin = 0;
  4125. for (var limit = 0; limit < 5; limit++) {
  4126. var changed = false, coords = cursorCoords(cm, pos);
  4127. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4128. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  4129. Math.min(coords.top, endCoords.top) - margin,
  4130. Math.max(coords.left, endCoords.left),
  4131. Math.max(coords.bottom, endCoords.bottom) + margin);
  4132. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4133. if (scrollPos.scrollTop != null) {
  4134. setScrollTop(cm, scrollPos.scrollTop);
  4135. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  4136. }
  4137. if (scrollPos.scrollLeft != null) {
  4138. setScrollLeft(cm, scrollPos.scrollLeft);
  4139. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  4140. }
  4141. if (!changed) break;
  4142. }
  4143. return coords;
  4144. }
  4145. // Scroll a given set of coordinates into view (immediately).
  4146. function scrollIntoView(cm, x1, y1, x2, y2) {
  4147. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  4148. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  4149. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  4150. }
  4151. // Calculate a new scroll position needed to scroll the given
  4152. // rectangle into view. Returns an object with scrollTop and
  4153. // scrollLeft properties. When these are undefined, the
  4154. // vertical/horizontal position does not need to be adjusted.
  4155. function calculateScrollPos(cm, x1, y1, x2, y2) {
  4156. var display = cm.display, snapMargin = textHeight(cm.display);
  4157. if (y1 < 0) y1 = 0;
  4158. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4159. var screen = displayHeight(cm), result = {};
  4160. if (y2 - y1 > screen) y2 = y1 + screen;
  4161. var docBottom = cm.doc.height + paddingVert(display);
  4162. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4163. if (y1 < screentop) {
  4164. result.scrollTop = atTop ? 0 : y1;
  4165. } else if (y2 > screentop + screen) {
  4166. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4167. if (newTop != screentop) result.scrollTop = newTop;
  4168. }
  4169. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4170. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4171. var tooWide = x2 - x1 > screenw;
  4172. if (tooWide) x2 = x1 + screenw;
  4173. if (x1 < 10)
  4174. result.scrollLeft = 0;
  4175. else if (x1 < screenleft)
  4176. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4177. else if (x2 > screenw + screenleft - 3)
  4178. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4179. return result;
  4180. }
  4181. // Store a relative adjustment to the scroll position in the current
  4182. // operation (to be applied when the operation finishes).
  4183. function addToScrollPos(cm, left, top) {
  4184. if (left != null || top != null) resolveScrollToPos(cm);
  4185. if (left != null)
  4186. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4187. if (top != null)
  4188. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4189. }
  4190. // Make sure that at the end of the operation the current cursor is
  4191. // shown.
  4192. function ensureCursorVisible(cm) {
  4193. resolveScrollToPos(cm);
  4194. var cur = cm.getCursor(), from = cur, to = cur;
  4195. if (!cm.options.lineWrapping) {
  4196. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4197. to = Pos(cur.line, cur.ch + 1);
  4198. }
  4199. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  4200. }
  4201. // When an operation has its scrollToPos property set, and another
  4202. // scroll action is applied before the end of the operation, this
  4203. // 'simulates' scrolling that position into view in a cheap way, so
  4204. // that the effect of intermediate scroll commands is not ignored.
  4205. function resolveScrollToPos(cm) {
  4206. var range = cm.curOp.scrollToPos;
  4207. if (range) {
  4208. cm.curOp.scrollToPos = null;
  4209. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4210. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4211. Math.min(from.top, to.top) - range.margin,
  4212. Math.max(from.right, to.right),
  4213. Math.max(from.bottom, to.bottom) + range.margin);
  4214. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4215. }
  4216. }
  4217. // API UTILITIES
  4218. // Indent the given line. The how parameter can be "smart",
  4219. // "add"/null, "subtract", or "prev". When aggressive is false
  4220. // (typically set to true for forced single-line indents), empty
  4221. // lines are not indented, and places where the mode returns Pass
  4222. // are left alone.
  4223. function indentLine(cm, n, how, aggressive) {
  4224. var doc = cm.doc, state;
  4225. if (how == null) how = "add";
  4226. if (how == "smart") {
  4227. // Fall back to "prev" when the mode doesn't have an indentation
  4228. // method.
  4229. if (!doc.mode.indent) how = "prev";
  4230. else state = getStateBefore(cm, n);
  4231. }
  4232. var tabSize = cm.options.tabSize;
  4233. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4234. if (line.stateAfter) line.stateAfter = null;
  4235. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4236. if (!aggressive && !/\S/.test(line.text)) {
  4237. indentation = 0;
  4238. how = "not";
  4239. } else if (how == "smart") {
  4240. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4241. if (indentation == Pass || indentation > 150) {
  4242. if (!aggressive) return;
  4243. how = "prev";
  4244. }
  4245. }
  4246. if (how == "prev") {
  4247. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  4248. else indentation = 0;
  4249. } else if (how == "add") {
  4250. indentation = curSpace + cm.options.indentUnit;
  4251. } else if (how == "subtract") {
  4252. indentation = curSpace - cm.options.indentUnit;
  4253. } else if (typeof how == "number") {
  4254. indentation = curSpace + how;
  4255. }
  4256. indentation = Math.max(0, indentation);
  4257. var indentString = "", pos = 0;
  4258. if (cm.options.indentWithTabs)
  4259. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  4260. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4261. if (indentString != curSpaceString) {
  4262. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4263. line.stateAfter = null;
  4264. return true;
  4265. } else {
  4266. // Ensure that, if the cursor was in the whitespace at the start
  4267. // of the line, it is moved to the end of that space.
  4268. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4269. var range = doc.sel.ranges[i];
  4270. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4271. var pos = Pos(n, curSpaceString.length);
  4272. replaceOneSelection(doc, i, new Range(pos, pos));
  4273. break;
  4274. }
  4275. }
  4276. }
  4277. }
  4278. // Utility for applying a change to a line by handle or number,
  4279. // returning the number and optionally registering the line as
  4280. // changed.
  4281. function changeLine(doc, handle, changeType, op) {
  4282. var no = handle, line = handle;
  4283. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4284. else no = lineNo(handle);
  4285. if (no == null) return null;
  4286. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4287. return line;
  4288. }
  4289. // Helper for deleting text near the selection(s), used to implement
  4290. // backspace, delete, and similar functionality.
  4291. function deleteNearSelection(cm, compute) {
  4292. var ranges = cm.doc.sel.ranges, kill = [];
  4293. // Build up a set of ranges to kill first, merging overlapping
  4294. // ranges.
  4295. for (var i = 0; i < ranges.length; i++) {
  4296. var toKill = compute(ranges[i]);
  4297. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4298. var replaced = kill.pop();
  4299. if (cmp(replaced.from, toKill.from) < 0) {
  4300. toKill.from = replaced.from;
  4301. break;
  4302. }
  4303. }
  4304. kill.push(toKill);
  4305. }
  4306. // Next, remove those actual ranges.
  4307. runInOp(cm, function() {
  4308. for (var i = kill.length - 1; i >= 0; i--)
  4309. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4310. ensureCursorVisible(cm);
  4311. });
  4312. }
  4313. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4314. // right), unit can be "char", "column" (like char, but doesn't
  4315. // cross line boundaries), "word" (across next word), or "group" (to
  4316. // the start of next group of word or non-word-non-whitespace
  4317. // chars). The visually param controls whether, in right-to-left
  4318. // text, direction 1 means to move towards the next index in the
  4319. // string, or towards the character to the right of the current
  4320. // position. The resulting position will have a hitSide=true
  4321. // property if it reached the end of the document.
  4322. function findPosH(doc, pos, dir, unit, visually) {
  4323. var line = pos.line, ch = pos.ch, origDir = dir;
  4324. var lineObj = getLine(doc, line);
  4325. function findNextLine() {
  4326. var l = line + dir;
  4327. if (l < doc.first || l >= doc.first + doc.size) return false
  4328. line = l;
  4329. return lineObj = getLine(doc, l);
  4330. }
  4331. function moveOnce(boundToLine) {
  4332. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4333. if (next == null) {
  4334. if (!boundToLine && findNextLine()) {
  4335. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4336. else ch = dir < 0 ? lineObj.text.length : 0;
  4337. } else return false
  4338. } else ch = next;
  4339. return true;
  4340. }
  4341. if (unit == "char") {
  4342. moveOnce()
  4343. } else if (unit == "column") {
  4344. moveOnce(true)
  4345. } else if (unit == "word" || unit == "group") {
  4346. var sawType = null, group = unit == "group";
  4347. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4348. for (var first = true;; first = false) {
  4349. if (dir < 0 && !moveOnce(!first)) break;
  4350. var cur = lineObj.text.charAt(ch) || "\n";
  4351. var type = isWordChar(cur, helper) ? "w"
  4352. : group && cur == "\n" ? "n"
  4353. : !group || /\s/.test(cur) ? null
  4354. : "p";
  4355. if (group && !first && !type) type = "s";
  4356. if (sawType && sawType != type) {
  4357. if (dir < 0) {dir = 1; moveOnce();}
  4358. break;
  4359. }
  4360. if (type) sawType = type;
  4361. if (dir > 0 && !moveOnce(!first)) break;
  4362. }
  4363. }
  4364. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
  4365. if (!cmp(pos, result)) result.hitSide = true;
  4366. return result;
  4367. }
  4368. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4369. // "page" or "line". The resulting position will have a hitSide=true
  4370. // property if it reached the end of the document.
  4371. function findPosV(cm, pos, dir, unit) {
  4372. var doc = cm.doc, x = pos.left, y;
  4373. if (unit == "page") {
  4374. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4375. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4376. } else if (unit == "line") {
  4377. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4378. }
  4379. for (;;) {
  4380. var target = coordsChar(cm, x, y);
  4381. if (!target.outside) break;
  4382. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4383. y += dir * 5;
  4384. }
  4385. return target;
  4386. }
  4387. // EDITOR METHODS
  4388. // The publicly visible API. Note that methodOp(f) means
  4389. // 'wrap f in an operation, performed on its `this` parameter'.
  4390. // This is not the complete set of editor methods. Most of the
  4391. // methods defined on the Doc type are also injected into
  4392. // CodeMirror.prototype, for backwards compatibility and
  4393. // convenience.
  4394. CodeMirror.prototype = {
  4395. constructor: CodeMirror,
  4396. focus: function(){window.focus(); this.display.input.focus();},
  4397. setOption: function(option, value) {
  4398. var options = this.options, old = options[option];
  4399. if (options[option] == value && option != "mode") return;
  4400. options[option] = value;
  4401. if (optionHandlers.hasOwnProperty(option))
  4402. operation(this, optionHandlers[option])(this, value, old);
  4403. },
  4404. getOption: function(option) {return this.options[option];},
  4405. getDoc: function() {return this.doc;},
  4406. addKeyMap: function(map, bottom) {
  4407. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4408. },
  4409. removeKeyMap: function(map) {
  4410. var maps = this.state.keyMaps;
  4411. for (var i = 0; i < maps.length; ++i)
  4412. if (maps[i] == map || maps[i].name == map) {
  4413. maps.splice(i, 1);
  4414. return true;
  4415. }
  4416. },
  4417. addOverlay: methodOp(function(spec, options) {
  4418. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4419. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4420. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  4421. this.state.modeGen++;
  4422. regChange(this);
  4423. }),
  4424. removeOverlay: methodOp(function(spec) {
  4425. var overlays = this.state.overlays;
  4426. for (var i = 0; i < overlays.length; ++i) {
  4427. var cur = overlays[i].modeSpec;
  4428. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4429. overlays.splice(i, 1);
  4430. this.state.modeGen++;
  4431. regChange(this);
  4432. return;
  4433. }
  4434. }
  4435. }),
  4436. indentLine: methodOp(function(n, dir, aggressive) {
  4437. if (typeof dir != "string" && typeof dir != "number") {
  4438. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4439. else dir = dir ? "add" : "subtract";
  4440. }
  4441. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4442. }),
  4443. indentSelection: methodOp(function(how) {
  4444. var ranges = this.doc.sel.ranges, end = -1;
  4445. for (var i = 0; i < ranges.length; i++) {
  4446. var range = ranges[i];
  4447. if (!range.empty()) {
  4448. var from = range.from(), to = range.to();
  4449. var start = Math.max(end, from.line);
  4450. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4451. for (var j = start; j < end; ++j)
  4452. indentLine(this, j, how);
  4453. var newRanges = this.doc.sel.ranges;
  4454. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4455. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4456. } else if (range.head.line > end) {
  4457. indentLine(this, range.head.line, how, true);
  4458. end = range.head.line;
  4459. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4460. }
  4461. }
  4462. }),
  4463. // Fetch the parser token for a given character. Useful for hacks
  4464. // that want to inspect the mode state (say, for completion).
  4465. getTokenAt: function(pos, precise) {
  4466. return takeToken(this, pos, precise);
  4467. },
  4468. getLineTokens: function(line, precise) {
  4469. return takeToken(this, Pos(line), precise, true);
  4470. },
  4471. getTokenTypeAt: function(pos) {
  4472. pos = clipPos(this.doc, pos);
  4473. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4474. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4475. var type;
  4476. if (ch == 0) type = styles[2];
  4477. else for (;;) {
  4478. var mid = (before + after) >> 1;
  4479. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4480. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4481. else { type = styles[mid * 2 + 2]; break; }
  4482. }
  4483. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4484. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4485. },
  4486. getModeAt: function(pos) {
  4487. var mode = this.doc.mode;
  4488. if (!mode.innerMode) return mode;
  4489. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4490. },
  4491. getHelper: function(pos, type) {
  4492. return this.getHelpers(pos, type)[0];
  4493. },
  4494. getHelpers: function(pos, type) {
  4495. var found = [];
  4496. if (!helpers.hasOwnProperty(type)) return found;
  4497. var help = helpers[type], mode = this.getModeAt(pos);
  4498. if (typeof mode[type] == "string") {
  4499. if (help[mode[type]]) found.push(help[mode[type]]);
  4500. } else if (mode[type]) {
  4501. for (var i = 0; i < mode[type].length; i++) {
  4502. var val = help[mode[type][i]];
  4503. if (val) found.push(val);
  4504. }
  4505. } else if (mode.helperType && help[mode.helperType]) {
  4506. found.push(help[mode.helperType]);
  4507. } else if (help[mode.name]) {
  4508. found.push(help[mode.name]);
  4509. }
  4510. for (var i = 0; i < help._global.length; i++) {
  4511. var cur = help._global[i];
  4512. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4513. found.push(cur.val);
  4514. }
  4515. return found;
  4516. },
  4517. getStateAfter: function(line, precise) {
  4518. var doc = this.doc;
  4519. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  4520. return getStateBefore(this, line + 1, precise);
  4521. },
  4522. cursorCoords: function(start, mode) {
  4523. var pos, range = this.doc.sel.primary();
  4524. if (start == null) pos = range.head;
  4525. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4526. else pos = start ? range.from() : range.to();
  4527. return cursorCoords(this, pos, mode || "page");
  4528. },
  4529. charCoords: function(pos, mode) {
  4530. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4531. },
  4532. coordsChar: function(coords, mode) {
  4533. coords = fromCoordSystem(this, coords, mode || "page");
  4534. return coordsChar(this, coords.left, coords.top);
  4535. },
  4536. lineAtHeight: function(height, mode) {
  4537. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  4538. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4539. },
  4540. heightAtLine: function(line, mode) {
  4541. var end = false, lineObj;
  4542. if (typeof line == "number") {
  4543. var last = this.doc.first + this.doc.size - 1;
  4544. if (line < this.doc.first) line = this.doc.first;
  4545. else if (line > last) { line = last; end = true; }
  4546. lineObj = getLine(this.doc, line);
  4547. } else {
  4548. lineObj = line;
  4549. }
  4550. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  4551. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4552. },
  4553. defaultTextHeight: function() { return textHeight(this.display); },
  4554. defaultCharWidth: function() { return charWidth(this.display); },
  4555. setGutterMarker: methodOp(function(line, gutterID, value) {
  4556. return changeLine(this.doc, line, "gutter", function(line) {
  4557. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4558. markers[gutterID] = value;
  4559. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4560. return true;
  4561. });
  4562. }),
  4563. clearGutter: methodOp(function(gutterID) {
  4564. var cm = this, doc = cm.doc, i = doc.first;
  4565. doc.iter(function(line) {
  4566. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4567. line.gutterMarkers[gutterID] = null;
  4568. regLineChange(cm, i, "gutter");
  4569. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4570. }
  4571. ++i;
  4572. });
  4573. }),
  4574. lineInfo: function(line) {
  4575. if (typeof line == "number") {
  4576. if (!isLine(this.doc, line)) return null;
  4577. var n = line;
  4578. line = getLine(this.doc, line);
  4579. if (!line) return null;
  4580. } else {
  4581. var n = lineNo(line);
  4582. if (n == null) return null;
  4583. }
  4584. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4585. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4586. widgets: line.widgets};
  4587. },
  4588. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  4589. addWidget: function(pos, node, scroll, vert, horiz) {
  4590. var display = this.display;
  4591. pos = cursorCoords(this, clipPos(this.doc, pos));
  4592. var top = pos.bottom, left = pos.left;
  4593. node.style.position = "absolute";
  4594. node.setAttribute("cm-ignore-events", "true");
  4595. this.display.input.setUneditable(node);
  4596. display.sizer.appendChild(node);
  4597. if (vert == "over") {
  4598. top = pos.top;
  4599. } else if (vert == "above" || vert == "near") {
  4600. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4601. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4602. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4603. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4604. top = pos.top - node.offsetHeight;
  4605. else if (pos.bottom + node.offsetHeight <= vspace)
  4606. top = pos.bottom;
  4607. if (left + node.offsetWidth > hspace)
  4608. left = hspace - node.offsetWidth;
  4609. }
  4610. node.style.top = top + "px";
  4611. node.style.left = node.style.right = "";
  4612. if (horiz == "right") {
  4613. left = display.sizer.clientWidth - node.offsetWidth;
  4614. node.style.right = "0px";
  4615. } else {
  4616. if (horiz == "left") left = 0;
  4617. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4618. node.style.left = left + "px";
  4619. }
  4620. if (scroll)
  4621. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4622. },
  4623. triggerOnKeyDown: methodOp(onKeyDown),
  4624. triggerOnKeyPress: methodOp(onKeyPress),
  4625. triggerOnKeyUp: onKeyUp,
  4626. execCommand: function(cmd) {
  4627. if (commands.hasOwnProperty(cmd))
  4628. return commands[cmd].call(null, this);
  4629. },
  4630. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  4631. findPosH: function(from, amount, unit, visually) {
  4632. var dir = 1;
  4633. if (amount < 0) { dir = -1; amount = -amount; }
  4634. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4635. cur = findPosH(this.doc, cur, dir, unit, visually);
  4636. if (cur.hitSide) break;
  4637. }
  4638. return cur;
  4639. },
  4640. moveH: methodOp(function(dir, unit) {
  4641. var cm = this;
  4642. cm.extendSelectionsBy(function(range) {
  4643. if (cm.display.shift || cm.doc.extend || range.empty())
  4644. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4645. else
  4646. return dir < 0 ? range.from() : range.to();
  4647. }, sel_move);
  4648. }),
  4649. deleteH: methodOp(function(dir, unit) {
  4650. var sel = this.doc.sel, doc = this.doc;
  4651. if (sel.somethingSelected())
  4652. doc.replaceSelection("", null, "+delete");
  4653. else
  4654. deleteNearSelection(this, function(range) {
  4655. var other = findPosH(doc, range.head, dir, unit, false);
  4656. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4657. });
  4658. }),
  4659. findPosV: function(from, amount, unit, goalColumn) {
  4660. var dir = 1, x = goalColumn;
  4661. if (amount < 0) { dir = -1; amount = -amount; }
  4662. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4663. var coords = cursorCoords(this, cur, "div");
  4664. if (x == null) x = coords.left;
  4665. else coords.left = x;
  4666. cur = findPosV(this, coords, dir, unit);
  4667. if (cur.hitSide) break;
  4668. }
  4669. return cur;
  4670. },
  4671. moveV: methodOp(function(dir, unit) {
  4672. var cm = this, doc = this.doc, goals = [];
  4673. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4674. doc.extendSelectionsBy(function(range) {
  4675. if (collapse)
  4676. return dir < 0 ? range.from() : range.to();
  4677. var headPos = cursorCoords(cm, range.head, "div");
  4678. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4679. goals.push(headPos.left);
  4680. var pos = findPosV(cm, headPos, dir, unit);
  4681. if (unit == "page" && range == doc.sel.primary())
  4682. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4683. return pos;
  4684. }, sel_move);
  4685. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4686. doc.sel.ranges[i].goalColumn = goals[i];
  4687. }),
  4688. // Find the word at the given position (as returned by coordsChar).
  4689. findWordAt: function(pos) {
  4690. var doc = this.doc, line = getLine(doc, pos.line).text;
  4691. var start = pos.ch, end = pos.ch;
  4692. if (line) {
  4693. var helper = this.getHelper(pos, "wordChars");
  4694. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4695. var startChar = line.charAt(start);
  4696. var check = isWordChar(startChar, helper)
  4697. ? function(ch) { return isWordChar(ch, helper); }
  4698. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4699. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4700. while (start > 0 && check(line.charAt(start - 1))) --start;
  4701. while (end < line.length && check(line.charAt(end))) ++end;
  4702. }
  4703. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4704. },
  4705. toggleOverwrite: function(value) {
  4706. if (value != null && value == this.state.overwrite) return;
  4707. if (this.state.overwrite = !this.state.overwrite)
  4708. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4709. else
  4710. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4711. signal(this, "overwriteToggle", this, this.state.overwrite);
  4712. },
  4713. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  4714. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  4715. scrollTo: methodOp(function(x, y) {
  4716. if (x != null || y != null) resolveScrollToPos(this);
  4717. if (x != null) this.curOp.scrollLeft = x;
  4718. if (y != null) this.curOp.scrollTop = y;
  4719. }),
  4720. getScrollInfo: function() {
  4721. var scroller = this.display.scroller;
  4722. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4723. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4724. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4725. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4726. },
  4727. scrollIntoView: methodOp(function(range, margin) {
  4728. if (range == null) {
  4729. range = {from: this.doc.sel.primary().head, to: null};
  4730. if (margin == null) margin = this.options.cursorScrollMargin;
  4731. } else if (typeof range == "number") {
  4732. range = {from: Pos(range, 0), to: null};
  4733. } else if (range.from == null) {
  4734. range = {from: range, to: null};
  4735. }
  4736. if (!range.to) range.to = range.from;
  4737. range.margin = margin || 0;
  4738. if (range.from.line != null) {
  4739. resolveScrollToPos(this);
  4740. this.curOp.scrollToPos = range;
  4741. } else {
  4742. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4743. Math.min(range.from.top, range.to.top) - range.margin,
  4744. Math.max(range.from.right, range.to.right),
  4745. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4746. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4747. }
  4748. }),
  4749. setSize: methodOp(function(width, height) {
  4750. var cm = this;
  4751. function interpret(val) {
  4752. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4753. }
  4754. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4755. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4756. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4757. var lineNo = cm.display.viewFrom;
  4758. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4759. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4760. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4761. ++lineNo;
  4762. });
  4763. cm.curOp.forceUpdate = true;
  4764. signal(cm, "refresh", this);
  4765. }),
  4766. operation: function(f){return runInOp(this, f);},
  4767. refresh: methodOp(function() {
  4768. var oldHeight = this.display.cachedTextHeight;
  4769. regChange(this);
  4770. this.curOp.forceUpdate = true;
  4771. clearCaches(this);
  4772. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4773. updateGutterSpace(this);
  4774. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4775. estimateLineHeights(this);
  4776. signal(this, "refresh", this);
  4777. }),
  4778. swapDoc: methodOp(function(doc) {
  4779. var old = this.doc;
  4780. old.cm = null;
  4781. attachDoc(this, doc);
  4782. clearCaches(this);
  4783. this.display.input.reset();
  4784. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4785. this.curOp.forceScroll = true;
  4786. signalLater(this, "swapDoc", this, old);
  4787. return old;
  4788. }),
  4789. getInputField: function(){return this.display.input.getField();},
  4790. getWrapperElement: function(){return this.display.wrapper;},
  4791. getScrollerElement: function(){return this.display.scroller;},
  4792. getGutterElement: function(){return this.display.gutters;}
  4793. };
  4794. eventMixin(CodeMirror);
  4795. // OPTION DEFAULTS
  4796. // The default configuration options.
  4797. var defaults = CodeMirror.defaults = {};
  4798. // Functions to run when options are changed.
  4799. var optionHandlers = CodeMirror.optionHandlers = {};
  4800. function option(name, deflt, handle, notOnInit) {
  4801. CodeMirror.defaults[name] = deflt;
  4802. if (handle) optionHandlers[name] =
  4803. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4804. }
  4805. // Passed to option handlers when there is no old value.
  4806. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4807. // These two are, on init, called from the constructor because they
  4808. // have to be initialized before the editor can start at all.
  4809. option("value", "", function(cm, val) {
  4810. cm.setValue(val);
  4811. }, true);
  4812. option("mode", null, function(cm, val) {
  4813. cm.doc.modeOption = val;
  4814. loadMode(cm);
  4815. }, true);
  4816. option("indentUnit", 2, loadMode, true);
  4817. option("indentWithTabs", false);
  4818. option("smartIndent", true);
  4819. option("tabSize", 4, function(cm) {
  4820. resetModeState(cm);
  4821. clearCaches(cm);
  4822. regChange(cm);
  4823. }, true);
  4824. option("lineSeparator", null, function(cm, val) {
  4825. cm.doc.lineSep = val;
  4826. if (!val) return;
  4827. var newBreaks = [], lineNo = cm.doc.first;
  4828. cm.doc.iter(function(line) {
  4829. for (var pos = 0;;) {
  4830. var found = line.text.indexOf(val, pos);
  4831. if (found == -1) break;
  4832. pos = found + val.length;
  4833. newBreaks.push(Pos(lineNo, found));
  4834. }
  4835. lineNo++;
  4836. });
  4837. for (var i = newBreaks.length - 1; i >= 0; i--)
  4838. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  4839. });
  4840. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  4841. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4842. if (old != CodeMirror.Init) cm.refresh();
  4843. });
  4844. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4845. option("electricChars", true);
  4846. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  4847. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4848. }, true);
  4849. option("rtlMoveVisually", !windows);
  4850. option("wholeLineUpdateBefore", true);
  4851. option("theme", "default", function(cm) {
  4852. themeChanged(cm);
  4853. guttersChanged(cm);
  4854. }, true);
  4855. option("keyMap", "default", function(cm, val, old) {
  4856. var next = getKeyMap(val);
  4857. var prev = old != CodeMirror.Init && getKeyMap(old);
  4858. if (prev && prev.detach) prev.detach(cm, next);
  4859. if (next.attach) next.attach(cm, prev || null);
  4860. });
  4861. option("extraKeys", null);
  4862. option("lineWrapping", false, wrappingChanged, true);
  4863. option("gutters", [], function(cm) {
  4864. setGuttersForLineNumbers(cm.options);
  4865. guttersChanged(cm);
  4866. }, true);
  4867. option("fixedGutter", true, function(cm, val) {
  4868. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4869. cm.refresh();
  4870. }, true);
  4871. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4872. option("scrollbarStyle", "native", function(cm) {
  4873. initScrollbars(cm);
  4874. updateScrollbars(cm);
  4875. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4876. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4877. }, true);
  4878. option("lineNumbers", false, function(cm) {
  4879. setGuttersForLineNumbers(cm.options);
  4880. guttersChanged(cm);
  4881. }, true);
  4882. option("firstLineNumber", 1, guttersChanged, true);
  4883. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4884. option("showCursorWhenSelecting", false, updateSelection, true);
  4885. option("resetSelectionOnContextMenu", true);
  4886. option("lineWiseCopyCut", true);
  4887. option("readOnly", false, function(cm, val) {
  4888. if (val == "nocursor") {
  4889. onBlur(cm);
  4890. cm.display.input.blur();
  4891. cm.display.disabled = true;
  4892. } else {
  4893. cm.display.disabled = false;
  4894. }
  4895. cm.display.input.readOnlyChanged(val)
  4896. });
  4897. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  4898. option("dragDrop", true, dragDropChanged);
  4899. option("allowDropFileTypes", null);
  4900. option("cursorBlinkRate", 530);
  4901. option("cursorScrollMargin", 0);
  4902. option("cursorHeight", 1, updateSelection, true);
  4903. option("singleCursorHeightPerLine", true, updateSelection, true);
  4904. option("workTime", 100);
  4905. option("workDelay", 100);
  4906. option("flattenSpans", true, resetModeState, true);
  4907. option("addModeClass", false, resetModeState, true);
  4908. option("pollInterval", 100);
  4909. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4910. option("historyEventDelay", 1250);
  4911. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4912. option("maxHighlightLength", 10000, resetModeState, true);
  4913. option("moveInputWithCursor", true, function(cm, val) {
  4914. if (!val) cm.display.input.resetPosition();
  4915. });
  4916. option("tabindex", null, function(cm, val) {
  4917. cm.display.input.getField().tabIndex = val || "";
  4918. });
  4919. option("autofocus", null);
  4920. // MODE DEFINITION AND QUERYING
  4921. // Known modes, by name and by MIME
  4922. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4923. // Extra arguments are stored as the mode's dependencies, which is
  4924. // used by (legacy) mechanisms like loadmode.js to automatically
  4925. // load a mode. (Preferred mechanism is the require/define calls.)
  4926. CodeMirror.defineMode = function(name, mode) {
  4927. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4928. if (arguments.length > 2)
  4929. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4930. modes[name] = mode;
  4931. };
  4932. CodeMirror.defineMIME = function(mime, spec) {
  4933. mimeModes[mime] = spec;
  4934. };
  4935. // Given a MIME type, a {name, ...options} config object, or a name
  4936. // string, return a mode config object.
  4937. CodeMirror.resolveMode = function(spec) {
  4938. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4939. spec = mimeModes[spec];
  4940. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4941. var found = mimeModes[spec.name];
  4942. if (typeof found == "string") found = {name: found};
  4943. spec = createObj(found, spec);
  4944. spec.name = found.name;
  4945. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4946. return CodeMirror.resolveMode("application/xml");
  4947. }
  4948. if (typeof spec == "string") return {name: spec};
  4949. else return spec || {name: "null"};
  4950. };
  4951. // Given a mode spec (anything that resolveMode accepts), find and
  4952. // initialize an actual mode object.
  4953. CodeMirror.getMode = function(options, spec) {
  4954. var spec = CodeMirror.resolveMode(spec);
  4955. var mfactory = modes[spec.name];
  4956. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4957. var modeObj = mfactory(options, spec);
  4958. if (modeExtensions.hasOwnProperty(spec.name)) {
  4959. var exts = modeExtensions[spec.name];
  4960. for (var prop in exts) {
  4961. if (!exts.hasOwnProperty(prop)) continue;
  4962. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4963. modeObj[prop] = exts[prop];
  4964. }
  4965. }
  4966. modeObj.name = spec.name;
  4967. if (spec.helperType) modeObj.helperType = spec.helperType;
  4968. if (spec.modeProps) for (var prop in spec.modeProps)
  4969. modeObj[prop] = spec.modeProps[prop];
  4970. return modeObj;
  4971. };
  4972. // Minimal default mode.
  4973. CodeMirror.defineMode("null", function() {
  4974. return {token: function(stream) {stream.skipToEnd();}};
  4975. });
  4976. CodeMirror.defineMIME("text/plain", "null");
  4977. // This can be used to attach properties to mode objects from
  4978. // outside the actual mode definition.
  4979. var modeExtensions = CodeMirror.modeExtensions = {};
  4980. CodeMirror.extendMode = function(mode, properties) {
  4981. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4982. copyObj(properties, exts);
  4983. };
  4984. // EXTENSIONS
  4985. CodeMirror.defineExtension = function(name, func) {
  4986. CodeMirror.prototype[name] = func;
  4987. };
  4988. CodeMirror.defineDocExtension = function(name, func) {
  4989. Doc.prototype[name] = func;
  4990. };
  4991. CodeMirror.defineOption = option;
  4992. var initHooks = [];
  4993. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  4994. var helpers = CodeMirror.helpers = {};
  4995. CodeMirror.registerHelper = function(type, name, value) {
  4996. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  4997. helpers[type][name] = value;
  4998. };
  4999. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  5000. CodeMirror.registerHelper(type, name, value);
  5001. helpers[type]._global.push({pred: predicate, val: value});
  5002. };
  5003. // MODE STATE HANDLING
  5004. // Utility functions for working with state. Exported because nested
  5005. // modes need to do this for their inner modes.
  5006. var copyState = CodeMirror.copyState = function(mode, state) {
  5007. if (state === true) return state;
  5008. if (mode.copyState) return mode.copyState(state);
  5009. var nstate = {};
  5010. for (var n in state) {
  5011. var val = state[n];
  5012. if (val instanceof Array) val = val.concat([]);
  5013. nstate[n] = val;
  5014. }
  5015. return nstate;
  5016. };
  5017. var startState = CodeMirror.startState = function(mode, a1, a2) {
  5018. return mode.startState ? mode.startState(a1, a2) : true;
  5019. };
  5020. // Given a mode and a state (for that mode), find the inner mode and
  5021. // state at the position that the state refers to.
  5022. CodeMirror.innerMode = function(mode, state) {
  5023. while (mode.innerMode) {
  5024. var info = mode.innerMode(state);
  5025. if (!info || info.mode == mode) break;
  5026. state = info.state;
  5027. mode = info.mode;
  5028. }
  5029. return info || {mode: mode, state: state};
  5030. };
  5031. // STANDARD COMMANDS
  5032. // Commands are parameter-less actions that can be performed on an
  5033. // editor, mostly used for keybindings.
  5034. var commands = CodeMirror.commands = {
  5035. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  5036. singleSelection: function(cm) {
  5037. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  5038. },
  5039. killLine: function(cm) {
  5040. deleteNearSelection(cm, function(range) {
  5041. if (range.empty()) {
  5042. var len = getLine(cm.doc, range.head.line).text.length;
  5043. if (range.head.ch == len && range.head.line < cm.lastLine())
  5044. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  5045. else
  5046. return {from: range.head, to: Pos(range.head.line, len)};
  5047. } else {
  5048. return {from: range.from(), to: range.to()};
  5049. }
  5050. });
  5051. },
  5052. deleteLine: function(cm) {
  5053. deleteNearSelection(cm, function(range) {
  5054. return {from: Pos(range.from().line, 0),
  5055. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  5056. });
  5057. },
  5058. delLineLeft: function(cm) {
  5059. deleteNearSelection(cm, function(range) {
  5060. return {from: Pos(range.from().line, 0), to: range.from()};
  5061. });
  5062. },
  5063. delWrappedLineLeft: function(cm) {
  5064. deleteNearSelection(cm, function(range) {
  5065. var top = cm.charCoords(range.head, "div").top + 5;
  5066. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  5067. return {from: leftPos, to: range.from()};
  5068. });
  5069. },
  5070. delWrappedLineRight: function(cm) {
  5071. deleteNearSelection(cm, function(range) {
  5072. var top = cm.charCoords(range.head, "div").top + 5;
  5073. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5074. return {from: range.from(), to: rightPos };
  5075. });
  5076. },
  5077. undo: function(cm) {cm.undo();},
  5078. redo: function(cm) {cm.redo();},
  5079. undoSelection: function(cm) {cm.undoSelection();},
  5080. redoSelection: function(cm) {cm.redoSelection();},
  5081. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  5082. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  5083. goLineStart: function(cm) {
  5084. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  5085. {origin: "+move", bias: 1});
  5086. },
  5087. goLineStartSmart: function(cm) {
  5088. cm.extendSelectionsBy(function(range) {
  5089. return lineStartSmart(cm, range.head);
  5090. }, {origin: "+move", bias: 1});
  5091. },
  5092. goLineEnd: function(cm) {
  5093. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  5094. {origin: "+move", bias: -1});
  5095. },
  5096. goLineRight: function(cm) {
  5097. cm.extendSelectionsBy(function(range) {
  5098. var top = cm.charCoords(range.head, "div").top + 5;
  5099. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5100. }, sel_move);
  5101. },
  5102. goLineLeft: function(cm) {
  5103. cm.extendSelectionsBy(function(range) {
  5104. var top = cm.charCoords(range.head, "div").top + 5;
  5105. return cm.coordsChar({left: 0, top: top}, "div");
  5106. }, sel_move);
  5107. },
  5108. goLineLeftSmart: function(cm) {
  5109. cm.extendSelectionsBy(function(range) {
  5110. var top = cm.charCoords(range.head, "div").top + 5;
  5111. var pos = cm.coordsChar({left: 0, top: top}, "div");
  5112. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  5113. return pos;
  5114. }, sel_move);
  5115. },
  5116. goLineUp: function(cm) {cm.moveV(-1, "line");},
  5117. goLineDown: function(cm) {cm.moveV(1, "line");},
  5118. goPageUp: function(cm) {cm.moveV(-1, "page");},
  5119. goPageDown: function(cm) {cm.moveV(1, "page");},
  5120. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  5121. goCharRight: function(cm) {cm.moveH(1, "char");},
  5122. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  5123. goColumnRight: function(cm) {cm.moveH(1, "column");},
  5124. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  5125. goGroupRight: function(cm) {cm.moveH(1, "group");},
  5126. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  5127. goWordRight: function(cm) {cm.moveH(1, "word");},
  5128. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  5129. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  5130. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  5131. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  5132. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  5133. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  5134. indentAuto: function(cm) {cm.indentSelection("smart");},
  5135. indentMore: function(cm) {cm.indentSelection("add");},
  5136. indentLess: function(cm) {cm.indentSelection("subtract");},
  5137. insertTab: function(cm) {cm.replaceSelection("\t");},
  5138. insertSoftTab: function(cm) {
  5139. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  5140. for (var i = 0; i < ranges.length; i++) {
  5141. var pos = ranges[i].from();
  5142. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  5143. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  5144. }
  5145. cm.replaceSelections(spaces);
  5146. },
  5147. defaultTab: function(cm) {
  5148. if (cm.somethingSelected()) cm.indentSelection("add");
  5149. else cm.execCommand("insertTab");
  5150. },
  5151. transposeChars: function(cm) {
  5152. runInOp(cm, function() {
  5153. var ranges = cm.listSelections(), newSel = [];
  5154. for (var i = 0; i < ranges.length; i++) {
  5155. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  5156. if (line) {
  5157. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  5158. if (cur.ch > 0) {
  5159. cur = new Pos(cur.line, cur.ch + 1);
  5160. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5161. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  5162. } else if (cur.line > cm.doc.first) {
  5163. var prev = getLine(cm.doc, cur.line - 1).text;
  5164. if (prev)
  5165. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  5166. prev.charAt(prev.length - 1),
  5167. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  5168. }
  5169. }
  5170. newSel.push(new Range(cur, cur));
  5171. }
  5172. cm.setSelections(newSel);
  5173. });
  5174. },
  5175. newlineAndIndent: function(cm) {
  5176. runInOp(cm, function() {
  5177. var len = cm.listSelections().length;
  5178. for (var i = 0; i < len; i++) {
  5179. var range = cm.listSelections()[i];
  5180. cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
  5181. cm.indentLine(range.from().line + 1, null, true);
  5182. }
  5183. ensureCursorVisible(cm);
  5184. });
  5185. },
  5186. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  5187. };
  5188. // STANDARD KEYMAPS
  5189. var keyMap = CodeMirror.keyMap = {};
  5190. keyMap.basic = {
  5191. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5192. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5193. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5194. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5195. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5196. "Esc": "singleSelection"
  5197. };
  5198. // Note that the save and find-related commands aren't defined by
  5199. // default. User code or addons can define them. Unknown commands
  5200. // are simply ignored.
  5201. keyMap.pcDefault = {
  5202. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5203. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5204. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5205. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5206. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5207. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5208. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5209. fallthrough: "basic"
  5210. };
  5211. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5212. keyMap.emacsy = {
  5213. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5214. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5215. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5216. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  5217. };
  5218. keyMap.macDefault = {
  5219. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5220. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5221. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5222. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5223. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5224. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5225. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5226. fallthrough: ["basic", "emacsy"]
  5227. };
  5228. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5229. // KEYMAP DISPATCH
  5230. function normalizeKeyName(name) {
  5231. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5232. var alt, ctrl, shift, cmd;
  5233. for (var i = 0; i < parts.length - 1; i++) {
  5234. var mod = parts[i];
  5235. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5236. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5237. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5238. else if (/^s(hift)$/i.test(mod)) shift = true;
  5239. else throw new Error("Unrecognized modifier name: " + mod);
  5240. }
  5241. if (alt) name = "Alt-" + name;
  5242. if (ctrl) name = "Ctrl-" + name;
  5243. if (cmd) name = "Cmd-" + name;
  5244. if (shift) name = "Shift-" + name;
  5245. return name;
  5246. }
  5247. // This is a kludge to keep keymaps mostly working as raw objects
  5248. // (backwards compatibility) while at the same time support features
  5249. // like normalization and multi-stroke key bindings. It compiles a
  5250. // new normalized keymap, and then updates the old object to reflect
  5251. // this.
  5252. CodeMirror.normalizeKeyMap = function(keymap) {
  5253. var copy = {};
  5254. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5255. var value = keymap[keyname];
  5256. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5257. if (value == "...") { delete keymap[keyname]; continue; }
  5258. var keys = map(keyname.split(" "), normalizeKeyName);
  5259. for (var i = 0; i < keys.length; i++) {
  5260. var val, name;
  5261. if (i == keys.length - 1) {
  5262. name = keys.join(" ");
  5263. val = value;
  5264. } else {
  5265. name = keys.slice(0, i + 1).join(" ");
  5266. val = "...";
  5267. }
  5268. var prev = copy[name];
  5269. if (!prev) copy[name] = val;
  5270. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5271. }
  5272. delete keymap[keyname];
  5273. }
  5274. for (var prop in copy) keymap[prop] = copy[prop];
  5275. return keymap;
  5276. };
  5277. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  5278. map = getKeyMap(map);
  5279. var found = map.call ? map.call(key, context) : map[key];
  5280. if (found === false) return "nothing";
  5281. if (found === "...") return "multi";
  5282. if (found != null && handle(found)) return "handled";
  5283. if (map.fallthrough) {
  5284. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5285. return lookupKey(key, map.fallthrough, handle, context);
  5286. for (var i = 0; i < map.fallthrough.length; i++) {
  5287. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5288. if (result) return result;
  5289. }
  5290. }
  5291. };
  5292. // Modifier key presses don't count as 'real' key presses for the
  5293. // purpose of keymap fallthrough.
  5294. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  5295. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5296. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5297. };
  5298. // Look up the name of a key as indicated by an event object.
  5299. var keyName = CodeMirror.keyName = function(event, noShift) {
  5300. if (presto && event.keyCode == 34 && event["char"]) return false;
  5301. var base = keyNames[event.keyCode], name = base;
  5302. if (name == null || event.altGraphKey) return false;
  5303. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5304. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5305. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5306. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5307. return name;
  5308. };
  5309. function getKeyMap(val) {
  5310. return typeof val == "string" ? keyMap[val] : val;
  5311. }
  5312. // FROMTEXTAREA
  5313. CodeMirror.fromTextArea = function(textarea, options) {
  5314. options = options ? copyObj(options) : {};
  5315. options.value = textarea.value;
  5316. if (!options.tabindex && textarea.tabIndex)
  5317. options.tabindex = textarea.tabIndex;
  5318. if (!options.placeholder && textarea.placeholder)
  5319. options.placeholder = textarea.placeholder;
  5320. // Set autofocus to true if this textarea is focused, or if it has
  5321. // autofocus and no other element is focused.
  5322. if (options.autofocus == null) {
  5323. var hasFocus = activeElt();
  5324. options.autofocus = hasFocus == textarea ||
  5325. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5326. }
  5327. function save() {textarea.value = cm.getValue();}
  5328. if (textarea.form) {
  5329. on(textarea.form, "submit", save);
  5330. // Deplorable hack to make the submit method do the right thing.
  5331. if (!options.leaveSubmitMethodAlone) {
  5332. var form = textarea.form, realSubmit = form.submit;
  5333. try {
  5334. var wrappedSubmit = form.submit = function() {
  5335. save();
  5336. form.submit = realSubmit;
  5337. form.submit();
  5338. form.submit = wrappedSubmit;
  5339. };
  5340. } catch(e) {}
  5341. }
  5342. }
  5343. options.finishInit = function(cm) {
  5344. cm.save = save;
  5345. cm.getTextArea = function() { return textarea; };
  5346. cm.toTextArea = function() {
  5347. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5348. save();
  5349. textarea.parentNode.removeChild(cm.getWrapperElement());
  5350. textarea.style.display = "";
  5351. if (textarea.form) {
  5352. off(textarea.form, "submit", save);
  5353. if (typeof textarea.form.submit == "function")
  5354. textarea.form.submit = realSubmit;
  5355. }
  5356. };
  5357. };
  5358. textarea.style.display = "none";
  5359. var cm = CodeMirror(function(node) {
  5360. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5361. }, options);
  5362. return cm;
  5363. };
  5364. // STRING STREAM
  5365. // Fed to the mode parsers, provides helper functions to make
  5366. // parsers more succinct.
  5367. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  5368. this.pos = this.start = 0;
  5369. this.string = string;
  5370. this.tabSize = tabSize || 8;
  5371. this.lastColumnPos = this.lastColumnValue = 0;
  5372. this.lineStart = 0;
  5373. };
  5374. StringStream.prototype = {
  5375. eol: function() {return this.pos >= this.string.length;},
  5376. sol: function() {return this.pos == this.lineStart;},
  5377. peek: function() {return this.string.charAt(this.pos) || undefined;},
  5378. next: function() {
  5379. if (this.pos < this.string.length)
  5380. return this.string.charAt(this.pos++);
  5381. },
  5382. eat: function(match) {
  5383. var ch = this.string.charAt(this.pos);
  5384. if (typeof match == "string") var ok = ch == match;
  5385. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5386. if (ok) {++this.pos; return ch;}
  5387. },
  5388. eatWhile: function(match) {
  5389. var start = this.pos;
  5390. while (this.eat(match)){}
  5391. return this.pos > start;
  5392. },
  5393. eatSpace: function() {
  5394. var start = this.pos;
  5395. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  5396. return this.pos > start;
  5397. },
  5398. skipToEnd: function() {this.pos = this.string.length;},
  5399. skipTo: function(ch) {
  5400. var found = this.string.indexOf(ch, this.pos);
  5401. if (found > -1) {this.pos = found; return true;}
  5402. },
  5403. backUp: function(n) {this.pos -= n;},
  5404. column: function() {
  5405. if (this.lastColumnPos < this.start) {
  5406. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5407. this.lastColumnPos = this.start;
  5408. }
  5409. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5410. },
  5411. indentation: function() {
  5412. return countColumn(this.string, null, this.tabSize) -
  5413. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5414. },
  5415. match: function(pattern, consume, caseInsensitive) {
  5416. if (typeof pattern == "string") {
  5417. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  5418. var substr = this.string.substr(this.pos, pattern.length);
  5419. if (cased(substr) == cased(pattern)) {
  5420. if (consume !== false) this.pos += pattern.length;
  5421. return true;
  5422. }
  5423. } else {
  5424. var match = this.string.slice(this.pos).match(pattern);
  5425. if (match && match.index > 0) return null;
  5426. if (match && consume !== false) this.pos += match[0].length;
  5427. return match;
  5428. }
  5429. },
  5430. current: function(){return this.string.slice(this.start, this.pos);},
  5431. hideFirstChars: function(n, inner) {
  5432. this.lineStart += n;
  5433. try { return inner(); }
  5434. finally { this.lineStart -= n; }
  5435. }
  5436. };
  5437. // TEXTMARKERS
  5438. // Created with markText and setBookmark methods. A TextMarker is a
  5439. // handle that can be used to clear or find a marked position in the
  5440. // document. Line objects hold arrays (markedSpans) containing
  5441. // {from, to, marker} object pointing to such marker objects, and
  5442. // indicating that such a marker is present on that line. Multiple
  5443. // lines may point to the same marker when it spans across lines.
  5444. // The spans will have null for their from/to properties when the
  5445. // marker continues beyond the start/end of the line. Markers have
  5446. // links back to the lines they currently touch.
  5447. var nextMarkerId = 0;
  5448. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  5449. this.lines = [];
  5450. this.type = type;
  5451. this.doc = doc;
  5452. this.id = ++nextMarkerId;
  5453. };
  5454. eventMixin(TextMarker);
  5455. // Clear the marker.
  5456. TextMarker.prototype.clear = function() {
  5457. if (this.explicitlyCleared) return;
  5458. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5459. if (withOp) startOperation(cm);
  5460. if (hasHandler(this, "clear")) {
  5461. var found = this.find();
  5462. if (found) signalLater(this, "clear", found.from, found.to);
  5463. }
  5464. var min = null, max = null;
  5465. for (var i = 0; i < this.lines.length; ++i) {
  5466. var line = this.lines[i];
  5467. var span = getMarkedSpanFor(line.markedSpans, this);
  5468. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5469. else if (cm) {
  5470. if (span.to != null) max = lineNo(line);
  5471. if (span.from != null) min = lineNo(line);
  5472. }
  5473. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5474. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5475. updateLineHeight(line, textHeight(cm.display));
  5476. }
  5477. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5478. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5479. if (len > cm.display.maxLineLength) {
  5480. cm.display.maxLine = visual;
  5481. cm.display.maxLineLength = len;
  5482. cm.display.maxLineChanged = true;
  5483. }
  5484. }
  5485. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5486. this.lines.length = 0;
  5487. this.explicitlyCleared = true;
  5488. if (this.atomic && this.doc.cantEdit) {
  5489. this.doc.cantEdit = false;
  5490. if (cm) reCheckSelection(cm.doc);
  5491. }
  5492. if (cm) signalLater(cm, "markerCleared", cm, this);
  5493. if (withOp) endOperation(cm);
  5494. if (this.parent) this.parent.clear();
  5495. };
  5496. // Find the position of the marker in the document. Returns a {from,
  5497. // to} object by default. Side can be passed to get a specific side
  5498. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5499. // Pos objects returned contain a line object, rather than a line
  5500. // number (used to prevent looking up the same line twice).
  5501. TextMarker.prototype.find = function(side, lineObj) {
  5502. if (side == null && this.type == "bookmark") side = 1;
  5503. var from, to;
  5504. for (var i = 0; i < this.lines.length; ++i) {
  5505. var line = this.lines[i];
  5506. var span = getMarkedSpanFor(line.markedSpans, this);
  5507. if (span.from != null) {
  5508. from = Pos(lineObj ? line : lineNo(line), span.from);
  5509. if (side == -1) return from;
  5510. }
  5511. if (span.to != null) {
  5512. to = Pos(lineObj ? line : lineNo(line), span.to);
  5513. if (side == 1) return to;
  5514. }
  5515. }
  5516. return from && {from: from, to: to};
  5517. };
  5518. // Signals that the marker's widget changed, and surrounding layout
  5519. // should be recomputed.
  5520. TextMarker.prototype.changed = function() {
  5521. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5522. if (!pos || !cm) return;
  5523. runInOp(cm, function() {
  5524. var line = pos.line, lineN = lineNo(pos.line);
  5525. var view = findViewForLine(cm, lineN);
  5526. if (view) {
  5527. clearLineMeasurementCacheFor(view);
  5528. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5529. }
  5530. cm.curOp.updateMaxLine = true;
  5531. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5532. var oldHeight = widget.height;
  5533. widget.height = null;
  5534. var dHeight = widgetHeight(widget) - oldHeight;
  5535. if (dHeight)
  5536. updateLineHeight(line, line.height + dHeight);
  5537. }
  5538. });
  5539. };
  5540. TextMarker.prototype.attachLine = function(line) {
  5541. if (!this.lines.length && this.doc.cm) {
  5542. var op = this.doc.cm.curOp;
  5543. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5544. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5545. }
  5546. this.lines.push(line);
  5547. };
  5548. TextMarker.prototype.detachLine = function(line) {
  5549. this.lines.splice(indexOf(this.lines, line), 1);
  5550. if (!this.lines.length && this.doc.cm) {
  5551. var op = this.doc.cm.curOp;
  5552. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5553. }
  5554. };
  5555. // Collapsed markers have unique ids, in order to be able to order
  5556. // them, which is needed for uniquely determining an outer marker
  5557. // when they overlap (they may nest, but not partially overlap).
  5558. var nextMarkerId = 0;
  5559. // Create a marker, wire it up to the right lines, and
  5560. function markText(doc, from, to, options, type) {
  5561. // Shared markers (across linked documents) are handled separately
  5562. // (markTextShared will call out to this again, once per
  5563. // document).
  5564. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5565. // Ensure we are in an operation.
  5566. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5567. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5568. if (options) copyObj(options, marker, false);
  5569. // Don't connect empty markers unless clearWhenEmpty is false
  5570. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5571. return marker;
  5572. if (marker.replacedWith) {
  5573. // Showing up as a widget implies collapsed (widget replaces text)
  5574. marker.collapsed = true;
  5575. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5576. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5577. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5578. }
  5579. if (marker.collapsed) {
  5580. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5581. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5582. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5583. sawCollapsedSpans = true;
  5584. }
  5585. if (marker.addToHistory)
  5586. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  5587. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5588. doc.iter(curLine, to.line + 1, function(line) {
  5589. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5590. updateMaxLine = true;
  5591. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5592. addMarkedSpan(line, new MarkedSpan(marker,
  5593. curLine == from.line ? from.ch : null,
  5594. curLine == to.line ? to.ch : null));
  5595. ++curLine;
  5596. });
  5597. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5598. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  5599. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5600. });
  5601. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  5602. if (marker.readOnly) {
  5603. sawReadOnlySpans = true;
  5604. if (doc.history.done.length || doc.history.undone.length)
  5605. doc.clearHistory();
  5606. }
  5607. if (marker.collapsed) {
  5608. marker.id = ++nextMarkerId;
  5609. marker.atomic = true;
  5610. }
  5611. if (cm) {
  5612. // Sync editor state
  5613. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5614. if (marker.collapsed)
  5615. regChange(cm, from.line, to.line + 1);
  5616. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5617. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5618. if (marker.atomic) reCheckSelection(cm.doc);
  5619. signalLater(cm, "markerAdded", cm, marker);
  5620. }
  5621. return marker;
  5622. }
  5623. // SHARED TEXTMARKERS
  5624. // A shared marker spans multiple linked documents. It is
  5625. // implemented as a meta-marker-object controlling multiple normal
  5626. // markers.
  5627. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  5628. this.markers = markers;
  5629. this.primary = primary;
  5630. for (var i = 0; i < markers.length; ++i)
  5631. markers[i].parent = this;
  5632. };
  5633. eventMixin(SharedTextMarker);
  5634. SharedTextMarker.prototype.clear = function() {
  5635. if (this.explicitlyCleared) return;
  5636. this.explicitlyCleared = true;
  5637. for (var i = 0; i < this.markers.length; ++i)
  5638. this.markers[i].clear();
  5639. signalLater(this, "clear");
  5640. };
  5641. SharedTextMarker.prototype.find = function(side, lineObj) {
  5642. return this.primary.find(side, lineObj);
  5643. };
  5644. function markTextShared(doc, from, to, options, type) {
  5645. options = copyObj(options);
  5646. options.shared = false;
  5647. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5648. var widget = options.widgetNode;
  5649. linkedDocs(doc, function(doc) {
  5650. if (widget) options.widgetNode = widget.cloneNode(true);
  5651. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5652. for (var i = 0; i < doc.linked.length; ++i)
  5653. if (doc.linked[i].isParent) return;
  5654. primary = lst(markers);
  5655. });
  5656. return new SharedTextMarker(markers, primary);
  5657. }
  5658. function findSharedMarkers(doc) {
  5659. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5660. function(m) { return m.parent; });
  5661. }
  5662. function copySharedMarkers(doc, markers) {
  5663. for (var i = 0; i < markers.length; i++) {
  5664. var marker = markers[i], pos = marker.find();
  5665. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5666. if (cmp(mFrom, mTo)) {
  5667. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5668. marker.markers.push(subMark);
  5669. subMark.parent = marker;
  5670. }
  5671. }
  5672. }
  5673. function detachSharedMarkers(markers) {
  5674. for (var i = 0; i < markers.length; i++) {
  5675. var marker = markers[i], linked = [marker.primary.doc];;
  5676. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5677. for (var j = 0; j < marker.markers.length; j++) {
  5678. var subMarker = marker.markers[j];
  5679. if (indexOf(linked, subMarker.doc) == -1) {
  5680. subMarker.parent = null;
  5681. marker.markers.splice(j--, 1);
  5682. }
  5683. }
  5684. }
  5685. }
  5686. // TEXTMARKER SPANS
  5687. function MarkedSpan(marker, from, to) {
  5688. this.marker = marker;
  5689. this.from = from; this.to = to;
  5690. }
  5691. // Search an array of spans for a span matching the given marker.
  5692. function getMarkedSpanFor(spans, marker) {
  5693. if (spans) for (var i = 0; i < spans.length; ++i) {
  5694. var span = spans[i];
  5695. if (span.marker == marker) return span;
  5696. }
  5697. }
  5698. // Remove a span from an array, returning undefined if no spans are
  5699. // left (we don't store arrays for lines without spans).
  5700. function removeMarkedSpan(spans, span) {
  5701. for (var r, i = 0; i < spans.length; ++i)
  5702. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5703. return r;
  5704. }
  5705. // Add a span to a line.
  5706. function addMarkedSpan(line, span) {
  5707. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5708. span.marker.attachLine(line);
  5709. }
  5710. // Used for the algorithm that adjusts markers for a change in the
  5711. // document. These functions cut an array of spans at a given
  5712. // character position, returning an array of remaining chunks (or
  5713. // undefined if nothing remains).
  5714. function markedSpansBefore(old, startCh, isInsert) {
  5715. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5716. var span = old[i], marker = span.marker;
  5717. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5718. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5719. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5720. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5721. }
  5722. }
  5723. return nw;
  5724. }
  5725. function markedSpansAfter(old, endCh, isInsert) {
  5726. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5727. var span = old[i], marker = span.marker;
  5728. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5729. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5730. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5731. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5732. span.to == null ? null : span.to - endCh));
  5733. }
  5734. }
  5735. return nw;
  5736. }
  5737. // Given a change object, compute the new set of marker spans that
  5738. // cover the line in which the change took place. Removes spans
  5739. // entirely within the change, reconnects spans belonging to the
  5740. // same marker that appear on both sides of the change, and cuts off
  5741. // spans partially within the change. Returns an array of span
  5742. // arrays with one element for each line in (after) the change.
  5743. function stretchSpansOverChange(doc, change) {
  5744. if (change.full) return null;
  5745. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5746. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5747. if (!oldFirst && !oldLast) return null;
  5748. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5749. // Get the spans that 'stick out' on both sides
  5750. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5751. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5752. // Next, merge those two ends
  5753. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5754. if (first) {
  5755. // Fix up .to properties of first
  5756. for (var i = 0; i < first.length; ++i) {
  5757. var span = first[i];
  5758. if (span.to == null) {
  5759. var found = getMarkedSpanFor(last, span.marker);
  5760. if (!found) span.to = startCh;
  5761. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5762. }
  5763. }
  5764. }
  5765. if (last) {
  5766. // Fix up .from in last (or move them into first in case of sameLine)
  5767. for (var i = 0; i < last.length; ++i) {
  5768. var span = last[i];
  5769. if (span.to != null) span.to += offset;
  5770. if (span.from == null) {
  5771. var found = getMarkedSpanFor(first, span.marker);
  5772. if (!found) {
  5773. span.from = offset;
  5774. if (sameLine) (first || (first = [])).push(span);
  5775. }
  5776. } else {
  5777. span.from += offset;
  5778. if (sameLine) (first || (first = [])).push(span);
  5779. }
  5780. }
  5781. }
  5782. // Make sure we didn't create any zero-length spans
  5783. if (first) first = clearEmptySpans(first);
  5784. if (last && last != first) last = clearEmptySpans(last);
  5785. var newMarkers = [first];
  5786. if (!sameLine) {
  5787. // Fill gap with whole-line-spans
  5788. var gap = change.text.length - 2, gapMarkers;
  5789. if (gap > 0 && first)
  5790. for (var i = 0; i < first.length; ++i)
  5791. if (first[i].to == null)
  5792. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5793. for (var i = 0; i < gap; ++i)
  5794. newMarkers.push(gapMarkers);
  5795. newMarkers.push(last);
  5796. }
  5797. return newMarkers;
  5798. }
  5799. // Remove spans that are empty and don't have a clearWhenEmpty
  5800. // option of false.
  5801. function clearEmptySpans(spans) {
  5802. for (var i = 0; i < spans.length; ++i) {
  5803. var span = spans[i];
  5804. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5805. spans.splice(i--, 1);
  5806. }
  5807. if (!spans.length) return null;
  5808. return spans;
  5809. }
  5810. // Used for un/re-doing changes from the history. Combines the
  5811. // result of computing the existing spans with the set of spans that
  5812. // existed in the history (so that deleting around a span and then
  5813. // undoing brings back the span).
  5814. function mergeOldSpans(doc, change) {
  5815. var old = getOldSpans(doc, change);
  5816. var stretched = stretchSpansOverChange(doc, change);
  5817. if (!old) return stretched;
  5818. if (!stretched) return old;
  5819. for (var i = 0; i < old.length; ++i) {
  5820. var oldCur = old[i], stretchCur = stretched[i];
  5821. if (oldCur && stretchCur) {
  5822. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5823. var span = stretchCur[j];
  5824. for (var k = 0; k < oldCur.length; ++k)
  5825. if (oldCur[k].marker == span.marker) continue spans;
  5826. oldCur.push(span);
  5827. }
  5828. } else if (stretchCur) {
  5829. old[i] = stretchCur;
  5830. }
  5831. }
  5832. return old;
  5833. }
  5834. // Used to 'clip' out readOnly ranges when making a change.
  5835. function removeReadOnlyRanges(doc, from, to) {
  5836. var markers = null;
  5837. doc.iter(from.line, to.line + 1, function(line) {
  5838. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5839. var mark = line.markedSpans[i].marker;
  5840. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5841. (markers || (markers = [])).push(mark);
  5842. }
  5843. });
  5844. if (!markers) return null;
  5845. var parts = [{from: from, to: to}];
  5846. for (var i = 0; i < markers.length; ++i) {
  5847. var mk = markers[i], m = mk.find(0);
  5848. for (var j = 0; j < parts.length; ++j) {
  5849. var p = parts[j];
  5850. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5851. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5852. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5853. newParts.push({from: p.from, to: m.from});
  5854. if (dto > 0 || !mk.inclusiveRight && !dto)
  5855. newParts.push({from: m.to, to: p.to});
  5856. parts.splice.apply(parts, newParts);
  5857. j += newParts.length - 1;
  5858. }
  5859. }
  5860. return parts;
  5861. }
  5862. // Connect or disconnect spans from a line.
  5863. function detachMarkedSpans(line) {
  5864. var spans = line.markedSpans;
  5865. if (!spans) return;
  5866. for (var i = 0; i < spans.length; ++i)
  5867. spans[i].marker.detachLine(line);
  5868. line.markedSpans = null;
  5869. }
  5870. function attachMarkedSpans(line, spans) {
  5871. if (!spans) return;
  5872. for (var i = 0; i < spans.length; ++i)
  5873. spans[i].marker.attachLine(line);
  5874. line.markedSpans = spans;
  5875. }
  5876. // Helpers used when computing which overlapping collapsed span
  5877. // counts as the larger one.
  5878. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5879. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5880. // Returns a number indicating which of two overlapping collapsed
  5881. // spans is larger (and thus includes the other). Falls back to
  5882. // comparing ids when the spans cover exactly the same range.
  5883. function compareCollapsedMarkers(a, b) {
  5884. var lenDiff = a.lines.length - b.lines.length;
  5885. if (lenDiff != 0) return lenDiff;
  5886. var aPos = a.find(), bPos = b.find();
  5887. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5888. if (fromCmp) return -fromCmp;
  5889. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5890. if (toCmp) return toCmp;
  5891. return b.id - a.id;
  5892. }
  5893. // Find out whether a line ends or starts in a collapsed span. If
  5894. // so, return the marker for that span.
  5895. function collapsedSpanAtSide(line, start) {
  5896. var sps = sawCollapsedSpans && line.markedSpans, found;
  5897. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5898. sp = sps[i];
  5899. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5900. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5901. found = sp.marker;
  5902. }
  5903. return found;
  5904. }
  5905. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5906. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5907. // Test whether there exists a collapsed span that partially
  5908. // overlaps (covers the start or end, but not both) of a new span.
  5909. // Such overlap is not allowed.
  5910. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5911. var line = getLine(doc, lineNo);
  5912. var sps = sawCollapsedSpans && line.markedSpans;
  5913. if (sps) for (var i = 0; i < sps.length; ++i) {
  5914. var sp = sps[i];
  5915. if (!sp.marker.collapsed) continue;
  5916. var found = sp.marker.find(0);
  5917. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5918. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5919. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5920. if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
  5921. fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
  5922. return true;
  5923. }
  5924. }
  5925. // A visual line is a line as drawn on the screen. Folding, for
  5926. // example, can cause multiple logical lines to appear on the same
  5927. // visual line. This finds the start of the visual line that the
  5928. // given line is part of (usually that is the line itself).
  5929. function visualLine(line) {
  5930. var merged;
  5931. while (merged = collapsedSpanAtStart(line))
  5932. line = merged.find(-1, true).line;
  5933. return line;
  5934. }
  5935. // Returns an array of logical lines that continue the visual line
  5936. // started by the argument, or undefined if there are no such lines.
  5937. function visualLineContinued(line) {
  5938. var merged, lines;
  5939. while (merged = collapsedSpanAtEnd(line)) {
  5940. line = merged.find(1, true).line;
  5941. (lines || (lines = [])).push(line);
  5942. }
  5943. return lines;
  5944. }
  5945. // Get the line number of the start of the visual line that the
  5946. // given line number is part of.
  5947. function visualLineNo(doc, lineN) {
  5948. var line = getLine(doc, lineN), vis = visualLine(line);
  5949. if (line == vis) return lineN;
  5950. return lineNo(vis);
  5951. }
  5952. // Get the line number of the start of the next visual line after
  5953. // the given line.
  5954. function visualLineEndNo(doc, lineN) {
  5955. if (lineN > doc.lastLine()) return lineN;
  5956. var line = getLine(doc, lineN), merged;
  5957. if (!lineIsHidden(doc, line)) return lineN;
  5958. while (merged = collapsedSpanAtEnd(line))
  5959. line = merged.find(1, true).line;
  5960. return lineNo(line) + 1;
  5961. }
  5962. // Compute whether a line is hidden. Lines count as hidden when they
  5963. // are part of a visual line that starts with another line, or when
  5964. // they are entirely covered by collapsed, non-widget span.
  5965. function lineIsHidden(doc, line) {
  5966. var sps = sawCollapsedSpans && line.markedSpans;
  5967. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5968. sp = sps[i];
  5969. if (!sp.marker.collapsed) continue;
  5970. if (sp.from == null) return true;
  5971. if (sp.marker.widgetNode) continue;
  5972. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5973. return true;
  5974. }
  5975. }
  5976. function lineIsHiddenInner(doc, line, span) {
  5977. if (span.to == null) {
  5978. var end = span.marker.find(1, true);
  5979. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5980. }
  5981. if (span.marker.inclusiveRight && span.to == line.text.length)
  5982. return true;
  5983. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5984. sp = line.markedSpans[i];
  5985. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5986. (sp.to == null || sp.to != span.from) &&
  5987. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5988. lineIsHiddenInner(doc, line, sp)) return true;
  5989. }
  5990. }
  5991. // LINE WIDGETS
  5992. // Line widgets are block elements displayed above or below a line.
  5993. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  5994. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  5995. this[opt] = options[opt];
  5996. this.doc = doc;
  5997. this.node = node;
  5998. };
  5999. eventMixin(LineWidget);
  6000. function adjustScrollWhenAboveVisible(cm, line, diff) {
  6001. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  6002. addToScrollPos(cm, null, diff);
  6003. }
  6004. LineWidget.prototype.clear = function() {
  6005. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  6006. if (no == null || !ws) return;
  6007. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  6008. if (!ws.length) line.widgets = null;
  6009. var height = widgetHeight(this);
  6010. updateLineHeight(line, Math.max(0, line.height - height));
  6011. if (cm) runInOp(cm, function() {
  6012. adjustScrollWhenAboveVisible(cm, line, -height);
  6013. regLineChange(cm, no, "widget");
  6014. });
  6015. };
  6016. LineWidget.prototype.changed = function() {
  6017. var oldH = this.height, cm = this.doc.cm, line = this.line;
  6018. this.height = null;
  6019. var diff = widgetHeight(this) - oldH;
  6020. if (!diff) return;
  6021. updateLineHeight(line, line.height + diff);
  6022. if (cm) runInOp(cm, function() {
  6023. cm.curOp.forceUpdate = true;
  6024. adjustScrollWhenAboveVisible(cm, line, diff);
  6025. });
  6026. };
  6027. function widgetHeight(widget) {
  6028. if (widget.height != null) return widget.height;
  6029. var cm = widget.doc.cm;
  6030. if (!cm) return 0;
  6031. if (!contains(document.body, widget.node)) {
  6032. var parentStyle = "position: relative;";
  6033. if (widget.coverGutter)
  6034. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  6035. if (widget.noHScroll)
  6036. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  6037. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  6038. }
  6039. return widget.height = widget.node.parentNode.offsetHeight;
  6040. }
  6041. function addLineWidget(doc, handle, node, options) {
  6042. var widget = new LineWidget(doc, node, options);
  6043. var cm = doc.cm;
  6044. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  6045. changeLine(doc, handle, "widget", function(line) {
  6046. var widgets = line.widgets || (line.widgets = []);
  6047. if (widget.insertAt == null) widgets.push(widget);
  6048. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  6049. widget.line = line;
  6050. if (cm && !lineIsHidden(doc, line)) {
  6051. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  6052. updateLineHeight(line, line.height + widgetHeight(widget));
  6053. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  6054. cm.curOp.forceUpdate = true;
  6055. }
  6056. return true;
  6057. });
  6058. return widget;
  6059. }
  6060. // LINE DATA STRUCTURE
  6061. // Line objects. These hold state related to a line, including
  6062. // highlighting info (the styles array).
  6063. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  6064. this.text = text;
  6065. attachMarkedSpans(this, markedSpans);
  6066. this.height = estimateHeight ? estimateHeight(this) : 1;
  6067. };
  6068. eventMixin(Line);
  6069. Line.prototype.lineNo = function() { return lineNo(this); };
  6070. // Change the content (text, markers) of a line. Automatically
  6071. // invalidates cached information and tries to re-estimate the
  6072. // line's height.
  6073. function updateLine(line, text, markedSpans, estimateHeight) {
  6074. line.text = text;
  6075. if (line.stateAfter) line.stateAfter = null;
  6076. if (line.styles) line.styles = null;
  6077. if (line.order != null) line.order = null;
  6078. detachMarkedSpans(line);
  6079. attachMarkedSpans(line, markedSpans);
  6080. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  6081. if (estHeight != line.height) updateLineHeight(line, estHeight);
  6082. }
  6083. // Detach a line from the document tree and its markers.
  6084. function cleanUpLine(line) {
  6085. line.parent = null;
  6086. detachMarkedSpans(line);
  6087. }
  6088. function extractLineClasses(type, output) {
  6089. if (type) for (;;) {
  6090. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  6091. if (!lineClass) break;
  6092. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  6093. var prop = lineClass[1] ? "bgClass" : "textClass";
  6094. if (output[prop] == null)
  6095. output[prop] = lineClass[2];
  6096. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  6097. output[prop] += " " + lineClass[2];
  6098. }
  6099. return type;
  6100. }
  6101. function callBlankLine(mode, state) {
  6102. if (mode.blankLine) return mode.blankLine(state);
  6103. if (!mode.innerMode) return;
  6104. var inner = CodeMirror.innerMode(mode, state);
  6105. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  6106. }
  6107. function readToken(mode, stream, state, inner) {
  6108. for (var i = 0; i < 10; i++) {
  6109. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  6110. var style = mode.token(stream, state);
  6111. if (stream.pos > stream.start) return style;
  6112. }
  6113. throw new Error("Mode " + mode.name + " failed to advance stream.");
  6114. }
  6115. // Utility for getTokenAt and getLineTokens
  6116. function takeToken(cm, pos, precise, asArray) {
  6117. function getObj(copy) {
  6118. return {start: stream.start, end: stream.pos,
  6119. string: stream.current(),
  6120. type: style || null,
  6121. state: copy ? copyState(doc.mode, state) : state};
  6122. }
  6123. var doc = cm.doc, mode = doc.mode, style;
  6124. pos = clipPos(doc, pos);
  6125. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  6126. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  6127. if (asArray) tokens = [];
  6128. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  6129. stream.start = stream.pos;
  6130. style = readToken(mode, stream, state);
  6131. if (asArray) tokens.push(getObj(true));
  6132. }
  6133. return asArray ? tokens : getObj();
  6134. }
  6135. // Run the given mode's parser over a line, calling f for each token.
  6136. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  6137. var flattenSpans = mode.flattenSpans;
  6138. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  6139. var curStart = 0, curStyle = null;
  6140. var stream = new StringStream(text, cm.options.tabSize), style;
  6141. var inner = cm.options.addModeClass && [null];
  6142. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  6143. while (!stream.eol()) {
  6144. if (stream.pos > cm.options.maxHighlightLength) {
  6145. flattenSpans = false;
  6146. if (forceToEnd) processLine(cm, text, state, stream.pos);
  6147. stream.pos = text.length;
  6148. style = null;
  6149. } else {
  6150. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  6151. }
  6152. if (inner) {
  6153. var mName = inner[0].name;
  6154. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  6155. }
  6156. if (!flattenSpans || curStyle != style) {
  6157. while (curStart < stream.start) {
  6158. curStart = Math.min(stream.start, curStart + 50000);
  6159. f(curStart, curStyle);
  6160. }
  6161. curStyle = style;
  6162. }
  6163. stream.start = stream.pos;
  6164. }
  6165. while (curStart < stream.pos) {
  6166. // Webkit seems to refuse to render text nodes longer than 57444 characters
  6167. var pos = Math.min(stream.pos, curStart + 50000);
  6168. f(pos, curStyle);
  6169. curStart = pos;
  6170. }
  6171. }
  6172. // Compute a style array (an array starting with a mode generation
  6173. // -- for invalidation -- followed by pairs of end positions and
  6174. // style strings), which is used to highlight the tokens on the
  6175. // line.
  6176. function highlightLine(cm, line, state, forceToEnd) {
  6177. // A styles array always starts with a number identifying the
  6178. // mode/overlays that it is based on (for easy invalidation).
  6179. var st = [cm.state.modeGen], lineClasses = {};
  6180. // Compute the base array of styles
  6181. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  6182. st.push(end, style);
  6183. }, lineClasses, forceToEnd);
  6184. // Run overlays, adjust style array.
  6185. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6186. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6187. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  6188. var start = i;
  6189. // Ensure there's a token end at the current position, and that i points at it
  6190. while (at < end) {
  6191. var i_end = st[i];
  6192. if (i_end > end)
  6193. st.splice(i, 1, end, st[i+1], i_end);
  6194. i += 2;
  6195. at = Math.min(end, i_end);
  6196. }
  6197. if (!style) return;
  6198. if (overlay.opaque) {
  6199. st.splice(start, i - start, end, "cm-overlay " + style);
  6200. i = start + 2;
  6201. } else {
  6202. for (; start < i; start += 2) {
  6203. var cur = st[start+1];
  6204. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6205. }
  6206. }
  6207. }, lineClasses);
  6208. }
  6209. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  6210. }
  6211. function getLineStyles(cm, line, updateFrontier) {
  6212. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6213. var state = getStateBefore(cm, lineNo(line));
  6214. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  6215. line.stateAfter = state;
  6216. line.styles = result.styles;
  6217. if (result.classes) line.styleClasses = result.classes;
  6218. else if (line.styleClasses) line.styleClasses = null;
  6219. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6220. }
  6221. return line.styles;
  6222. }
  6223. // Lightweight form of highlight -- proceed over this line and
  6224. // update state, but don't save a style array. Used for lines that
  6225. // aren't currently visible.
  6226. function processLine(cm, text, state, startAt) {
  6227. var mode = cm.doc.mode;
  6228. var stream = new StringStream(text, cm.options.tabSize);
  6229. stream.start = stream.pos = startAt || 0;
  6230. if (text == "") callBlankLine(mode, state);
  6231. while (!stream.eol()) {
  6232. readToken(mode, stream, state);
  6233. stream.start = stream.pos;
  6234. }
  6235. }
  6236. // Convert a style as returned by a mode (either null, or a string
  6237. // containing one or more styles) to a CSS style. This is cached,
  6238. // and also looks for line-wide styles.
  6239. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6240. function interpretTokenStyle(style, options) {
  6241. if (!style || /^\s*$/.test(style)) return null;
  6242. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6243. return cache[style] ||
  6244. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6245. }
  6246. // Render the DOM representation of the text of a line. Also builds
  6247. // up a 'line map', which points at the DOM nodes that represent
  6248. // specific stretches of text, and is used by the measuring code.
  6249. // The returned object contains the DOM node, this map, and
  6250. // information about line-wide styles that were set by the mode.
  6251. function buildLineContent(cm, lineView) {
  6252. // The padding-right forces the element to have a 'border', which
  6253. // is needed on Webkit to be able to get line-level bounding
  6254. // rectangles for it (in measureChar).
  6255. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6256. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  6257. col: 0, pos: 0, cm: cm,
  6258. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  6259. lineView.measure = {};
  6260. // Iterate over the logical lines that make up this visual line.
  6261. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6262. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6263. builder.pos = 0;
  6264. builder.addToken = buildToken;
  6265. // Optionally wire in some hacks into the token-rendering
  6266. // algorithm, to deal with browser quirks.
  6267. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6268. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6269. builder.map = [];
  6270. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6271. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6272. if (line.styleClasses) {
  6273. if (line.styleClasses.bgClass)
  6274. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6275. if (line.styleClasses.textClass)
  6276. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6277. }
  6278. // Ensure at least a single node is present, for measuring.
  6279. if (builder.map.length == 0)
  6280. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6281. // Store the map and a cache object for the current logical line
  6282. if (i == 0) {
  6283. lineView.measure.map = builder.map;
  6284. lineView.measure.cache = {};
  6285. } else {
  6286. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6287. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6288. }
  6289. }
  6290. // See issue #2901
  6291. if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
  6292. builder.content.className = "cm-tab-wrap-hack";
  6293. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6294. if (builder.pre.className)
  6295. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6296. return builder;
  6297. }
  6298. function defaultSpecialCharPlaceholder(ch) {
  6299. var token = elt("span", "\u2022", "cm-invalidchar");
  6300. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6301. token.setAttribute("aria-label", token.title);
  6302. return token;
  6303. }
  6304. // Build up the DOM representation for a single token, and add it to
  6305. // the line map. Takes care to render special characters separately.
  6306. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6307. if (!text) return;
  6308. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  6309. var special = builder.cm.state.specialChars, mustWrap = false;
  6310. if (!special.test(text)) {
  6311. builder.col += text.length;
  6312. var content = document.createTextNode(displayText);
  6313. builder.map.push(builder.pos, builder.pos + text.length, content);
  6314. if (ie && ie_version < 9) mustWrap = true;
  6315. builder.pos += text.length;
  6316. } else {
  6317. var content = document.createDocumentFragment(), pos = 0;
  6318. while (true) {
  6319. special.lastIndex = pos;
  6320. var m = special.exec(text);
  6321. var skipped = m ? m.index - pos : text.length - pos;
  6322. if (skipped) {
  6323. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  6324. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6325. else content.appendChild(txt);
  6326. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6327. builder.col += skipped;
  6328. builder.pos += skipped;
  6329. }
  6330. if (!m) break;
  6331. pos += skipped + 1;
  6332. if (m[0] == "\t") {
  6333. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6334. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6335. txt.setAttribute("role", "presentation");
  6336. txt.setAttribute("cm-text", "\t");
  6337. builder.col += tabWidth;
  6338. } else if (m[0] == "\r" || m[0] == "\n") {
  6339. var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  6340. txt.setAttribute("cm-text", m[0]);
  6341. builder.col += 1;
  6342. } else {
  6343. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6344. txt.setAttribute("cm-text", m[0]);
  6345. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6346. else content.appendChild(txt);
  6347. builder.col += 1;
  6348. }
  6349. builder.map.push(builder.pos, builder.pos + 1, txt);
  6350. builder.pos++;
  6351. }
  6352. }
  6353. if (style || startStyle || endStyle || mustWrap || css) {
  6354. var fullStyle = style || "";
  6355. if (startStyle) fullStyle += startStyle;
  6356. if (endStyle) fullStyle += endStyle;
  6357. var token = elt("span", [content], fullStyle, css);
  6358. if (title) token.title = title;
  6359. return builder.content.appendChild(token);
  6360. }
  6361. builder.content.appendChild(content);
  6362. }
  6363. function splitSpaces(old) {
  6364. var out = " ";
  6365. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  6366. out += " ";
  6367. return out;
  6368. }
  6369. // Work around nonsense dimensions being reported for stretches of
  6370. // right-to-left text.
  6371. function buildTokenBadBidi(inner, order) {
  6372. return function(builder, text, style, startStyle, endStyle, title, css) {
  6373. style = style ? style + " cm-force-border" : "cm-force-border";
  6374. var start = builder.pos, end = start + text.length;
  6375. for (;;) {
  6376. // Find the part that overlaps with the start of this text
  6377. for (var i = 0; i < order.length; i++) {
  6378. var part = order[i];
  6379. if (part.to > start && part.from <= start) break;
  6380. }
  6381. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  6382. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  6383. startStyle = null;
  6384. text = text.slice(part.to - start);
  6385. start = part.to;
  6386. }
  6387. };
  6388. }
  6389. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6390. var widget = !ignoreWidget && marker.widgetNode;
  6391. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6392. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6393. if (!widget)
  6394. widget = builder.content.appendChild(document.createElement("span"));
  6395. widget.setAttribute("cm-marker", marker.id);
  6396. }
  6397. if (widget) {
  6398. builder.cm.display.input.setUneditable(widget);
  6399. builder.content.appendChild(widget);
  6400. }
  6401. builder.pos += size;
  6402. }
  6403. // Outputs a number of spans to make up a line, taking highlighting
  6404. // and marked text into account.
  6405. function insertLineContent(line, builder, styles) {
  6406. var spans = line.markedSpans, allText = line.text, at = 0;
  6407. if (!spans) {
  6408. for (var i = 1; i < styles.length; i+=2)
  6409. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  6410. return;
  6411. }
  6412. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6413. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6414. for (;;) {
  6415. if (nextChange == pos) { // Update current marker set
  6416. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6417. collapsed = null; nextChange = Infinity;
  6418. var foundBookmarks = [], endStyles
  6419. for (var j = 0; j < spans.length; ++j) {
  6420. var sp = spans[j], m = sp.marker;
  6421. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  6422. foundBookmarks.push(m);
  6423. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  6424. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  6425. nextChange = sp.to;
  6426. spanEndStyle = "";
  6427. }
  6428. if (m.className) spanStyle += " " + m.className;
  6429. if (m.css) css = (css ? css + ";" : "") + m.css;
  6430. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6431. if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  6432. if (m.title && !title) title = m.title;
  6433. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6434. collapsed = sp;
  6435. } else if (sp.from > pos && nextChange > sp.from) {
  6436. nextChange = sp.from;
  6437. }
  6438. }
  6439. if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
  6440. if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  6441. if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
  6442. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6443. if (collapsed && (collapsed.from || 0) == pos) {
  6444. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6445. collapsed.marker, collapsed.from == null);
  6446. if (collapsed.to == null) return;
  6447. if (collapsed.to == pos) collapsed = false;
  6448. }
  6449. }
  6450. if (pos >= len) break;
  6451. var upto = Math.min(len, nextChange);
  6452. while (true) {
  6453. if (text) {
  6454. var end = pos + text.length;
  6455. if (!collapsed) {
  6456. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6457. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6458. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6459. }
  6460. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  6461. pos = end;
  6462. spanStartStyle = "";
  6463. }
  6464. text = allText.slice(at, at = styles[i++]);
  6465. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6466. }
  6467. }
  6468. }
  6469. // DOCUMENT DATA STRUCTURE
  6470. // By default, updates that start and end at the beginning of a line
  6471. // are treated specially, in order to make the association of line
  6472. // widgets and marker elements with the text behave more intuitive.
  6473. function isWholeLineUpdate(doc, change) {
  6474. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6475. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6476. }
  6477. // Perform a change on the document data structure.
  6478. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6479. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  6480. function update(line, text, spans) {
  6481. updateLine(line, text, spans, estimateHeight);
  6482. signalLater(line, "change", line, change);
  6483. }
  6484. function linesFor(start, end) {
  6485. for (var i = start, result = []; i < end; ++i)
  6486. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6487. return result;
  6488. }
  6489. var from = change.from, to = change.to, text = change.text;
  6490. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6491. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6492. // Adjust the line structure
  6493. if (change.full) {
  6494. doc.insert(0, linesFor(0, text.length));
  6495. doc.remove(text.length, doc.size - text.length);
  6496. } else if (isWholeLineUpdate(doc, change)) {
  6497. // This is a whole-line replace. Treated specially to make
  6498. // sure line objects move the way they are supposed to.
  6499. var added = linesFor(0, text.length - 1);
  6500. update(lastLine, lastLine.text, lastSpans);
  6501. if (nlines) doc.remove(from.line, nlines);
  6502. if (added.length) doc.insert(from.line, added);
  6503. } else if (firstLine == lastLine) {
  6504. if (text.length == 1) {
  6505. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6506. } else {
  6507. var added = linesFor(1, text.length - 1);
  6508. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6509. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6510. doc.insert(from.line + 1, added);
  6511. }
  6512. } else if (text.length == 1) {
  6513. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6514. doc.remove(from.line + 1, nlines);
  6515. } else {
  6516. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6517. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6518. var added = linesFor(1, text.length - 1);
  6519. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6520. doc.insert(from.line + 1, added);
  6521. }
  6522. signalLater(doc, "change", doc, change);
  6523. }
  6524. // The document is represented as a BTree consisting of leaves, with
  6525. // chunk of lines in them, and branches, with up to ten leaves or
  6526. // other branch nodes below them. The top node is always a branch
  6527. // node, and is the document object itself (meaning it has
  6528. // additional methods and properties).
  6529. //
  6530. // All nodes have parent links. The tree is used both to go from
  6531. // line numbers to line objects, and to go from objects to numbers.
  6532. // It also indexes by height, and is used to convert between height
  6533. // and line object, and to find the total height of the document.
  6534. //
  6535. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6536. function LeafChunk(lines) {
  6537. this.lines = lines;
  6538. this.parent = null;
  6539. for (var i = 0, height = 0; i < lines.length; ++i) {
  6540. lines[i].parent = this;
  6541. height += lines[i].height;
  6542. }
  6543. this.height = height;
  6544. }
  6545. LeafChunk.prototype = {
  6546. chunkSize: function() { return this.lines.length; },
  6547. // Remove the n lines at offset 'at'.
  6548. removeInner: function(at, n) {
  6549. for (var i = at, e = at + n; i < e; ++i) {
  6550. var line = this.lines[i];
  6551. this.height -= line.height;
  6552. cleanUpLine(line);
  6553. signalLater(line, "delete");
  6554. }
  6555. this.lines.splice(at, n);
  6556. },
  6557. // Helper used to collapse a small branch into a single leaf.
  6558. collapse: function(lines) {
  6559. lines.push.apply(lines, this.lines);
  6560. },
  6561. // Insert the given array of lines at offset 'at', count them as
  6562. // having the given height.
  6563. insertInner: function(at, lines, height) {
  6564. this.height += height;
  6565. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6566. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6567. },
  6568. // Used to iterate over a part of the tree.
  6569. iterN: function(at, n, op) {
  6570. for (var e = at + n; at < e; ++at)
  6571. if (op(this.lines[at])) return true;
  6572. }
  6573. };
  6574. function BranchChunk(children) {
  6575. this.children = children;
  6576. var size = 0, height = 0;
  6577. for (var i = 0; i < children.length; ++i) {
  6578. var ch = children[i];
  6579. size += ch.chunkSize(); height += ch.height;
  6580. ch.parent = this;
  6581. }
  6582. this.size = size;
  6583. this.height = height;
  6584. this.parent = null;
  6585. }
  6586. BranchChunk.prototype = {
  6587. chunkSize: function() { return this.size; },
  6588. removeInner: function(at, n) {
  6589. this.size -= n;
  6590. for (var i = 0; i < this.children.length; ++i) {
  6591. var child = this.children[i], sz = child.chunkSize();
  6592. if (at < sz) {
  6593. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6594. child.removeInner(at, rm);
  6595. this.height -= oldHeight - child.height;
  6596. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6597. if ((n -= rm) == 0) break;
  6598. at = 0;
  6599. } else at -= sz;
  6600. }
  6601. // If the result is smaller than 25 lines, ensure that it is a
  6602. // single leaf node.
  6603. if (this.size - n < 25 &&
  6604. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6605. var lines = [];
  6606. this.collapse(lines);
  6607. this.children = [new LeafChunk(lines)];
  6608. this.children[0].parent = this;
  6609. }
  6610. },
  6611. collapse: function(lines) {
  6612. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6613. },
  6614. insertInner: function(at, lines, height) {
  6615. this.size += lines.length;
  6616. this.height += height;
  6617. for (var i = 0; i < this.children.length; ++i) {
  6618. var child = this.children[i], sz = child.chunkSize();
  6619. if (at <= sz) {
  6620. child.insertInner(at, lines, height);
  6621. if (child.lines && child.lines.length > 50) {
  6622. while (child.lines.length > 50) {
  6623. var spilled = child.lines.splice(child.lines.length - 25, 25);
  6624. var newleaf = new LeafChunk(spilled);
  6625. child.height -= newleaf.height;
  6626. this.children.splice(i + 1, 0, newleaf);
  6627. newleaf.parent = this;
  6628. }
  6629. this.maybeSpill();
  6630. }
  6631. break;
  6632. }
  6633. at -= sz;
  6634. }
  6635. },
  6636. // When a node has grown, check whether it should be split.
  6637. maybeSpill: function() {
  6638. if (this.children.length <= 10) return;
  6639. var me = this;
  6640. do {
  6641. var spilled = me.children.splice(me.children.length - 5, 5);
  6642. var sibling = new BranchChunk(spilled);
  6643. if (!me.parent) { // Become the parent node
  6644. var copy = new BranchChunk(me.children);
  6645. copy.parent = me;
  6646. me.children = [copy, sibling];
  6647. me = copy;
  6648. } else {
  6649. me.size -= sibling.size;
  6650. me.height -= sibling.height;
  6651. var myIndex = indexOf(me.parent.children, me);
  6652. me.parent.children.splice(myIndex + 1, 0, sibling);
  6653. }
  6654. sibling.parent = me.parent;
  6655. } while (me.children.length > 10);
  6656. me.parent.maybeSpill();
  6657. },
  6658. iterN: function(at, n, op) {
  6659. for (var i = 0; i < this.children.length; ++i) {
  6660. var child = this.children[i], sz = child.chunkSize();
  6661. if (at < sz) {
  6662. var used = Math.min(n, sz - at);
  6663. if (child.iterN(at, used, op)) return true;
  6664. if ((n -= used) == 0) break;
  6665. at = 0;
  6666. } else at -= sz;
  6667. }
  6668. }
  6669. };
  6670. var nextDocId = 0;
  6671. var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
  6672. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
  6673. if (firstLine == null) firstLine = 0;
  6674. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6675. this.first = firstLine;
  6676. this.scrollTop = this.scrollLeft = 0;
  6677. this.cantEdit = false;
  6678. this.cleanGeneration = 1;
  6679. this.frontier = firstLine;
  6680. var start = Pos(firstLine, 0);
  6681. this.sel = simpleSelection(start);
  6682. this.history = new History(null);
  6683. this.id = ++nextDocId;
  6684. this.modeOption = mode;
  6685. this.lineSep = lineSep;
  6686. this.extend = false;
  6687. if (typeof text == "string") text = this.splitLines(text);
  6688. updateDoc(this, {from: start, to: start, text: text});
  6689. setSelection(this, simpleSelection(start), sel_dontScroll);
  6690. };
  6691. Doc.prototype = createObj(BranchChunk.prototype, {
  6692. constructor: Doc,
  6693. // Iterate over the document. Supports two forms -- with only one
  6694. // argument, it calls that for each line in the document. With
  6695. // three, it iterates over the range given by the first two (with
  6696. // the second being non-inclusive).
  6697. iter: function(from, to, op) {
  6698. if (op) this.iterN(from - this.first, to - from, op);
  6699. else this.iterN(this.first, this.first + this.size, from);
  6700. },
  6701. // Non-public interface for adding and removing lines.
  6702. insert: function(at, lines) {
  6703. var height = 0;
  6704. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6705. this.insertInner(at - this.first, lines, height);
  6706. },
  6707. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6708. // From here, the methods are part of the public interface. Most
  6709. // are also available from CodeMirror (editor) instances.
  6710. getValue: function(lineSep) {
  6711. var lines = getLines(this, this.first, this.first + this.size);
  6712. if (lineSep === false) return lines;
  6713. return lines.join(lineSep || this.lineSeparator());
  6714. },
  6715. setValue: docMethodOp(function(code) {
  6716. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6717. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6718. text: this.splitLines(code), origin: "setValue", full: true}, true);
  6719. setSelection(this, simpleSelection(top));
  6720. }),
  6721. replaceRange: function(code, from, to, origin) {
  6722. from = clipPos(this, from);
  6723. to = to ? clipPos(this, to) : from;
  6724. replaceRange(this, code, from, to, origin);
  6725. },
  6726. getRange: function(from, to, lineSep) {
  6727. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6728. if (lineSep === false) return lines;
  6729. return lines.join(lineSep || this.lineSeparator());
  6730. },
  6731. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6732. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6733. getLineNumber: function(line) {return lineNo(line);},
  6734. getLineHandleVisualStart: function(line) {
  6735. if (typeof line == "number") line = getLine(this, line);
  6736. return visualLine(line);
  6737. },
  6738. lineCount: function() {return this.size;},
  6739. firstLine: function() {return this.first;},
  6740. lastLine: function() {return this.first + this.size - 1;},
  6741. clipPos: function(pos) {return clipPos(this, pos);},
  6742. getCursor: function(start) {
  6743. var range = this.sel.primary(), pos;
  6744. if (start == null || start == "head") pos = range.head;
  6745. else if (start == "anchor") pos = range.anchor;
  6746. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6747. else pos = range.from();
  6748. return pos;
  6749. },
  6750. listSelections: function() { return this.sel.ranges; },
  6751. somethingSelected: function() {return this.sel.somethingSelected();},
  6752. setCursor: docMethodOp(function(line, ch, options) {
  6753. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6754. }),
  6755. setSelection: docMethodOp(function(anchor, head, options) {
  6756. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6757. }),
  6758. extendSelection: docMethodOp(function(head, other, options) {
  6759. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6760. }),
  6761. extendSelections: docMethodOp(function(heads, options) {
  6762. extendSelections(this, clipPosArray(this, heads), options);
  6763. }),
  6764. extendSelectionsBy: docMethodOp(function(f, options) {
  6765. var heads = map(this.sel.ranges, f);
  6766. extendSelections(this, clipPosArray(this, heads), options);
  6767. }),
  6768. setSelections: docMethodOp(function(ranges, primary, options) {
  6769. if (!ranges.length) return;
  6770. for (var i = 0, out = []; i < ranges.length; i++)
  6771. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6772. clipPos(this, ranges[i].head));
  6773. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6774. setSelection(this, normalizeSelection(out, primary), options);
  6775. }),
  6776. addSelection: docMethodOp(function(anchor, head, options) {
  6777. var ranges = this.sel.ranges.slice(0);
  6778. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6779. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6780. }),
  6781. getSelection: function(lineSep) {
  6782. var ranges = this.sel.ranges, lines;
  6783. for (var i = 0; i < ranges.length; i++) {
  6784. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6785. lines = lines ? lines.concat(sel) : sel;
  6786. }
  6787. if (lineSep === false) return lines;
  6788. else return lines.join(lineSep || this.lineSeparator());
  6789. },
  6790. getSelections: function(lineSep) {
  6791. var parts = [], ranges = this.sel.ranges;
  6792. for (var i = 0; i < ranges.length; i++) {
  6793. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6794. if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
  6795. parts[i] = sel;
  6796. }
  6797. return parts;
  6798. },
  6799. replaceSelection: function(code, collapse, origin) {
  6800. var dup = [];
  6801. for (var i = 0; i < this.sel.ranges.length; i++)
  6802. dup[i] = code;
  6803. this.replaceSelections(dup, collapse, origin || "+input");
  6804. },
  6805. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6806. var changes = [], sel = this.sel;
  6807. for (var i = 0; i < sel.ranges.length; i++) {
  6808. var range = sel.ranges[i];
  6809. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  6810. }
  6811. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6812. for (var i = changes.length - 1; i >= 0; i--)
  6813. makeChange(this, changes[i]);
  6814. if (newSel) setSelectionReplaceHistory(this, newSel);
  6815. else if (this.cm) ensureCursorVisible(this.cm);
  6816. }),
  6817. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6818. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6819. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6820. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6821. setExtending: function(val) {this.extend = val;},
  6822. getExtending: function() {return this.extend;},
  6823. historySize: function() {
  6824. var hist = this.history, done = 0, undone = 0;
  6825. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6826. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6827. return {undo: done, redo: undone};
  6828. },
  6829. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6830. markClean: function() {
  6831. this.cleanGeneration = this.changeGeneration(true);
  6832. },
  6833. changeGeneration: function(forceSplit) {
  6834. if (forceSplit)
  6835. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6836. return this.history.generation;
  6837. },
  6838. isClean: function (gen) {
  6839. return this.history.generation == (gen || this.cleanGeneration);
  6840. },
  6841. getHistory: function() {
  6842. return {done: copyHistoryArray(this.history.done),
  6843. undone: copyHistoryArray(this.history.undone)};
  6844. },
  6845. setHistory: function(histData) {
  6846. var hist = this.history = new History(this.history.maxGeneration);
  6847. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6848. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6849. },
  6850. addLineClass: docMethodOp(function(handle, where, cls) {
  6851. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6852. var prop = where == "text" ? "textClass"
  6853. : where == "background" ? "bgClass"
  6854. : where == "gutter" ? "gutterClass" : "wrapClass";
  6855. if (!line[prop]) line[prop] = cls;
  6856. else if (classTest(cls).test(line[prop])) return false;
  6857. else line[prop] += " " + cls;
  6858. return true;
  6859. });
  6860. }),
  6861. removeLineClass: docMethodOp(function(handle, where, cls) {
  6862. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6863. var prop = where == "text" ? "textClass"
  6864. : where == "background" ? "bgClass"
  6865. : where == "gutter" ? "gutterClass" : "wrapClass";
  6866. var cur = line[prop];
  6867. if (!cur) return false;
  6868. else if (cls == null) line[prop] = null;
  6869. else {
  6870. var found = cur.match(classTest(cls));
  6871. if (!found) return false;
  6872. var end = found.index + found[0].length;
  6873. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6874. }
  6875. return true;
  6876. });
  6877. }),
  6878. addLineWidget: docMethodOp(function(handle, node, options) {
  6879. return addLineWidget(this, handle, node, options);
  6880. }),
  6881. removeLineWidget: function(widget) { widget.clear(); },
  6882. markText: function(from, to, options) {
  6883. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
  6884. },
  6885. setBookmark: function(pos, options) {
  6886. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6887. insertLeft: options && options.insertLeft,
  6888. clearWhenEmpty: false, shared: options && options.shared,
  6889. handleMouseEvents: options && options.handleMouseEvents};
  6890. pos = clipPos(this, pos);
  6891. return markText(this, pos, pos, realOpts, "bookmark");
  6892. },
  6893. findMarksAt: function(pos) {
  6894. pos = clipPos(this, pos);
  6895. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6896. if (spans) for (var i = 0; i < spans.length; ++i) {
  6897. var span = spans[i];
  6898. if ((span.from == null || span.from <= pos.ch) &&
  6899. (span.to == null || span.to >= pos.ch))
  6900. markers.push(span.marker.parent || span.marker);
  6901. }
  6902. return markers;
  6903. },
  6904. findMarks: function(from, to, filter) {
  6905. from = clipPos(this, from); to = clipPos(this, to);
  6906. var found = [], lineNo = from.line;
  6907. this.iter(from.line, to.line + 1, function(line) {
  6908. var spans = line.markedSpans;
  6909. if (spans) for (var i = 0; i < spans.length; i++) {
  6910. var span = spans[i];
  6911. if (!(lineNo == from.line && from.ch > span.to ||
  6912. span.from == null && lineNo != from.line||
  6913. lineNo == to.line && span.from > to.ch) &&
  6914. (!filter || filter(span.marker)))
  6915. found.push(span.marker.parent || span.marker);
  6916. }
  6917. ++lineNo;
  6918. });
  6919. return found;
  6920. },
  6921. getAllMarks: function() {
  6922. var markers = [];
  6923. this.iter(function(line) {
  6924. var sps = line.markedSpans;
  6925. if (sps) for (var i = 0; i < sps.length; ++i)
  6926. if (sps[i].from != null) markers.push(sps[i].marker);
  6927. });
  6928. return markers;
  6929. },
  6930. posFromIndex: function(off) {
  6931. var ch, lineNo = this.first;
  6932. this.iter(function(line) {
  6933. var sz = line.text.length + 1;
  6934. if (sz > off) { ch = off; return true; }
  6935. off -= sz;
  6936. ++lineNo;
  6937. });
  6938. return clipPos(this, Pos(lineNo, ch));
  6939. },
  6940. indexFromPos: function (coords) {
  6941. coords = clipPos(this, coords);
  6942. var index = coords.ch;
  6943. if (coords.line < this.first || coords.ch < 0) return 0;
  6944. this.iter(this.first, coords.line, function (line) {
  6945. index += line.text.length + 1;
  6946. });
  6947. return index;
  6948. },
  6949. copy: function(copyHistory) {
  6950. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  6951. this.modeOption, this.first, this.lineSep);
  6952. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6953. doc.sel = this.sel;
  6954. doc.extend = false;
  6955. if (copyHistory) {
  6956. doc.history.undoDepth = this.history.undoDepth;
  6957. doc.setHistory(this.getHistory());
  6958. }
  6959. return doc;
  6960. },
  6961. linkedDoc: function(options) {
  6962. if (!options) options = {};
  6963. var from = this.first, to = this.first + this.size;
  6964. if (options.from != null && options.from > from) from = options.from;
  6965. if (options.to != null && options.to < to) to = options.to;
  6966. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
  6967. if (options.sharedHist) copy.history = this.history;
  6968. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6969. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6970. copySharedMarkers(copy, findSharedMarkers(this));
  6971. return copy;
  6972. },
  6973. unlinkDoc: function(other) {
  6974. if (other instanceof CodeMirror) other = other.doc;
  6975. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6976. var link = this.linked[i];
  6977. if (link.doc != other) continue;
  6978. this.linked.splice(i, 1);
  6979. other.unlinkDoc(this);
  6980. detachSharedMarkers(findSharedMarkers(this));
  6981. break;
  6982. }
  6983. // If the histories were shared, split them again
  6984. if (other.history == this.history) {
  6985. var splitIds = [other.id];
  6986. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  6987. other.history = new History(null);
  6988. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6989. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6990. }
  6991. },
  6992. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  6993. getMode: function() {return this.mode;},
  6994. getEditor: function() {return this.cm;},
  6995. splitLines: function(str) {
  6996. if (this.lineSep) return str.split(this.lineSep);
  6997. return splitLinesAuto(str);
  6998. },
  6999. lineSeparator: function() { return this.lineSep || "\n"; }
  7000. });
  7001. // Public alias.
  7002. Doc.prototype.eachLine = Doc.prototype.iter;
  7003. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  7004. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  7005. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  7006. CodeMirror.prototype[prop] = (function(method) {
  7007. return function() {return method.apply(this.doc, arguments);};
  7008. })(Doc.prototype[prop]);
  7009. eventMixin(Doc);
  7010. // Call f for all linked documents.
  7011. function linkedDocs(doc, f, sharedHistOnly) {
  7012. function propagate(doc, skip, sharedHist) {
  7013. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  7014. var rel = doc.linked[i];
  7015. if (rel.doc == skip) continue;
  7016. var shared = sharedHist && rel.sharedHist;
  7017. if (sharedHistOnly && !shared) continue;
  7018. f(rel.doc, shared);
  7019. propagate(rel.doc, doc, shared);
  7020. }
  7021. }
  7022. propagate(doc, null, true);
  7023. }
  7024. // Attach a document to an editor.
  7025. function attachDoc(cm, doc) {
  7026. if (doc.cm) throw new Error("This document is already in use.");
  7027. cm.doc = doc;
  7028. doc.cm = cm;
  7029. estimateLineHeights(cm);
  7030. loadMode(cm);
  7031. if (!cm.options.lineWrapping) findMaxLine(cm);
  7032. cm.options.mode = doc.modeOption;
  7033. regChange(cm);
  7034. }
  7035. // LINE UTILITIES
  7036. // Find the line object corresponding to the given line number.
  7037. function getLine(doc, n) {
  7038. n -= doc.first;
  7039. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  7040. for (var chunk = doc; !chunk.lines;) {
  7041. for (var i = 0;; ++i) {
  7042. var child = chunk.children[i], sz = child.chunkSize();
  7043. if (n < sz) { chunk = child; break; }
  7044. n -= sz;
  7045. }
  7046. }
  7047. return chunk.lines[n];
  7048. }
  7049. // Get the part of a document between two positions, as an array of
  7050. // strings.
  7051. function getBetween(doc, start, end) {
  7052. var out = [], n = start.line;
  7053. doc.iter(start.line, end.line + 1, function(line) {
  7054. var text = line.text;
  7055. if (n == end.line) text = text.slice(0, end.ch);
  7056. if (n == start.line) text = text.slice(start.ch);
  7057. out.push(text);
  7058. ++n;
  7059. });
  7060. return out;
  7061. }
  7062. // Get the lines between from and to, as array of strings.
  7063. function getLines(doc, from, to) {
  7064. var out = [];
  7065. doc.iter(from, to, function(line) { out.push(line.text); });
  7066. return out;
  7067. }
  7068. // Update the height of a line, propagating the height change
  7069. // upwards to parent nodes.
  7070. function updateLineHeight(line, height) {
  7071. var diff = height - line.height;
  7072. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  7073. }
  7074. // Given a line object, find its line number by walking up through
  7075. // its parent links.
  7076. function lineNo(line) {
  7077. if (line.parent == null) return null;
  7078. var cur = line.parent, no = indexOf(cur.lines, line);
  7079. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  7080. for (var i = 0;; ++i) {
  7081. if (chunk.children[i] == cur) break;
  7082. no += chunk.children[i].chunkSize();
  7083. }
  7084. }
  7085. return no + cur.first;
  7086. }
  7087. // Find the line at the given vertical position, using the height
  7088. // information in the document tree.
  7089. function lineAtHeight(chunk, h) {
  7090. var n = chunk.first;
  7091. outer: do {
  7092. for (var i = 0; i < chunk.children.length; ++i) {
  7093. var child = chunk.children[i], ch = child.height;
  7094. if (h < ch) { chunk = child; continue outer; }
  7095. h -= ch;
  7096. n += child.chunkSize();
  7097. }
  7098. return n;
  7099. } while (!chunk.lines);
  7100. for (var i = 0; i < chunk.lines.length; ++i) {
  7101. var line = chunk.lines[i], lh = line.height;
  7102. if (h < lh) break;
  7103. h -= lh;
  7104. }
  7105. return n + i;
  7106. }
  7107. // Find the height above the given line.
  7108. function heightAtLine(lineObj) {
  7109. lineObj = visualLine(lineObj);
  7110. var h = 0, chunk = lineObj.parent;
  7111. for (var i = 0; i < chunk.lines.length; ++i) {
  7112. var line = chunk.lines[i];
  7113. if (line == lineObj) break;
  7114. else h += line.height;
  7115. }
  7116. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  7117. for (var i = 0; i < p.children.length; ++i) {
  7118. var cur = p.children[i];
  7119. if (cur == chunk) break;
  7120. else h += cur.height;
  7121. }
  7122. }
  7123. return h;
  7124. }
  7125. // Get the bidi ordering for the given line (and cache it). Returns
  7126. // false for lines that are fully left-to-right, and an array of
  7127. // BidiSpan objects otherwise.
  7128. function getOrder(line) {
  7129. var order = line.order;
  7130. if (order == null) order = line.order = bidiOrdering(line.text);
  7131. return order;
  7132. }
  7133. // HISTORY
  7134. function History(startGen) {
  7135. // Arrays of change events and selections. Doing something adds an
  7136. // event to done and clears undo. Undoing moves events from done
  7137. // to undone, redoing moves them in the other direction.
  7138. this.done = []; this.undone = [];
  7139. this.undoDepth = Infinity;
  7140. // Used to track when changes can be merged into a single undo
  7141. // event
  7142. this.lastModTime = this.lastSelTime = 0;
  7143. this.lastOp = this.lastSelOp = null;
  7144. this.lastOrigin = this.lastSelOrigin = null;
  7145. // Used by the isClean() method
  7146. this.generation = this.maxGeneration = startGen || 1;
  7147. }
  7148. // Create a history change event from an updateDoc-style change
  7149. // object.
  7150. function historyChangeFromChange(doc, change) {
  7151. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  7152. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  7153. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  7154. return histChange;
  7155. }
  7156. // Pop all selection events off the end of a history array. Stop at
  7157. // a change event.
  7158. function clearSelectionEvents(array) {
  7159. while (array.length) {
  7160. var last = lst(array);
  7161. if (last.ranges) array.pop();
  7162. else break;
  7163. }
  7164. }
  7165. // Find the top change event in the history. Pop off selection
  7166. // events that are in the way.
  7167. function lastChangeEvent(hist, force) {
  7168. if (force) {
  7169. clearSelectionEvents(hist.done);
  7170. return lst(hist.done);
  7171. } else if (hist.done.length && !lst(hist.done).ranges) {
  7172. return lst(hist.done);
  7173. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  7174. hist.done.pop();
  7175. return lst(hist.done);
  7176. }
  7177. }
  7178. // Register a change in the history. Merges changes that are within
  7179. // a single operation, ore are close together with an origin that
  7180. // allows merging (starting with "+") into a single event.
  7181. function addChangeToHistory(doc, change, selAfter, opId) {
  7182. var hist = doc.history;
  7183. hist.undone.length = 0;
  7184. var time = +new Date, cur;
  7185. if ((hist.lastOp == opId ||
  7186. hist.lastOrigin == change.origin && change.origin &&
  7187. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  7188. change.origin.charAt(0) == "*")) &&
  7189. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  7190. // Merge this change into the last event
  7191. var last = lst(cur.changes);
  7192. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  7193. // Optimized case for simple insertion -- don't want to add
  7194. // new changesets for every character typed
  7195. last.to = changeEnd(change);
  7196. } else {
  7197. // Add new sub-event
  7198. cur.changes.push(historyChangeFromChange(doc, change));
  7199. }
  7200. } else {
  7201. // Can not be merged, start a new event.
  7202. var before = lst(hist.done);
  7203. if (!before || !before.ranges)
  7204. pushSelectionToHistory(doc.sel, hist.done);
  7205. cur = {changes: [historyChangeFromChange(doc, change)],
  7206. generation: hist.generation};
  7207. hist.done.push(cur);
  7208. while (hist.done.length > hist.undoDepth) {
  7209. hist.done.shift();
  7210. if (!hist.done[0].ranges) hist.done.shift();
  7211. }
  7212. }
  7213. hist.done.push(selAfter);
  7214. hist.generation = ++hist.maxGeneration;
  7215. hist.lastModTime = hist.lastSelTime = time;
  7216. hist.lastOp = hist.lastSelOp = opId;
  7217. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7218. if (!last) signal(doc, "historyAdded");
  7219. }
  7220. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7221. var ch = origin.charAt(0);
  7222. return ch == "*" ||
  7223. ch == "+" &&
  7224. prev.ranges.length == sel.ranges.length &&
  7225. prev.somethingSelected() == sel.somethingSelected() &&
  7226. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7227. }
  7228. // Called whenever the selection changes, sets the new selection as
  7229. // the pending selection in the history, and pushes the old pending
  7230. // selection into the 'done' array when it was significantly
  7231. // different (in number of selected ranges, emptiness, or time).
  7232. function addSelectionToHistory(doc, sel, opId, options) {
  7233. var hist = doc.history, origin = options && options.origin;
  7234. // A new event is started when the previous origin does not match
  7235. // the current, or the origins don't allow matching. Origins
  7236. // starting with * are always merged, those starting with + are
  7237. // merged when similar and close together in time.
  7238. if (opId == hist.lastSelOp ||
  7239. (origin && hist.lastSelOrigin == origin &&
  7240. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7241. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7242. hist.done[hist.done.length - 1] = sel;
  7243. else
  7244. pushSelectionToHistory(sel, hist.done);
  7245. hist.lastSelTime = +new Date;
  7246. hist.lastSelOrigin = origin;
  7247. hist.lastSelOp = opId;
  7248. if (options && options.clearRedo !== false)
  7249. clearSelectionEvents(hist.undone);
  7250. }
  7251. function pushSelectionToHistory(sel, dest) {
  7252. var top = lst(dest);
  7253. if (!(top && top.ranges && top.equals(sel)))
  7254. dest.push(sel);
  7255. }
  7256. // Used to store marked span information in the history.
  7257. function attachLocalSpans(doc, change, from, to) {
  7258. var existing = change["spans_" + doc.id], n = 0;
  7259. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  7260. if (line.markedSpans)
  7261. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7262. ++n;
  7263. });
  7264. }
  7265. // When un/re-doing restores text containing marked spans, those
  7266. // that have been explicitly cleared should not be restored.
  7267. function removeClearedSpans(spans) {
  7268. if (!spans) return null;
  7269. for (var i = 0, out; i < spans.length; ++i) {
  7270. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7271. else if (out) out.push(spans[i]);
  7272. }
  7273. return !out ? spans : out.length ? out : null;
  7274. }
  7275. // Retrieve and filter the old marked spans stored in a change event.
  7276. function getOldSpans(doc, change) {
  7277. var found = change["spans_" + doc.id];
  7278. if (!found) return null;
  7279. for (var i = 0, nw = []; i < change.text.length; ++i)
  7280. nw.push(removeClearedSpans(found[i]));
  7281. return nw;
  7282. }
  7283. // Used both to provide a JSON-safe object in .getHistory, and, when
  7284. // detaching a document, to split the history in two
  7285. function copyHistoryArray(events, newGroup, instantiateSel) {
  7286. for (var i = 0, copy = []; i < events.length; ++i) {
  7287. var event = events[i];
  7288. if (event.ranges) {
  7289. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7290. continue;
  7291. }
  7292. var changes = event.changes, newChanges = [];
  7293. copy.push({changes: newChanges});
  7294. for (var j = 0; j < changes.length; ++j) {
  7295. var change = changes[j], m;
  7296. newChanges.push({from: change.from, to: change.to, text: change.text});
  7297. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7298. if (indexOf(newGroup, Number(m[1])) > -1) {
  7299. lst(newChanges)[prop] = change[prop];
  7300. delete change[prop];
  7301. }
  7302. }
  7303. }
  7304. }
  7305. return copy;
  7306. }
  7307. // Rebasing/resetting history to deal with externally-sourced changes
  7308. function rebaseHistSelSingle(pos, from, to, diff) {
  7309. if (to < pos.line) {
  7310. pos.line += diff;
  7311. } else if (from < pos.line) {
  7312. pos.line = from;
  7313. pos.ch = 0;
  7314. }
  7315. }
  7316. // Tries to rebase an array of history events given a change in the
  7317. // document. If the change touches the same lines as the event, the
  7318. // event, and everything 'behind' it, is discarded. If the change is
  7319. // before the event, the event's positions are updated. Uses a
  7320. // copy-on-write scheme for the positions, to avoid having to
  7321. // reallocate them all on every rebase, but also avoid problems with
  7322. // shared position objects being unsafely updated.
  7323. function rebaseHistArray(array, from, to, diff) {
  7324. for (var i = 0; i < array.length; ++i) {
  7325. var sub = array[i], ok = true;
  7326. if (sub.ranges) {
  7327. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7328. for (var j = 0; j < sub.ranges.length; j++) {
  7329. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7330. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7331. }
  7332. continue;
  7333. }
  7334. for (var j = 0; j < sub.changes.length; ++j) {
  7335. var cur = sub.changes[j];
  7336. if (to < cur.from.line) {
  7337. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7338. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7339. } else if (from <= cur.to.line) {
  7340. ok = false;
  7341. break;
  7342. }
  7343. }
  7344. if (!ok) {
  7345. array.splice(0, i + 1);
  7346. i = 0;
  7347. }
  7348. }
  7349. }
  7350. function rebaseHist(hist, change) {
  7351. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7352. rebaseHistArray(hist.done, from, to, diff);
  7353. rebaseHistArray(hist.undone, from, to, diff);
  7354. }
  7355. // EVENT UTILITIES
  7356. // Due to the fact that we still support jurassic IE versions, some
  7357. // compatibility wrappers are needed.
  7358. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  7359. if (e.preventDefault) e.preventDefault();
  7360. else e.returnValue = false;
  7361. };
  7362. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  7363. if (e.stopPropagation) e.stopPropagation();
  7364. else e.cancelBubble = true;
  7365. };
  7366. function e_defaultPrevented(e) {
  7367. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7368. }
  7369. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  7370. function e_target(e) {return e.target || e.srcElement;}
  7371. function e_button(e) {
  7372. var b = e.which;
  7373. if (b == null) {
  7374. if (e.button & 1) b = 1;
  7375. else if (e.button & 2) b = 3;
  7376. else if (e.button & 4) b = 2;
  7377. }
  7378. if (mac && e.ctrlKey && b == 1) b = 3;
  7379. return b;
  7380. }
  7381. // EVENT HANDLING
  7382. // Lightweight event framework. on/off also work on DOM nodes,
  7383. // registering native DOM handlers.
  7384. var on = CodeMirror.on = function(emitter, type, f) {
  7385. if (emitter.addEventListener)
  7386. emitter.addEventListener(type, f, false);
  7387. else if (emitter.attachEvent)
  7388. emitter.attachEvent("on" + type, f);
  7389. else {
  7390. var map = emitter._handlers || (emitter._handlers = {});
  7391. var arr = map[type] || (map[type] = []);
  7392. arr.push(f);
  7393. }
  7394. };
  7395. var noHandlers = []
  7396. function getHandlers(emitter, type, copy) {
  7397. var arr = emitter._handlers && emitter._handlers[type]
  7398. if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
  7399. else return arr || noHandlers
  7400. }
  7401. var off = CodeMirror.off = function(emitter, type, f) {
  7402. if (emitter.removeEventListener)
  7403. emitter.removeEventListener(type, f, false);
  7404. else if (emitter.detachEvent)
  7405. emitter.detachEvent("on" + type, f);
  7406. else {
  7407. var handlers = getHandlers(emitter, type, false)
  7408. for (var i = 0; i < handlers.length; ++i)
  7409. if (handlers[i] == f) { handlers.splice(i, 1); break; }
  7410. }
  7411. };
  7412. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  7413. var handlers = getHandlers(emitter, type, true)
  7414. if (!handlers.length) return;
  7415. var args = Array.prototype.slice.call(arguments, 2);
  7416. for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
  7417. };
  7418. var orphanDelayedCallbacks = null;
  7419. // Often, we want to signal events at a point where we are in the
  7420. // middle of some work, but don't want the handler to start calling
  7421. // other methods on the editor, which might be in an inconsistent
  7422. // state or simply not expect any other events to happen.
  7423. // signalLater looks whether there are any handlers, and schedules
  7424. // them to be executed when the last operation ends, or, if no
  7425. // operation is active, when a timeout fires.
  7426. function signalLater(emitter, type /*, values...*/) {
  7427. var arr = getHandlers(emitter, type, false)
  7428. if (!arr.length) return;
  7429. var args = Array.prototype.slice.call(arguments, 2), list;
  7430. if (operationGroup) {
  7431. list = operationGroup.delayedCallbacks;
  7432. } else if (orphanDelayedCallbacks) {
  7433. list = orphanDelayedCallbacks;
  7434. } else {
  7435. list = orphanDelayedCallbacks = [];
  7436. setTimeout(fireOrphanDelayed, 0);
  7437. }
  7438. function bnd(f) {return function(){f.apply(null, args);};};
  7439. for (var i = 0; i < arr.length; ++i)
  7440. list.push(bnd(arr[i]));
  7441. }
  7442. function fireOrphanDelayed() {
  7443. var delayed = orphanDelayedCallbacks;
  7444. orphanDelayedCallbacks = null;
  7445. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7446. }
  7447. // The DOM events that CodeMirror handles can be overridden by
  7448. // registering a (non-DOM) handler on the editor for the event name,
  7449. // and preventDefault-ing the event in that handler.
  7450. function signalDOMEvent(cm, e, override) {
  7451. if (typeof e == "string")
  7452. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  7453. signal(cm, override || e.type, cm, e);
  7454. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7455. }
  7456. function signalCursorActivity(cm) {
  7457. var arr = cm._handlers && cm._handlers.cursorActivity;
  7458. if (!arr) return;
  7459. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7460. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7461. set.push(arr[i]);
  7462. }
  7463. function hasHandler(emitter, type) {
  7464. return getHandlers(emitter, type).length > 0
  7465. }
  7466. // Add on and off methods to a constructor's prototype, to make
  7467. // registering events on such objects more convenient.
  7468. function eventMixin(ctor) {
  7469. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7470. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7471. }
  7472. // MISC UTILITIES
  7473. // Number of pixels added to scroller and sizer to hide scrollbar
  7474. var scrollerGap = 30;
  7475. // Returned or thrown by various protocols to signal 'I'm not
  7476. // handling this'.
  7477. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  7478. // Reused option objects for setSelection & friends
  7479. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  7480. function Delayed() {this.id = null;}
  7481. Delayed.prototype.set = function(ms, f) {
  7482. clearTimeout(this.id);
  7483. this.id = setTimeout(f, ms);
  7484. };
  7485. // Counts the column offset in a string, taking tabs into account.
  7486. // Used mostly to find indentation.
  7487. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  7488. if (end == null) {
  7489. end = string.search(/[^\s\u00a0]/);
  7490. if (end == -1) end = string.length;
  7491. }
  7492. for (var i = startIndex || 0, n = startValue || 0;;) {
  7493. var nextTab = string.indexOf("\t", i);
  7494. if (nextTab < 0 || nextTab >= end)
  7495. return n + (end - i);
  7496. n += nextTab - i;
  7497. n += tabSize - (n % tabSize);
  7498. i = nextTab + 1;
  7499. }
  7500. };
  7501. // The inverse of countColumn -- find the offset that corresponds to
  7502. // a particular column.
  7503. var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
  7504. for (var pos = 0, col = 0;;) {
  7505. var nextTab = string.indexOf("\t", pos);
  7506. if (nextTab == -1) nextTab = string.length;
  7507. var skipped = nextTab - pos;
  7508. if (nextTab == string.length || col + skipped >= goal)
  7509. return pos + Math.min(skipped, goal - col);
  7510. col += nextTab - pos;
  7511. col += tabSize - (col % tabSize);
  7512. pos = nextTab + 1;
  7513. if (col >= goal) return pos;
  7514. }
  7515. }
  7516. var spaceStrs = [""];
  7517. function spaceStr(n) {
  7518. while (spaceStrs.length <= n)
  7519. spaceStrs.push(lst(spaceStrs) + " ");
  7520. return spaceStrs[n];
  7521. }
  7522. function lst(arr) { return arr[arr.length-1]; }
  7523. var selectInput = function(node) { node.select(); };
  7524. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7525. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7526. else if (ie) // Suppress mysterious IE10 errors
  7527. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  7528. function indexOf(array, elt) {
  7529. for (var i = 0; i < array.length; ++i)
  7530. if (array[i] == elt) return i;
  7531. return -1;
  7532. }
  7533. function map(array, f) {
  7534. var out = [];
  7535. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7536. return out;
  7537. }
  7538. function nothing() {}
  7539. function createObj(base, props) {
  7540. var inst;
  7541. if (Object.create) {
  7542. inst = Object.create(base);
  7543. } else {
  7544. nothing.prototype = base;
  7545. inst = new nothing();
  7546. }
  7547. if (props) copyObj(props, inst);
  7548. return inst;
  7549. };
  7550. function copyObj(obj, target, overwrite) {
  7551. if (!target) target = {};
  7552. for (var prop in obj)
  7553. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7554. target[prop] = obj[prop];
  7555. return target;
  7556. }
  7557. function bind(f) {
  7558. var args = Array.prototype.slice.call(arguments, 1);
  7559. return function(){return f.apply(null, args);};
  7560. }
  7561. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7562. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  7563. return /\w/.test(ch) || ch > "\x80" &&
  7564. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7565. };
  7566. function isWordChar(ch, helper) {
  7567. if (!helper) return isWordCharBasic(ch);
  7568. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7569. return helper.test(ch);
  7570. }
  7571. function isEmpty(obj) {
  7572. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7573. return true;
  7574. }
  7575. // Extending unicode characters. A series of a non-extending char +
  7576. // any number of extending chars is treated as a single unit as far
  7577. // as editing and measuring is concerned. This is not fully correct,
  7578. // since some scripts/fonts/browsers also treat other configurations
  7579. // of code points as a group.
  7580. 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]/;
  7581. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7582. // DOM UTILITIES
  7583. function elt(tag, content, className, style) {
  7584. var e = document.createElement(tag);
  7585. if (className) e.className = className;
  7586. if (style) e.style.cssText = style;
  7587. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7588. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7589. return e;
  7590. }
  7591. var range;
  7592. if (document.createRange) range = function(node, start, end, endNode) {
  7593. var r = document.createRange();
  7594. r.setEnd(endNode || node, end);
  7595. r.setStart(node, start);
  7596. return r;
  7597. };
  7598. else range = function(node, start, end) {
  7599. var r = document.body.createTextRange();
  7600. try { r.moveToElementText(node.parentNode); }
  7601. catch(e) { return r; }
  7602. r.collapse(true);
  7603. r.moveEnd("character", end);
  7604. r.moveStart("character", start);
  7605. return r;
  7606. };
  7607. function removeChildren(e) {
  7608. for (var count = e.childNodes.length; count > 0; --count)
  7609. e.removeChild(e.firstChild);
  7610. return e;
  7611. }
  7612. function removeChildrenAndAdd(parent, e) {
  7613. return removeChildren(parent).appendChild(e);
  7614. }
  7615. var contains = CodeMirror.contains = function(parent, child) {
  7616. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7617. child = child.parentNode;
  7618. if (parent.contains)
  7619. return parent.contains(child);
  7620. do {
  7621. if (child.nodeType == 11) child = child.host;
  7622. if (child == parent) return true;
  7623. } while (child = child.parentNode);
  7624. };
  7625. function activeElt() {
  7626. var activeElement = document.activeElement;
  7627. while (activeElement && activeElement.root && activeElement.root.activeElement)
  7628. activeElement = activeElement.root.activeElement;
  7629. return activeElement;
  7630. }
  7631. // Older versions of IE throws unspecified error when touching
  7632. // document.activeElement in some cases (during loading, in iframe)
  7633. if (ie && ie_version < 11) activeElt = function() {
  7634. try { return document.activeElement; }
  7635. catch(e) { return document.body; }
  7636. };
  7637. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7638. var rmClass = CodeMirror.rmClass = function(node, cls) {
  7639. var current = node.className;
  7640. var match = classTest(cls).exec(current);
  7641. if (match) {
  7642. var after = current.slice(match.index + match[0].length);
  7643. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7644. }
  7645. };
  7646. var addClass = CodeMirror.addClass = function(node, cls) {
  7647. var current = node.className;
  7648. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7649. };
  7650. function joinClasses(a, b) {
  7651. var as = a.split(" ");
  7652. for (var i = 0; i < as.length; i++)
  7653. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7654. return b;
  7655. }
  7656. // WINDOW-WIDE EVENTS
  7657. // These must be handled carefully, because naively registering a
  7658. // handler for each editor will cause the editors to never be
  7659. // garbage collected.
  7660. function forEachCodeMirror(f) {
  7661. if (!document.body.getElementsByClassName) return;
  7662. var byClass = document.body.getElementsByClassName("CodeMirror");
  7663. for (var i = 0; i < byClass.length; i++) {
  7664. var cm = byClass[i].CodeMirror;
  7665. if (cm) f(cm);
  7666. }
  7667. }
  7668. var globalsRegistered = false;
  7669. function ensureGlobalHandlers() {
  7670. if (globalsRegistered) return;
  7671. registerGlobalHandlers();
  7672. globalsRegistered = true;
  7673. }
  7674. function registerGlobalHandlers() {
  7675. // When the window resizes, we need to refresh active editors.
  7676. var resizeTimer;
  7677. on(window, "resize", function() {
  7678. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  7679. resizeTimer = null;
  7680. forEachCodeMirror(onResize);
  7681. }, 100);
  7682. });
  7683. // When the window loses focus, we want to show the editor as blurred
  7684. on(window, "blur", function() {
  7685. forEachCodeMirror(onBlur);
  7686. });
  7687. }
  7688. // FEATURE DETECTION
  7689. // Detect drag-and-drop
  7690. var dragAndDrop = function() {
  7691. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7692. // couldn't get it to work yet.
  7693. if (ie && ie_version < 9) return false;
  7694. var div = elt('div');
  7695. return "draggable" in div || "dragDrop" in div;
  7696. }();
  7697. var zwspSupported;
  7698. function zeroWidthElement(measure) {
  7699. if (zwspSupported == null) {
  7700. var test = elt("span", "\u200b");
  7701. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7702. if (measure.firstChild.offsetHeight != 0)
  7703. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7704. }
  7705. var node = zwspSupported ? elt("span", "\u200b") :
  7706. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7707. node.setAttribute("cm-text", "");
  7708. return node;
  7709. }
  7710. // Feature-detect IE's crummy client rect reporting for bidi text
  7711. var badBidiRects;
  7712. function hasBadBidiRects(measure) {
  7713. if (badBidiRects != null) return badBidiRects;
  7714. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7715. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7716. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7717. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7718. return badBidiRects = (r1.right - r0.right < 3);
  7719. }
  7720. // See if "".split is the broken IE version, if so, provide an
  7721. // alternative way to split lines.
  7722. var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7723. var pos = 0, result = [], l = string.length;
  7724. while (pos <= l) {
  7725. var nl = string.indexOf("\n", pos);
  7726. if (nl == -1) nl = string.length;
  7727. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7728. var rt = line.indexOf("\r");
  7729. if (rt != -1) {
  7730. result.push(line.slice(0, rt));
  7731. pos += rt + 1;
  7732. } else {
  7733. result.push(line);
  7734. pos = nl + 1;
  7735. }
  7736. }
  7737. return result;
  7738. } : function(string){return string.split(/\r\n?|\n/);};
  7739. var hasSelection = window.getSelection ? function(te) {
  7740. try { return te.selectionStart != te.selectionEnd; }
  7741. catch(e) { return false; }
  7742. } : function(te) {
  7743. try {var range = te.ownerDocument.selection.createRange();}
  7744. catch(e) {}
  7745. if (!range || range.parentElement() != te) return false;
  7746. return range.compareEndPoints("StartToEnd", range) != 0;
  7747. };
  7748. var hasCopyEvent = (function() {
  7749. var e = elt("div");
  7750. if ("oncopy" in e) return true;
  7751. e.setAttribute("oncopy", "return;");
  7752. return typeof e.oncopy == "function";
  7753. })();
  7754. var badZoomedRects = null;
  7755. function hasBadZoomedRects(measure) {
  7756. if (badZoomedRects != null) return badZoomedRects;
  7757. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7758. var normal = node.getBoundingClientRect();
  7759. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7760. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7761. }
  7762. // KEY NAMES
  7763. var keyNames = CodeMirror.keyNames = {
  7764. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7765. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7766. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7767. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  7768. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  7769. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7770. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7771. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7772. };
  7773. (function() {
  7774. // Number keys
  7775. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7776. // Alphabetic keys
  7777. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7778. // Function keys
  7779. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7780. })();
  7781. // BIDI HELPERS
  7782. function iterateBidiSections(order, from, to, f) {
  7783. if (!order) return f(from, to, "ltr");
  7784. var found = false;
  7785. for (var i = 0; i < order.length; ++i) {
  7786. var part = order[i];
  7787. if (part.from < to && part.to > from || from == to && part.to == from) {
  7788. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7789. found = true;
  7790. }
  7791. }
  7792. if (!found) f(from, to, "ltr");
  7793. }
  7794. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7795. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7796. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7797. function lineRight(line) {
  7798. var order = getOrder(line);
  7799. if (!order) return line.text.length;
  7800. return bidiRight(lst(order));
  7801. }
  7802. function lineStart(cm, lineN) {
  7803. var line = getLine(cm.doc, lineN);
  7804. var visual = visualLine(line);
  7805. if (visual != line) lineN = lineNo(visual);
  7806. var order = getOrder(visual);
  7807. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7808. return Pos(lineN, ch);
  7809. }
  7810. function lineEnd(cm, lineN) {
  7811. var merged, line = getLine(cm.doc, lineN);
  7812. while (merged = collapsedSpanAtEnd(line)) {
  7813. line = merged.find(1, true).line;
  7814. lineN = null;
  7815. }
  7816. var order = getOrder(line);
  7817. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7818. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7819. }
  7820. function lineStartSmart(cm, pos) {
  7821. var start = lineStart(cm, pos.line);
  7822. var line = getLine(cm.doc, start.line);
  7823. var order = getOrder(line);
  7824. if (!order || order[0].level == 0) {
  7825. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7826. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7827. return Pos(start.line, inWS ? 0 : firstNonWS);
  7828. }
  7829. return start;
  7830. }
  7831. function compareBidiLevel(order, a, b) {
  7832. var linedir = order[0].level;
  7833. if (a == linedir) return true;
  7834. if (b == linedir) return false;
  7835. return a < b;
  7836. }
  7837. var bidiOther;
  7838. function getBidiPartAt(order, pos) {
  7839. bidiOther = null;
  7840. for (var i = 0, found; i < order.length; ++i) {
  7841. var cur = order[i];
  7842. if (cur.from < pos && cur.to > pos) return i;
  7843. if ((cur.from == pos || cur.to == pos)) {
  7844. if (found == null) {
  7845. found = i;
  7846. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7847. if (cur.from != cur.to) bidiOther = found;
  7848. return i;
  7849. } else {
  7850. if (cur.from != cur.to) bidiOther = i;
  7851. return found;
  7852. }
  7853. }
  7854. }
  7855. return found;
  7856. }
  7857. function moveInLine(line, pos, dir, byUnit) {
  7858. if (!byUnit) return pos + dir;
  7859. do pos += dir;
  7860. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7861. return pos;
  7862. }
  7863. // This is needed in order to move 'visually' through bi-directional
  7864. // text -- i.e., pressing left should make the cursor go left, even
  7865. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7866. // LTR text touch each other. This often requires the cursor offset
  7867. // to move more than one unit, in order to visually move one unit.
  7868. function moveVisually(line, start, dir, byUnit) {
  7869. var bidi = getOrder(line);
  7870. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7871. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7872. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7873. for (;;) {
  7874. if (target > part.from && target < part.to) return target;
  7875. if (target == part.from || target == part.to) {
  7876. if (getBidiPartAt(bidi, target) == pos) return target;
  7877. part = bidi[pos += dir];
  7878. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7879. } else {
  7880. part = bidi[pos += dir];
  7881. if (!part) return null;
  7882. if ((dir > 0) == part.level % 2)
  7883. target = moveInLine(line, part.to, -1, byUnit);
  7884. else
  7885. target = moveInLine(line, part.from, 1, byUnit);
  7886. }
  7887. }
  7888. }
  7889. function moveLogically(line, start, dir, byUnit) {
  7890. var target = start + dir;
  7891. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7892. return target < 0 || target > line.text.length ? null : target;
  7893. }
  7894. // Bidirectional ordering algorithm
  7895. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7896. // that this (partially) implements.
  7897. // One-char codes used for character types:
  7898. // L (L): Left-to-Right
  7899. // R (R): Right-to-Left
  7900. // r (AL): Right-to-Left Arabic
  7901. // 1 (EN): European Number
  7902. // + (ES): European Number Separator
  7903. // % (ET): European Number Terminator
  7904. // n (AN): Arabic Number
  7905. // , (CS): Common Number Separator
  7906. // m (NSM): Non-Spacing Mark
  7907. // b (BN): Boundary Neutral
  7908. // s (B): Paragraph Separator
  7909. // t (S): Segment Separator
  7910. // w (WS): Whitespace
  7911. // N (ON): Other Neutrals
  7912. // Returns null if characters are ordered as they appear
  7913. // (left-to-right), or an array of sections ({from, to, level}
  7914. // objects) in the order in which they occur visually.
  7915. var bidiOrdering = (function() {
  7916. // Character types for codepoints 0 to 0xff
  7917. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7918. // Character types for codepoints 0x600 to 0x6ff
  7919. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7920. function charType(code) {
  7921. if (code <= 0xf7) return lowTypes.charAt(code);
  7922. else if (0x590 <= code && code <= 0x5f4) return "R";
  7923. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7924. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7925. else if (0x2000 <= code && code <= 0x200b) return "w";
  7926. else if (code == 0x200c) return "b";
  7927. else return "L";
  7928. }
  7929. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7930. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7931. // Browsers seem to always treat the boundaries of block elements as being L.
  7932. var outerType = "L";
  7933. function BidiSpan(level, from, to) {
  7934. this.level = level;
  7935. this.from = from; this.to = to;
  7936. }
  7937. return function(str) {
  7938. if (!bidiRE.test(str)) return false;
  7939. var len = str.length, types = [];
  7940. for (var i = 0, type; i < len; ++i)
  7941. types.push(type = charType(str.charCodeAt(i)));
  7942. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7943. // change the type of the NSM to the type of the previous
  7944. // character. If the NSM is at the start of the level run, it will
  7945. // get the type of sor.
  7946. for (var i = 0, prev = outerType; i < len; ++i) {
  7947. var type = types[i];
  7948. if (type == "m") types[i] = prev;
  7949. else prev = type;
  7950. }
  7951. // W2. Search backwards from each instance of a European number
  7952. // until the first strong type (R, L, AL, or sor) is found. If an
  7953. // AL is found, change the type of the European number to Arabic
  7954. // number.
  7955. // W3. Change all ALs to R.
  7956. for (var i = 0, cur = outerType; i < len; ++i) {
  7957. var type = types[i];
  7958. if (type == "1" && cur == "r") types[i] = "n";
  7959. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7960. }
  7961. // W4. A single European separator between two European numbers
  7962. // changes to a European number. A single common separator between
  7963. // two numbers of the same type changes to that type.
  7964. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7965. var type = types[i];
  7966. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  7967. else if (type == "," && prev == types[i+1] &&
  7968. (prev == "1" || prev == "n")) types[i] = prev;
  7969. prev = type;
  7970. }
  7971. // W5. A sequence of European terminators adjacent to European
  7972. // numbers changes to all European numbers.
  7973. // W6. Otherwise, separators and terminators change to Other
  7974. // Neutral.
  7975. for (var i = 0; i < len; ++i) {
  7976. var type = types[i];
  7977. if (type == ",") types[i] = "N";
  7978. else if (type == "%") {
  7979. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  7980. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7981. for (var j = i; j < end; ++j) types[j] = replace;
  7982. i = end - 1;
  7983. }
  7984. }
  7985. // W7. Search backwards from each instance of a European number
  7986. // until the first strong type (R, L, or sor) is found. If an L is
  7987. // found, then change the type of the European number to L.
  7988. for (var i = 0, cur = outerType; i < len; ++i) {
  7989. var type = types[i];
  7990. if (cur == "L" && type == "1") types[i] = "L";
  7991. else if (isStrong.test(type)) cur = type;
  7992. }
  7993. // N1. A sequence of neutrals takes the direction of the
  7994. // surrounding strong text if the text on both sides has the same
  7995. // direction. European and Arabic numbers act as if they were R in
  7996. // terms of their influence on neutrals. Start-of-level-run (sor)
  7997. // and end-of-level-run (eor) are used at level run boundaries.
  7998. // N2. Any remaining neutrals take the embedding direction.
  7999. for (var i = 0; i < len; ++i) {
  8000. if (isNeutral.test(types[i])) {
  8001. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  8002. var before = (i ? types[i-1] : outerType) == "L";
  8003. var after = (end < len ? types[end] : outerType) == "L";
  8004. var replace = before || after ? "L" : "R";
  8005. for (var j = i; j < end; ++j) types[j] = replace;
  8006. i = end - 1;
  8007. }
  8008. }
  8009. // Here we depart from the documented algorithm, in order to avoid
  8010. // building up an actual levels array. Since there are only three
  8011. // levels (0, 1, 2) in an implementation that doesn't take
  8012. // explicit embedding into account, we can build up the order on
  8013. // the fly, without following the level-based algorithm.
  8014. var order = [], m;
  8015. for (var i = 0; i < len;) {
  8016. if (countsAsLeft.test(types[i])) {
  8017. var start = i;
  8018. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  8019. order.push(new BidiSpan(0, start, i));
  8020. } else {
  8021. var pos = i, at = order.length;
  8022. for (++i; i < len && types[i] != "L"; ++i) {}
  8023. for (var j = pos; j < i;) {
  8024. if (countsAsNum.test(types[j])) {
  8025. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  8026. var nstart = j;
  8027. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  8028. order.splice(at, 0, new BidiSpan(2, nstart, j));
  8029. pos = j;
  8030. } else ++j;
  8031. }
  8032. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  8033. }
  8034. }
  8035. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  8036. order[0].from = m[0].length;
  8037. order.unshift(new BidiSpan(0, 0, m[0].length));
  8038. }
  8039. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  8040. lst(order).to -= m[0].length;
  8041. order.push(new BidiSpan(0, len - m[0].length, len));
  8042. }
  8043. if (order[0].level == 2)
  8044. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  8045. if (order[0].level != lst(order).level)
  8046. order.push(new BidiSpan(order[0].level, len, len));
  8047. return order;
  8048. };
  8049. })();
  8050. // THE END
  8051. CodeMirror.version = "5.11.0";
  8052. return CodeMirror;
  8053. });