codemirror.js 348 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935
  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 chromeOS = /\bCrOS\b/.test(userAgent);
  39. var windows = /win/i.test(platform);
  40. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  41. if (presto_version) presto_version = Number(presto_version[1]);
  42. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  43. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  44. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  45. var captureRightClick = gecko || (ie && ie_version >= 9);
  46. // Optimize some code when these features are not used.
  47. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  48. // EDITOR CONSTRUCTOR
  49. // A CodeMirror instance represents an editor. This is the object
  50. // that user code is usually dealing with.
  51. function CodeMirror(place, options) {
  52. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  53. this.options = options = options ? copyObj(options) : {};
  54. // Determine effective options based on given values and defaults.
  55. copyObj(defaults, options, false);
  56. setGuttersForLineNumbers(options);
  57. var doc = options.value;
  58. if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
  59. this.doc = doc;
  60. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  61. var display = this.display = new Display(place, doc, input);
  62. display.wrapper.CodeMirror = this;
  63. updateGutters(this);
  64. themeChanged(this);
  65. if (options.lineWrapping)
  66. this.display.wrapper.className += " CodeMirror-wrap";
  67. if (options.autofocus && !mobile) display.input.focus();
  68. initScrollbars(this);
  69. this.state = {
  70. keyMaps: [], // stores maps added by addKeyMap
  71. overlays: [], // highlighting overlays, as added by addOverlay
  72. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  73. overwrite: false,
  74. delayingBlurEvent: false,
  75. focused: false,
  76. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  77. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  78. selectingText: false,
  79. draggingText: false,
  80. highlight: new Delayed(), // stores highlight worker timeout
  81. keySeq: null, // Unfinished key sequence
  82. specialChars: null
  83. };
  84. var cm = this;
  85. // Override magic textarea content restore that IE sometimes does
  86. // on our hidden textarea on reload
  87. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  88. registerEventHandlers(this);
  89. ensureGlobalHandlers();
  90. startOperation(this);
  91. this.curOp.forceUpdate = true;
  92. attachDoc(this, doc);
  93. if ((options.autofocus && !mobile) || cm.hasFocus())
  94. setTimeout(bind(onFocus, this), 20);
  95. else
  96. onBlur(this);
  97. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  98. optionHandlers[opt](this, options[opt], Init);
  99. maybeUpdateLineNumberWidth(this);
  100. if (options.finishInit) options.finishInit(this);
  101. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  102. endOperation(this);
  103. // Suppress optimizelegibility in Webkit, since it breaks text
  104. // measuring on line wrapping boundaries.
  105. if (webkit && options.lineWrapping &&
  106. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  107. display.lineDiv.style.textRendering = "auto";
  108. }
  109. // DISPLAY CONSTRUCTOR
  110. // The display handles the DOM integration, both for input reading
  111. // and content drawing. It holds references to DOM nodes and
  112. // display-related state.
  113. function Display(place, doc, input) {
  114. var d = this;
  115. this.input = input;
  116. // Covers bottom-right square when both scrollbars are present.
  117. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  118. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  119. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  120. // and h scrollbar is present.
  121. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  122. d.gutterFiller.setAttribute("cm-not-content", "true");
  123. // Will contain the actual code, positioned to cover the viewport.
  124. d.lineDiv = elt("div", null, "CodeMirror-code");
  125. // Elements are added to these to represent selection and cursors.
  126. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  127. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  128. // A visibility: hidden element used to find the size of things.
  129. d.measure = elt("div", null, "CodeMirror-measure");
  130. // When lines outside of the viewport are measured, they are drawn in this.
  131. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  132. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  133. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  134. null, "position: relative; outline: none");
  135. // Moved around its parent to cover visible view.
  136. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  137. // Set to the height of the document, allowing scrolling.
  138. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  139. d.sizerWidth = null;
  140. // Behavior of elts with overflow: auto and padding is
  141. // inconsistent across browsers. This is used to ensure the
  142. // scrollable area is big enough.
  143. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  144. // Will contain the gutters, if any.
  145. d.gutters = elt("div", null, "CodeMirror-gutters");
  146. d.lineGutter = null;
  147. // Actual scrollable element.
  148. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  149. d.scroller.setAttribute("tabIndex", "-1");
  150. // The element in which the editor lives.
  151. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  152. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  153. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  154. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  155. if (place) {
  156. if (place.appendChild) place.appendChild(d.wrapper);
  157. else place(d.wrapper);
  158. }
  159. // Current rendered range (may be bigger than the view window).
  160. d.viewFrom = d.viewTo = doc.first;
  161. d.reportedViewFrom = d.reportedViewTo = doc.first;
  162. // Information about the rendered lines.
  163. d.view = [];
  164. d.renderedView = null;
  165. // Holds info about a single rendered line when it was rendered
  166. // for measurement, while not in view.
  167. d.externalMeasured = null;
  168. // Empty space (in pixels) above the view
  169. d.viewOffset = 0;
  170. d.lastWrapHeight = d.lastWrapWidth = 0;
  171. d.updateLineNumbers = null;
  172. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  173. d.scrollbarsClipped = false;
  174. // Used to only resize the line number gutter when necessary (when
  175. // the amount of lines crosses a boundary that makes its width change)
  176. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  177. // Set to true when a non-horizontal-scrolling line widget is
  178. // added. As an optimization, line widget aligning is skipped when
  179. // this is false.
  180. d.alignWidgets = false;
  181. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  182. // Tracks the maximum line length so that the horizontal scrollbar
  183. // can be kept static when scrolling.
  184. d.maxLine = null;
  185. d.maxLineLength = 0;
  186. d.maxLineChanged = false;
  187. // Used for measuring wheel scrolling granularity
  188. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  189. // True when shift is held down.
  190. d.shift = false;
  191. // Used to track whether anything happened since the context menu
  192. // was opened.
  193. d.selForContextMenu = null;
  194. d.activeTouch = null;
  195. input.init(d);
  196. }
  197. // STATE UPDATES
  198. // Used to get the editor into a consistent state again when options change.
  199. function loadMode(cm) {
  200. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  201. resetModeState(cm);
  202. }
  203. function resetModeState(cm) {
  204. cm.doc.iter(function(line) {
  205. if (line.stateAfter) line.stateAfter = null;
  206. if (line.styles) line.styles = null;
  207. });
  208. cm.doc.frontier = cm.doc.first;
  209. startWorker(cm, 100);
  210. cm.state.modeGen++;
  211. if (cm.curOp) regChange(cm);
  212. }
  213. function wrappingChanged(cm) {
  214. if (cm.options.lineWrapping) {
  215. addClass(cm.display.wrapper, "CodeMirror-wrap");
  216. cm.display.sizer.style.minWidth = "";
  217. cm.display.sizerWidth = null;
  218. } else {
  219. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  220. findMaxLine(cm);
  221. }
  222. estimateLineHeights(cm);
  223. regChange(cm);
  224. clearCaches(cm);
  225. setTimeout(function(){updateScrollbars(cm);}, 100);
  226. }
  227. // Returns a function that estimates the height of a line, to use as
  228. // first approximation until the line becomes visible (and is thus
  229. // properly measurable).
  230. function estimateHeight(cm) {
  231. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  232. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  233. return function(line) {
  234. if (lineIsHidden(cm.doc, line)) return 0;
  235. var widgetsHeight = 0;
  236. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  237. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  238. }
  239. if (wrapping)
  240. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  241. else
  242. return widgetsHeight + th;
  243. };
  244. }
  245. function estimateLineHeights(cm) {
  246. var doc = cm.doc, est = estimateHeight(cm);
  247. doc.iter(function(line) {
  248. var estHeight = est(line);
  249. if (estHeight != line.height) updateLineHeight(line, estHeight);
  250. });
  251. }
  252. function themeChanged(cm) {
  253. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  254. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  255. clearCaches(cm);
  256. }
  257. function guttersChanged(cm) {
  258. updateGutters(cm);
  259. regChange(cm);
  260. setTimeout(function(){alignHorizontally(cm);}, 20);
  261. }
  262. // Rebuild the gutter elements, ensure the margin to the left of the
  263. // code matches their width.
  264. function updateGutters(cm) {
  265. var gutters = cm.display.gutters, specs = cm.options.gutters;
  266. removeChildren(gutters);
  267. for (var i = 0; i < specs.length; ++i) {
  268. var gutterClass = specs[i];
  269. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  270. if (gutterClass == "CodeMirror-linenumbers") {
  271. cm.display.lineGutter = gElt;
  272. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  273. }
  274. }
  275. gutters.style.display = i ? "" : "none";
  276. updateGutterSpace(cm);
  277. }
  278. function updateGutterSpace(cm) {
  279. var width = cm.display.gutters.offsetWidth;
  280. cm.display.sizer.style.marginLeft = width + "px";
  281. }
  282. // Compute the character length of a line, taking into account
  283. // collapsed ranges (see markText) that might hide parts, and join
  284. // other lines onto it.
  285. function lineLength(line) {
  286. if (line.height == 0) return 0;
  287. var len = line.text.length, merged, cur = line;
  288. while (merged = collapsedSpanAtStart(cur)) {
  289. var found = merged.find(0, true);
  290. cur = found.from.line;
  291. len += found.from.ch - found.to.ch;
  292. }
  293. cur = line;
  294. while (merged = collapsedSpanAtEnd(cur)) {
  295. var found = merged.find(0, true);
  296. len -= cur.text.length - found.from.ch;
  297. cur = found.to.line;
  298. len += cur.text.length - found.to.ch;
  299. }
  300. return len;
  301. }
  302. // Find the longest line in the document.
  303. function findMaxLine(cm) {
  304. var d = cm.display, doc = cm.doc;
  305. d.maxLine = getLine(doc, doc.first);
  306. d.maxLineLength = lineLength(d.maxLine);
  307. d.maxLineChanged = true;
  308. doc.iter(function(line) {
  309. var len = lineLength(line);
  310. if (len > d.maxLineLength) {
  311. d.maxLineLength = len;
  312. d.maxLine = line;
  313. }
  314. });
  315. }
  316. // Make sure the gutters options contains the element
  317. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  318. function setGuttersForLineNumbers(options) {
  319. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  320. if (found == -1 && options.lineNumbers) {
  321. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  322. } else if (found > -1 && !options.lineNumbers) {
  323. options.gutters = options.gutters.slice(0);
  324. options.gutters.splice(found, 1);
  325. }
  326. }
  327. // SCROLLBARS
  328. // Prepare DOM reads needed to update the scrollbars. Done in one
  329. // shot to minimize update/measure roundtrips.
  330. function measureForScrollbars(cm) {
  331. var d = cm.display, gutterW = d.gutters.offsetWidth;
  332. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  333. return {
  334. clientHeight: d.scroller.clientHeight,
  335. viewHeight: d.wrapper.clientHeight,
  336. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  337. viewWidth: d.wrapper.clientWidth,
  338. barLeft: cm.options.fixedGutter ? gutterW : 0,
  339. docHeight: docH,
  340. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  341. nativeBarWidth: d.nativeBarWidth,
  342. gutterWidth: gutterW
  343. };
  344. }
  345. function NativeScrollbars(place, scroll, cm) {
  346. this.cm = cm;
  347. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  348. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  349. place(vert); place(horiz);
  350. on(vert, "scroll", function() {
  351. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  352. });
  353. on(horiz, "scroll", function() {
  354. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  355. });
  356. this.checkedZeroWidth = false;
  357. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  358. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  359. }
  360. NativeScrollbars.prototype = copyObj({
  361. update: function(measure) {
  362. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  363. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  364. var sWidth = measure.nativeBarWidth;
  365. if (needsV) {
  366. this.vert.style.display = "block";
  367. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  368. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  369. // A bug in IE8 can cause this value to be negative, so guard it.
  370. this.vert.firstChild.style.height =
  371. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  372. } else {
  373. this.vert.style.display = "";
  374. this.vert.firstChild.style.height = "0";
  375. }
  376. if (needsH) {
  377. this.horiz.style.display = "block";
  378. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  379. this.horiz.style.left = measure.barLeft + "px";
  380. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  381. this.horiz.firstChild.style.width =
  382. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  383. } else {
  384. this.horiz.style.display = "";
  385. this.horiz.firstChild.style.width = "0";
  386. }
  387. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  388. if (sWidth == 0) this.zeroWidthHack();
  389. this.checkedZeroWidth = true;
  390. }
  391. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  392. },
  393. setScrollLeft: function(pos) {
  394. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  395. if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
  396. },
  397. setScrollTop: function(pos) {
  398. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  399. if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
  400. },
  401. zeroWidthHack: function() {
  402. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  403. this.horiz.style.height = this.vert.style.width = w;
  404. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  405. this.disableHoriz = new Delayed;
  406. this.disableVert = new Delayed;
  407. },
  408. enableZeroWidthBar: function(bar, delay) {
  409. bar.style.pointerEvents = "auto";
  410. function maybeDisable() {
  411. // To find out whether the scrollbar is still visible, we
  412. // check whether the element under the pixel in the bottom
  413. // left corner of the scrollbar box is the scrollbar box
  414. // itself (when the bar is still visible) or its filler child
  415. // (when the bar is hidden). If it is still visible, we keep
  416. // it enabled, if it's hidden, we disable pointer events.
  417. var box = bar.getBoundingClientRect();
  418. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
  419. if (elt != bar) bar.style.pointerEvents = "none";
  420. else delay.set(1000, maybeDisable);
  421. }
  422. delay.set(1000, maybeDisable);
  423. },
  424. clear: function() {
  425. var parent = this.horiz.parentNode;
  426. parent.removeChild(this.horiz);
  427. parent.removeChild(this.vert);
  428. }
  429. }, NativeScrollbars.prototype);
  430. function NullScrollbars() {}
  431. NullScrollbars.prototype = copyObj({
  432. update: function() { return {bottom: 0, right: 0}; },
  433. setScrollLeft: function() {},
  434. setScrollTop: function() {},
  435. clear: function() {}
  436. }, NullScrollbars.prototype);
  437. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  438. function initScrollbars(cm) {
  439. if (cm.display.scrollbars) {
  440. cm.display.scrollbars.clear();
  441. if (cm.display.scrollbars.addClass)
  442. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  443. }
  444. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  445. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  446. // Prevent clicks in the scrollbars from killing focus
  447. on(node, "mousedown", function() {
  448. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  449. });
  450. node.setAttribute("cm-not-content", "true");
  451. }, function(pos, axis) {
  452. if (axis == "horizontal") setScrollLeft(cm, pos);
  453. else setScrollTop(cm, pos);
  454. }, cm);
  455. if (cm.display.scrollbars.addClass)
  456. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  457. }
  458. function updateScrollbars(cm, measure) {
  459. if (!measure) measure = measureForScrollbars(cm);
  460. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  461. updateScrollbarsInner(cm, measure);
  462. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  463. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  464. updateHeightsInViewport(cm);
  465. updateScrollbarsInner(cm, measureForScrollbars(cm));
  466. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  467. }
  468. }
  469. // Re-synchronize the fake scrollbars with the actual size of the
  470. // content.
  471. function updateScrollbarsInner(cm, measure) {
  472. var d = cm.display;
  473. var sizes = d.scrollbars.update(measure);
  474. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  475. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  476. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  477. if (sizes.right && sizes.bottom) {
  478. d.scrollbarFiller.style.display = "block";
  479. d.scrollbarFiller.style.height = sizes.bottom + "px";
  480. d.scrollbarFiller.style.width = sizes.right + "px";
  481. } else d.scrollbarFiller.style.display = "";
  482. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  483. d.gutterFiller.style.display = "block";
  484. d.gutterFiller.style.height = sizes.bottom + "px";
  485. d.gutterFiller.style.width = measure.gutterWidth + "px";
  486. } else d.gutterFiller.style.display = "";
  487. }
  488. // Compute the lines that are visible in a given viewport (defaults
  489. // the the current scroll position). viewport may contain top,
  490. // height, and ensure (see op.scrollToPos) properties.
  491. function visibleLines(display, doc, viewport) {
  492. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  493. top = Math.floor(top - paddingTop(display));
  494. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  495. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  496. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  497. // forces those lines into the viewport (if possible).
  498. if (viewport && viewport.ensure) {
  499. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  500. if (ensureFrom < from) {
  501. from = ensureFrom;
  502. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  503. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  504. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  505. to = ensureTo;
  506. }
  507. }
  508. return {from: from, to: Math.max(to, from + 1)};
  509. }
  510. // LINE NUMBERS
  511. // Re-align line numbers and gutter marks to compensate for
  512. // horizontal scrolling.
  513. function alignHorizontally(cm) {
  514. var display = cm.display, view = display.view;
  515. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  516. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  517. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  518. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  519. if (cm.options.fixedGutter && view[i].gutter)
  520. view[i].gutter.style.left = left;
  521. var align = view[i].alignable;
  522. if (align) for (var j = 0; j < align.length; j++)
  523. align[j].style.left = left;
  524. }
  525. if (cm.options.fixedGutter)
  526. display.gutters.style.left = (comp + gutterW) + "px";
  527. }
  528. // Used to ensure that the line number gutter is still the right
  529. // size for the current document size. Returns true when an update
  530. // is needed.
  531. function maybeUpdateLineNumberWidth(cm) {
  532. if (!cm.options.lineNumbers) return false;
  533. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  534. if (last.length != display.lineNumChars) {
  535. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  536. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  537. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  538. display.lineGutter.style.width = "";
  539. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  540. display.lineNumWidth = display.lineNumInnerWidth + padding;
  541. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  542. display.lineGutter.style.width = display.lineNumWidth + "px";
  543. updateGutterSpace(cm);
  544. return true;
  545. }
  546. return false;
  547. }
  548. function lineNumberFor(options, i) {
  549. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  550. }
  551. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  552. // but using getBoundingClientRect to get a sub-pixel-accurate
  553. // result.
  554. function compensateForHScroll(display) {
  555. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  556. }
  557. // DISPLAY DRAWING
  558. function DisplayUpdate(cm, viewport, force) {
  559. var display = cm.display;
  560. this.viewport = viewport;
  561. // Store some values that we'll need later (but don't want to force a relayout for)
  562. this.visible = visibleLines(display, cm.doc, viewport);
  563. this.editorIsHidden = !display.wrapper.offsetWidth;
  564. this.wrapperHeight = display.wrapper.clientHeight;
  565. this.wrapperWidth = display.wrapper.clientWidth;
  566. this.oldDisplayWidth = displayWidth(cm);
  567. this.force = force;
  568. this.dims = getDimensions(cm);
  569. this.events = [];
  570. }
  571. DisplayUpdate.prototype.signal = function(emitter, type) {
  572. if (hasHandler(emitter, type))
  573. this.events.push(arguments);
  574. };
  575. DisplayUpdate.prototype.finish = function() {
  576. for (var i = 0; i < this.events.length; i++)
  577. signal.apply(null, this.events[i]);
  578. };
  579. function maybeClipScrollbars(cm) {
  580. var display = cm.display;
  581. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  582. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  583. display.heightForcer.style.height = scrollGap(cm) + "px";
  584. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  585. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  586. display.scrollbarsClipped = true;
  587. }
  588. }
  589. // Does the actual updating of the line display. Bails out
  590. // (returning false) when there is nothing to be done and forced is
  591. // false.
  592. function updateDisplayIfNeeded(cm, update) {
  593. var display = cm.display, doc = cm.doc;
  594. if (update.editorIsHidden) {
  595. resetView(cm);
  596. return false;
  597. }
  598. // Bail out if the visible area is already rendered and nothing changed.
  599. if (!update.force &&
  600. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  601. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  602. display.renderedView == display.view && countDirtyView(cm) == 0)
  603. return false;
  604. if (maybeUpdateLineNumberWidth(cm)) {
  605. resetView(cm);
  606. update.dims = getDimensions(cm);
  607. }
  608. // Compute a suitable new viewport (from & to)
  609. var end = doc.first + doc.size;
  610. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  611. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  612. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  613. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  614. if (sawCollapsedSpans) {
  615. from = visualLineNo(cm.doc, from);
  616. to = visualLineEndNo(cm.doc, to);
  617. }
  618. var different = from != display.viewFrom || to != display.viewTo ||
  619. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  620. adjustView(cm, from, to);
  621. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  622. // Position the mover div to align with the current scroll position
  623. cm.display.mover.style.top = display.viewOffset + "px";
  624. var toUpdate = countDirtyView(cm);
  625. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  626. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  627. return false;
  628. // For big changes, we hide the enclosing element during the
  629. // update, since that speeds up the operations on most browsers.
  630. var focused = activeElt();
  631. if (toUpdate > 4) display.lineDiv.style.display = "none";
  632. patchDisplay(cm, display.updateLineNumbers, update.dims);
  633. if (toUpdate > 4) display.lineDiv.style.display = "";
  634. display.renderedView = display.view;
  635. // There might have been a widget with a focused element that got
  636. // hidden or updated, if so re-focus it.
  637. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  638. // Prevent selection and cursors from interfering with the scroll
  639. // width and height.
  640. removeChildren(display.cursorDiv);
  641. removeChildren(display.selectionDiv);
  642. display.gutters.style.height = display.sizer.style.minHeight = 0;
  643. if (different) {
  644. display.lastWrapHeight = update.wrapperHeight;
  645. display.lastWrapWidth = update.wrapperWidth;
  646. startWorker(cm, 400);
  647. }
  648. display.updateLineNumbers = null;
  649. return true;
  650. }
  651. function postUpdateDisplay(cm, update) {
  652. var viewport = update.viewport;
  653. for (var first = true;; first = false) {
  654. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  655. // Clip forced viewport to actual scrollable area.
  656. if (viewport && viewport.top != null)
  657. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  658. // Updated line heights might result in the drawn area not
  659. // actually covering the viewport. Keep looping until it does.
  660. update.visible = visibleLines(cm.display, cm.doc, viewport);
  661. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  662. break;
  663. }
  664. if (!updateDisplayIfNeeded(cm, update)) break;
  665. updateHeightsInViewport(cm);
  666. var barMeasure = measureForScrollbars(cm);
  667. updateSelection(cm);
  668. updateScrollbars(cm, barMeasure);
  669. setDocumentHeight(cm, barMeasure);
  670. }
  671. update.signal(cm, "update", cm);
  672. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  673. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  674. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  675. }
  676. }
  677. function updateDisplaySimple(cm, viewport) {
  678. var update = new DisplayUpdate(cm, viewport);
  679. if (updateDisplayIfNeeded(cm, update)) {
  680. updateHeightsInViewport(cm);
  681. postUpdateDisplay(cm, update);
  682. var barMeasure = measureForScrollbars(cm);
  683. updateSelection(cm);
  684. updateScrollbars(cm, barMeasure);
  685. setDocumentHeight(cm, barMeasure);
  686. update.finish();
  687. }
  688. }
  689. function setDocumentHeight(cm, measure) {
  690. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  691. cm.display.heightForcer.style.top = measure.docHeight + "px";
  692. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  693. }
  694. // Read the actual heights of the rendered lines, and update their
  695. // stored heights to match.
  696. function updateHeightsInViewport(cm) {
  697. var display = cm.display;
  698. var prevBottom = display.lineDiv.offsetTop;
  699. for (var i = 0; i < display.view.length; i++) {
  700. var cur = display.view[i], height;
  701. if (cur.hidden) continue;
  702. if (ie && ie_version < 8) {
  703. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  704. height = bot - prevBottom;
  705. prevBottom = bot;
  706. } else {
  707. var box = cur.node.getBoundingClientRect();
  708. height = box.bottom - box.top;
  709. }
  710. var diff = cur.line.height - height;
  711. if (height < 2) height = textHeight(display);
  712. if (diff > .001 || diff < -.001) {
  713. updateLineHeight(cur.line, height);
  714. updateWidgetHeight(cur.line);
  715. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  716. updateWidgetHeight(cur.rest[j]);
  717. }
  718. }
  719. }
  720. // Read and store the height of line widgets associated with the
  721. // given line.
  722. function updateWidgetHeight(line) {
  723. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  724. line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
  725. }
  726. // Do a bulk-read of the DOM positions and sizes needed to draw the
  727. // view, so that we don't interleave reading and writing to the DOM.
  728. function getDimensions(cm) {
  729. var d = cm.display, left = {}, width = {};
  730. var gutterLeft = d.gutters.clientLeft;
  731. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  732. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  733. width[cm.options.gutters[i]] = n.clientWidth;
  734. }
  735. return {fixedPos: compensateForHScroll(d),
  736. gutterTotalWidth: d.gutters.offsetWidth,
  737. gutterLeft: left,
  738. gutterWidth: width,
  739. wrapperWidth: d.wrapper.clientWidth};
  740. }
  741. // Sync the actual display DOM structure with display.view, removing
  742. // nodes for lines that are no longer in view, and creating the ones
  743. // that are not there yet, and updating the ones that are out of
  744. // date.
  745. function patchDisplay(cm, updateNumbersFrom, dims) {
  746. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  747. var container = display.lineDiv, cur = container.firstChild;
  748. function rm(node) {
  749. var next = node.nextSibling;
  750. // Works around a throw-scroll bug in OS X Webkit
  751. if (webkit && mac && cm.display.currentWheelTarget == node)
  752. node.style.display = "none";
  753. else
  754. node.parentNode.removeChild(node);
  755. return next;
  756. }
  757. var view = display.view, lineN = display.viewFrom;
  758. // Loop over the elements in the view, syncing cur (the DOM nodes
  759. // in display.lineDiv) with the view as we go.
  760. for (var i = 0; i < view.length; i++) {
  761. var lineView = view[i];
  762. if (lineView.hidden) {
  763. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  764. var node = buildLineElement(cm, lineView, lineN, dims);
  765. container.insertBefore(node, cur);
  766. } else { // Already drawn
  767. while (cur != lineView.node) cur = rm(cur);
  768. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  769. updateNumbersFrom <= lineN && lineView.lineNumber;
  770. if (lineView.changes) {
  771. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  772. updateLineForChanges(cm, lineView, lineN, dims);
  773. }
  774. if (updateNumber) {
  775. removeChildren(lineView.lineNumber);
  776. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  777. }
  778. cur = lineView.node.nextSibling;
  779. }
  780. lineN += lineView.size;
  781. }
  782. while (cur) cur = rm(cur);
  783. }
  784. // When an aspect of a line changes, a string is added to
  785. // lineView.changes. This updates the relevant part of the line's
  786. // DOM structure.
  787. function updateLineForChanges(cm, lineView, lineN, dims) {
  788. for (var j = 0; j < lineView.changes.length; j++) {
  789. var type = lineView.changes[j];
  790. if (type == "text") updateLineText(cm, lineView);
  791. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  792. else if (type == "class") updateLineClasses(lineView);
  793. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  794. }
  795. lineView.changes = null;
  796. }
  797. // Lines with gutter elements, widgets or a background class need to
  798. // be wrapped, and have the extra elements added to the wrapper div
  799. function ensureLineWrapped(lineView) {
  800. if (lineView.node == lineView.text) {
  801. lineView.node = elt("div", null, null, "position: relative");
  802. if (lineView.text.parentNode)
  803. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  804. lineView.node.appendChild(lineView.text);
  805. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  806. }
  807. return lineView.node;
  808. }
  809. function updateLineBackground(lineView) {
  810. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  811. if (cls) cls += " CodeMirror-linebackground";
  812. if (lineView.background) {
  813. if (cls) lineView.background.className = cls;
  814. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  815. } else if (cls) {
  816. var wrap = ensureLineWrapped(lineView);
  817. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  818. }
  819. }
  820. // Wrapper around buildLineContent which will reuse the structure
  821. // in display.externalMeasured when possible.
  822. function getLineContent(cm, lineView) {
  823. var ext = cm.display.externalMeasured;
  824. if (ext && ext.line == lineView.line) {
  825. cm.display.externalMeasured = null;
  826. lineView.measure = ext.measure;
  827. return ext.built;
  828. }
  829. return buildLineContent(cm, lineView);
  830. }
  831. // Redraw the line's text. Interacts with the background and text
  832. // classes because the mode may output tokens that influence these
  833. // classes.
  834. function updateLineText(cm, lineView) {
  835. var cls = lineView.text.className;
  836. var built = getLineContent(cm, lineView);
  837. if (lineView.text == lineView.node) lineView.node = built.pre;
  838. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  839. lineView.text = built.pre;
  840. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  841. lineView.bgClass = built.bgClass;
  842. lineView.textClass = built.textClass;
  843. updateLineClasses(lineView);
  844. } else if (cls) {
  845. lineView.text.className = cls;
  846. }
  847. }
  848. function updateLineClasses(lineView) {
  849. updateLineBackground(lineView);
  850. if (lineView.line.wrapClass)
  851. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  852. else if (lineView.node != lineView.text)
  853. lineView.node.className = "";
  854. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  855. lineView.text.className = textClass || "";
  856. }
  857. function updateLineGutter(cm, lineView, lineN, dims) {
  858. if (lineView.gutter) {
  859. lineView.node.removeChild(lineView.gutter);
  860. lineView.gutter = null;
  861. }
  862. if (lineView.gutterBackground) {
  863. lineView.node.removeChild(lineView.gutterBackground);
  864. lineView.gutterBackground = null;
  865. }
  866. if (lineView.line.gutterClass) {
  867. var wrap = ensureLineWrapped(lineView);
  868. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  869. "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  870. "px; width: " + dims.gutterTotalWidth + "px");
  871. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  872. }
  873. var markers = lineView.line.gutterMarkers;
  874. if (cm.options.lineNumbers || markers) {
  875. var wrap = ensureLineWrapped(lineView);
  876. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  877. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
  878. cm.display.input.setUneditable(gutterWrap);
  879. wrap.insertBefore(gutterWrap, lineView.text);
  880. if (lineView.line.gutterClass)
  881. gutterWrap.className += " " + lineView.line.gutterClass;
  882. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  883. lineView.lineNumber = gutterWrap.appendChild(
  884. elt("div", lineNumberFor(cm.options, lineN),
  885. "CodeMirror-linenumber CodeMirror-gutter-elt",
  886. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  887. + cm.display.lineNumInnerWidth + "px"));
  888. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  889. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  890. if (found)
  891. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  892. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  893. }
  894. }
  895. }
  896. function updateLineWidgets(cm, lineView, dims) {
  897. if (lineView.alignable) lineView.alignable = null;
  898. for (var node = lineView.node.firstChild, next; node; node = next) {
  899. var next = node.nextSibling;
  900. if (node.className == "CodeMirror-linewidget")
  901. lineView.node.removeChild(node);
  902. }
  903. insertLineWidgets(cm, lineView, dims);
  904. }
  905. // Build a line's DOM representation from scratch
  906. function buildLineElement(cm, lineView, lineN, dims) {
  907. var built = getLineContent(cm, lineView);
  908. lineView.text = lineView.node = built.pre;
  909. if (built.bgClass) lineView.bgClass = built.bgClass;
  910. if (built.textClass) lineView.textClass = built.textClass;
  911. updateLineClasses(lineView);
  912. updateLineGutter(cm, lineView, lineN, dims);
  913. insertLineWidgets(cm, lineView, dims);
  914. return lineView.node;
  915. }
  916. // A lineView may contain multiple logical lines (when merged by
  917. // collapsed spans). The widgets for all of them need to be drawn.
  918. function insertLineWidgets(cm, lineView, dims) {
  919. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  920. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  921. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  922. }
  923. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  924. if (!line.widgets) return;
  925. var wrap = ensureLineWrapped(lineView);
  926. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  927. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  928. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  929. positionLineWidget(widget, node, lineView, dims);
  930. cm.display.input.setUneditable(node);
  931. if (allowAbove && widget.above)
  932. wrap.insertBefore(node, lineView.gutter || lineView.text);
  933. else
  934. wrap.appendChild(node);
  935. signalLater(widget, "redraw");
  936. }
  937. }
  938. function positionLineWidget(widget, node, lineView, dims) {
  939. if (widget.noHScroll) {
  940. (lineView.alignable || (lineView.alignable = [])).push(node);
  941. var width = dims.wrapperWidth;
  942. node.style.left = dims.fixedPos + "px";
  943. if (!widget.coverGutter) {
  944. width -= dims.gutterTotalWidth;
  945. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  946. }
  947. node.style.width = width + "px";
  948. }
  949. if (widget.coverGutter) {
  950. node.style.zIndex = 5;
  951. node.style.position = "relative";
  952. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  953. }
  954. }
  955. // POSITION OBJECT
  956. // A Pos instance represents a position within the text.
  957. var Pos = CodeMirror.Pos = function(line, ch) {
  958. if (!(this instanceof Pos)) return new Pos(line, ch);
  959. this.line = line; this.ch = ch;
  960. };
  961. // Compare two positions, return 0 if they are the same, a negative
  962. // number when a is less, and a positive number otherwise.
  963. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  964. function copyPos(x) {return Pos(x.line, x.ch);}
  965. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  966. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  967. // INPUT HANDLING
  968. function ensureFocus(cm) {
  969. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  970. }
  971. // This will be set to a {lineWise: bool, text: [string]} object, so
  972. // that, when pasting, we know what kind of selections the copied
  973. // text was made out of.
  974. var lastCopied = null;
  975. function applyTextInput(cm, inserted, deleted, sel, origin) {
  976. var doc = cm.doc;
  977. cm.display.shift = false;
  978. if (!sel) sel = doc.sel;
  979. var paste = cm.state.pasteIncoming || origin == "paste";
  980. var textLines = doc.splitLines(inserted), multiPaste = null
  981. // When pasing N lines into N selections, insert one line per selection
  982. if (paste && sel.ranges.length > 1) {
  983. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  984. if (sel.ranges.length % lastCopied.text.length == 0) {
  985. multiPaste = [];
  986. for (var i = 0; i < lastCopied.text.length; i++)
  987. multiPaste.push(doc.splitLines(lastCopied.text[i]));
  988. }
  989. } else if (textLines.length == sel.ranges.length) {
  990. multiPaste = map(textLines, function(l) { return [l]; });
  991. }
  992. }
  993. // Normal behavior is to insert the new text into every selection
  994. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  995. var range = sel.ranges[i];
  996. var from = range.from(), to = range.to();
  997. if (range.empty()) {
  998. if (deleted && deleted > 0) // Handle deletion
  999. from = Pos(from.line, from.ch - deleted);
  1000. else if (cm.state.overwrite && !paste) // Handle overwrite
  1001. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  1002. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  1003. from = to = Pos(from.line, 0)
  1004. }
  1005. var updateInput = cm.curOp.updateInput;
  1006. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  1007. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  1008. makeChange(cm.doc, changeEvent);
  1009. signalLater(cm, "inputRead", cm, changeEvent);
  1010. }
  1011. if (inserted && !paste)
  1012. triggerElectric(cm, inserted);
  1013. ensureCursorVisible(cm);
  1014. cm.curOp.updateInput = updateInput;
  1015. cm.curOp.typing = true;
  1016. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  1017. }
  1018. function handlePaste(e, cm) {
  1019. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1020. if (pasted) {
  1021. e.preventDefault();
  1022. if (!cm.isReadOnly() && !cm.options.disableInput)
  1023. runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
  1024. return true;
  1025. }
  1026. }
  1027. function triggerElectric(cm, inserted) {
  1028. // When an 'electric' character is inserted, immediately trigger a reindent
  1029. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  1030. var sel = cm.doc.sel;
  1031. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  1032. var range = sel.ranges[i];
  1033. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  1034. var mode = cm.getModeAt(range.head);
  1035. var indented = false;
  1036. if (mode.electricChars) {
  1037. for (var j = 0; j < mode.electricChars.length; j++)
  1038. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  1039. indented = indentLine(cm, range.head.line, "smart");
  1040. break;
  1041. }
  1042. } else if (mode.electricInput) {
  1043. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  1044. indented = indentLine(cm, range.head.line, "smart");
  1045. }
  1046. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  1047. }
  1048. }
  1049. function copyableRanges(cm) {
  1050. var text = [], ranges = [];
  1051. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1052. var line = cm.doc.sel.ranges[i].head.line;
  1053. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  1054. ranges.push(lineRange);
  1055. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1056. }
  1057. return {text: text, ranges: ranges};
  1058. }
  1059. function disableBrowserMagic(field) {
  1060. field.setAttribute("autocorrect", "off");
  1061. field.setAttribute("autocapitalize", "off");
  1062. field.setAttribute("spellcheck", "false");
  1063. }
  1064. // TEXTAREA INPUT STYLE
  1065. function TextareaInput(cm) {
  1066. this.cm = cm;
  1067. // See input.poll and input.reset
  1068. this.prevInput = "";
  1069. // Flag that indicates whether we expect input to appear real soon
  1070. // now (after some event like 'keypress' or 'input') and are
  1071. // polling intensively.
  1072. this.pollingFast = false;
  1073. // Self-resetting timeout for the poller
  1074. this.polling = new Delayed();
  1075. // Tracks when input.reset has punted to just putting a short
  1076. // string into the textarea instead of the full selection.
  1077. this.inaccurateSelection = false;
  1078. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1079. this.hasSelection = false;
  1080. this.composing = null;
  1081. };
  1082. function hiddenTextarea() {
  1083. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  1084. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1085. // The textarea is kept positioned near the cursor to prevent the
  1086. // fact that it'll be scrolled into view on input from scrolling
  1087. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1088. // very slow. So make the area wide instead.
  1089. if (webkit) te.style.width = "1000px";
  1090. else te.setAttribute("wrap", "off");
  1091. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1092. if (ios) te.style.border = "1px solid black";
  1093. disableBrowserMagic(te);
  1094. return div;
  1095. }
  1096. TextareaInput.prototype = copyObj({
  1097. init: function(display) {
  1098. var input = this, cm = this.cm;
  1099. // Wraps and hides input textarea
  1100. var div = this.wrapper = hiddenTextarea();
  1101. // The semihidden textarea that is focused when the editor is
  1102. // focused, and receives input.
  1103. var te = this.textarea = div.firstChild;
  1104. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1105. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1106. if (ios) te.style.width = "0px";
  1107. on(te, "input", function() {
  1108. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1109. input.poll();
  1110. });
  1111. on(te, "paste", function(e) {
  1112. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  1113. cm.state.pasteIncoming = true;
  1114. input.fastPoll();
  1115. });
  1116. function prepareCopyCut(e) {
  1117. if (signalDOMEvent(cm, e)) return
  1118. if (cm.somethingSelected()) {
  1119. lastCopied = {lineWise: false, text: cm.getSelections()};
  1120. if (input.inaccurateSelection) {
  1121. input.prevInput = "";
  1122. input.inaccurateSelection = false;
  1123. te.value = lastCopied.text.join("\n");
  1124. selectInput(te);
  1125. }
  1126. } else if (!cm.options.lineWiseCopyCut) {
  1127. return;
  1128. } else {
  1129. var ranges = copyableRanges(cm);
  1130. lastCopied = {lineWise: true, text: ranges.text};
  1131. if (e.type == "cut") {
  1132. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1133. } else {
  1134. input.prevInput = "";
  1135. te.value = ranges.text.join("\n");
  1136. selectInput(te);
  1137. }
  1138. }
  1139. if (e.type == "cut") cm.state.cutIncoming = true;
  1140. }
  1141. on(te, "cut", prepareCopyCut);
  1142. on(te, "copy", prepareCopyCut);
  1143. on(display.scroller, "paste", function(e) {
  1144. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
  1145. cm.state.pasteIncoming = true;
  1146. input.focus();
  1147. });
  1148. // Prevent normal selection in the editor (we handle our own)
  1149. on(display.lineSpace, "selectstart", function(e) {
  1150. if (!eventInWidget(display, e)) e_preventDefault(e);
  1151. });
  1152. on(te, "compositionstart", function() {
  1153. var start = cm.getCursor("from");
  1154. if (input.composing) input.composing.range.clear()
  1155. input.composing = {
  1156. start: start,
  1157. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  1158. };
  1159. });
  1160. on(te, "compositionend", function() {
  1161. if (input.composing) {
  1162. input.poll();
  1163. input.composing.range.clear();
  1164. input.composing = null;
  1165. }
  1166. });
  1167. },
  1168. prepareSelection: function() {
  1169. // Redraw the selection and/or cursor
  1170. var cm = this.cm, display = cm.display, doc = cm.doc;
  1171. var result = prepareSelection(cm);
  1172. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1173. if (cm.options.moveInputWithCursor) {
  1174. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1175. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1176. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1177. headPos.top + lineOff.top - wrapOff.top));
  1178. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1179. headPos.left + lineOff.left - wrapOff.left));
  1180. }
  1181. return result;
  1182. },
  1183. showSelection: function(drawn) {
  1184. var cm = this.cm, display = cm.display;
  1185. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1186. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1187. if (drawn.teTop != null) {
  1188. this.wrapper.style.top = drawn.teTop + "px";
  1189. this.wrapper.style.left = drawn.teLeft + "px";
  1190. }
  1191. },
  1192. // Reset the input to correspond to the selection (or to be empty,
  1193. // when not typing and nothing is selected)
  1194. reset: function(typing) {
  1195. if (this.contextMenuPending) return;
  1196. var minimal, selected, cm = this.cm, doc = cm.doc;
  1197. if (cm.somethingSelected()) {
  1198. this.prevInput = "";
  1199. var range = doc.sel.primary();
  1200. minimal = hasCopyEvent &&
  1201. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1202. var content = minimal ? "-" : selected || cm.getSelection();
  1203. this.textarea.value = content;
  1204. if (cm.state.focused) selectInput(this.textarea);
  1205. if (ie && ie_version >= 9) this.hasSelection = content;
  1206. } else if (!typing) {
  1207. this.prevInput = this.textarea.value = "";
  1208. if (ie && ie_version >= 9) this.hasSelection = null;
  1209. }
  1210. this.inaccurateSelection = minimal;
  1211. },
  1212. getField: function() { return this.textarea; },
  1213. supportsTouch: function() { return false; },
  1214. focus: function() {
  1215. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1216. try { this.textarea.focus(); }
  1217. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  1218. }
  1219. },
  1220. blur: function() { this.textarea.blur(); },
  1221. resetPosition: function() {
  1222. this.wrapper.style.top = this.wrapper.style.left = 0;
  1223. },
  1224. receivedFocus: function() { this.slowPoll(); },
  1225. // Poll for input changes, using the normal rate of polling. This
  1226. // runs as long as the editor is focused.
  1227. slowPoll: function() {
  1228. var input = this;
  1229. if (input.pollingFast) return;
  1230. input.polling.set(this.cm.options.pollInterval, function() {
  1231. input.poll();
  1232. if (input.cm.state.focused) input.slowPoll();
  1233. });
  1234. },
  1235. // When an event has just come in that is likely to add or change
  1236. // something in the input textarea, we poll faster, to ensure that
  1237. // the change appears on the screen quickly.
  1238. fastPoll: function() {
  1239. var missed = false, input = this;
  1240. input.pollingFast = true;
  1241. function p() {
  1242. var changed = input.poll();
  1243. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  1244. else {input.pollingFast = false; input.slowPoll();}
  1245. }
  1246. input.polling.set(20, p);
  1247. },
  1248. // Read input from the textarea, and update the document to match.
  1249. // When something is selected, it is present in the textarea, and
  1250. // selected (unless it is huge, in which case a placeholder is
  1251. // used). When nothing is selected, the cursor sits after previously
  1252. // seen text (can be empty), which is stored in prevInput (we must
  1253. // not reset the textarea when typing, because that breaks IME).
  1254. poll: function() {
  1255. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1256. // Since this is called a *lot*, try to bail out as cheaply as
  1257. // possible when it is clear that nothing happened. hasSelection
  1258. // will be the case when there is a lot of text in the textarea,
  1259. // in which case reading its value would be expensive.
  1260. if (this.contextMenuPending || !cm.state.focused ||
  1261. (hasSelection(input) && !prevInput && !this.composing) ||
  1262. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  1263. return false;
  1264. var text = input.value;
  1265. // If nothing changed, bail.
  1266. if (text == prevInput && !cm.somethingSelected()) return false;
  1267. // Work around nonsensical selection resetting in IE9/10, and
  1268. // inexplicable appearance of private area unicode characters on
  1269. // some key combos in Mac (#2689).
  1270. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1271. mac && /[\uf700-\uf7ff]/.test(text)) {
  1272. cm.display.input.reset();
  1273. return false;
  1274. }
  1275. if (cm.doc.sel == cm.display.selForContextMenu) {
  1276. var first = text.charCodeAt(0);
  1277. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  1278. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  1279. }
  1280. // Find the part of the input that is actually new
  1281. var same = 0, l = Math.min(prevInput.length, text.length);
  1282. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1283. var self = this;
  1284. runInOp(cm, function() {
  1285. applyTextInput(cm, text.slice(same), prevInput.length - same,
  1286. null, self.composing ? "*compose" : null);
  1287. // Don't leave long text in the textarea, since it makes further polling slow
  1288. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1289. else self.prevInput = text;
  1290. if (self.composing) {
  1291. self.composing.range.clear();
  1292. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  1293. {className: "CodeMirror-composing"});
  1294. }
  1295. });
  1296. return true;
  1297. },
  1298. ensurePolled: function() {
  1299. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1300. },
  1301. onKeyPress: function() {
  1302. if (ie && ie_version >= 9) this.hasSelection = null;
  1303. this.fastPoll();
  1304. },
  1305. onContextMenu: function(e) {
  1306. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1307. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1308. if (!pos || presto) return; // Opera is difficult.
  1309. // Reset the current text selection only if the click is done outside of the selection
  1310. // and 'resetSelectionOnContextMenu' option is true.
  1311. var reset = cm.options.resetSelectionOnContextMenu;
  1312. if (reset && cm.doc.sel.contains(pos) == -1)
  1313. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1314. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  1315. input.wrapper.style.cssText = "position: absolute"
  1316. var wrapperBox = input.wrapper.getBoundingClientRect()
  1317. te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
  1318. "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
  1319. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1320. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1321. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1322. display.input.focus();
  1323. if (webkit) window.scrollTo(null, oldScrollY);
  1324. display.input.reset();
  1325. // Adds "Select all" to context menu in FF
  1326. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1327. input.contextMenuPending = true;
  1328. display.selForContextMenu = cm.doc.sel;
  1329. clearTimeout(display.detectingSelectAll);
  1330. // Select-all will be greyed out if there's nothing to select, so
  1331. // this adds a zero-width space so that we can later check whether
  1332. // it got selected.
  1333. function prepareSelectAllHack() {
  1334. if (te.selectionStart != null) {
  1335. var selected = cm.somethingSelected();
  1336. var extval = "\u200b" + (selected ? te.value : "");
  1337. te.value = "\u21da"; // Used to catch context-menu undo
  1338. te.value = extval;
  1339. input.prevInput = selected ? "" : "\u200b";
  1340. te.selectionStart = 1; te.selectionEnd = extval.length;
  1341. // Re-set this, in case some other handler touched the
  1342. // selection in the meantime.
  1343. display.selForContextMenu = cm.doc.sel;
  1344. }
  1345. }
  1346. function rehide() {
  1347. input.contextMenuPending = false;
  1348. input.wrapper.style.cssText = oldWrapperCSS
  1349. te.style.cssText = oldCSS;
  1350. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1351. // Try to detect the user choosing select-all
  1352. if (te.selectionStart != null) {
  1353. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1354. var i = 0, poll = function() {
  1355. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  1356. te.selectionEnd > 0 && input.prevInput == "\u200b")
  1357. operation(cm, commands.selectAll)(cm);
  1358. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1359. else display.input.reset();
  1360. };
  1361. display.detectingSelectAll = setTimeout(poll, 200);
  1362. }
  1363. }
  1364. if (ie && ie_version >= 9) prepareSelectAllHack();
  1365. if (captureRightClick) {
  1366. e_stop(e);
  1367. var mouseup = function() {
  1368. off(window, "mouseup", mouseup);
  1369. setTimeout(rehide, 20);
  1370. };
  1371. on(window, "mouseup", mouseup);
  1372. } else {
  1373. setTimeout(rehide, 50);
  1374. }
  1375. },
  1376. readOnlyChanged: function(val) {
  1377. if (!val) this.reset();
  1378. },
  1379. setUneditable: nothing,
  1380. needsContentAttribute: false
  1381. }, TextareaInput.prototype);
  1382. // CONTENTEDITABLE INPUT STYLE
  1383. function ContentEditableInput(cm) {
  1384. this.cm = cm;
  1385. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1386. this.polling = new Delayed();
  1387. this.gracePeriod = false;
  1388. }
  1389. ContentEditableInput.prototype = copyObj({
  1390. init: function(display) {
  1391. var input = this, cm = input.cm;
  1392. var div = input.div = display.lineDiv;
  1393. disableBrowserMagic(div);
  1394. on(div, "paste", function(e) {
  1395. if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
  1396. })
  1397. on(div, "compositionstart", function(e) {
  1398. var data = e.data;
  1399. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  1400. if (!data) return;
  1401. var prim = cm.doc.sel.primary();
  1402. var line = cm.getLine(prim.head.line);
  1403. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1404. if (found > -1 && found <= prim.head.ch)
  1405. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1406. Pos(prim.head.line, found + data.length));
  1407. });
  1408. on(div, "compositionupdate", function(e) {
  1409. input.composing.data = e.data;
  1410. });
  1411. on(div, "compositionend", function(e) {
  1412. var ours = input.composing;
  1413. if (!ours) return;
  1414. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1415. ours.data = e.data;
  1416. // Need a small delay to prevent other code (input event,
  1417. // selection polling) from doing damage when fired right after
  1418. // compositionend.
  1419. setTimeout(function() {
  1420. if (!ours.handled)
  1421. input.applyComposition(ours);
  1422. if (input.composing == ours)
  1423. input.composing = null;
  1424. }, 50);
  1425. });
  1426. on(div, "touchstart", function() {
  1427. input.forceCompositionEnd();
  1428. });
  1429. on(div, "input", function() {
  1430. if (input.composing) return;
  1431. if (cm.isReadOnly() || !input.pollContent())
  1432. runInOp(input.cm, function() {regChange(cm);});
  1433. });
  1434. function onCopyCut(e) {
  1435. if (signalDOMEvent(cm, e)) return
  1436. if (cm.somethingSelected()) {
  1437. lastCopied = {lineWise: false, text: cm.getSelections()};
  1438. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1439. } else if (!cm.options.lineWiseCopyCut) {
  1440. return;
  1441. } else {
  1442. var ranges = copyableRanges(cm);
  1443. lastCopied = {lineWise: true, text: ranges.text};
  1444. if (e.type == "cut") {
  1445. cm.operation(function() {
  1446. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1447. cm.replaceSelection("", null, "cut");
  1448. });
  1449. }
  1450. }
  1451. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1452. if (e.clipboardData && !ios) {
  1453. e.preventDefault();
  1454. e.clipboardData.clearData();
  1455. e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
  1456. } else {
  1457. // Old-fashioned briefly-focus-a-textarea hack
  1458. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1459. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1460. te.value = lastCopied.text.join("\n");
  1461. var hadFocus = document.activeElement;
  1462. selectInput(te);
  1463. setTimeout(function() {
  1464. cm.display.lineSpace.removeChild(kludge);
  1465. hadFocus.focus();
  1466. }, 50);
  1467. }
  1468. }
  1469. on(div, "copy", onCopyCut);
  1470. on(div, "cut", onCopyCut);
  1471. },
  1472. prepareSelection: function() {
  1473. var result = prepareSelection(this.cm, false);
  1474. result.focus = this.cm.state.focused;
  1475. return result;
  1476. },
  1477. showSelection: function(info, takeFocus) {
  1478. if (!info || !this.cm.display.view.length) return;
  1479. if (info.focus || takeFocus) this.showPrimarySelection();
  1480. this.showMultipleSelections(info);
  1481. },
  1482. showPrimarySelection: function() {
  1483. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1484. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1485. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1486. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1487. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1488. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1489. return;
  1490. var start = posToDOM(this.cm, prim.from());
  1491. var end = posToDOM(this.cm, prim.to());
  1492. if (!start && !end) return;
  1493. var view = this.cm.display.view;
  1494. var old = sel.rangeCount && sel.getRangeAt(0);
  1495. if (!start) {
  1496. start = {node: view[0].measure.map[2], offset: 0};
  1497. } else if (!end) { // FIXME dangerously hacky
  1498. var measure = view[view.length - 1].measure;
  1499. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1500. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  1501. }
  1502. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1503. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1504. if (rng) {
  1505. if (!gecko && this.cm.state.focused) {
  1506. sel.collapse(start.node, start.offset);
  1507. if (!rng.collapsed) sel.addRange(rng);
  1508. } else {
  1509. sel.removeAllRanges();
  1510. sel.addRange(rng);
  1511. }
  1512. if (old && sel.anchorNode == null) sel.addRange(old);
  1513. else if (gecko) this.startGracePeriod();
  1514. }
  1515. this.rememberSelection();
  1516. },
  1517. startGracePeriod: function() {
  1518. var input = this;
  1519. clearTimeout(this.gracePeriod);
  1520. this.gracePeriod = setTimeout(function() {
  1521. input.gracePeriod = false;
  1522. if (input.selectionChanged())
  1523. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  1524. }, 20);
  1525. },
  1526. showMultipleSelections: function(info) {
  1527. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1528. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1529. },
  1530. rememberSelection: function() {
  1531. var sel = window.getSelection();
  1532. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1533. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1534. },
  1535. selectionInEditor: function() {
  1536. var sel = window.getSelection();
  1537. if (!sel.rangeCount) return false;
  1538. var node = sel.getRangeAt(0).commonAncestorContainer;
  1539. return contains(this.div, node);
  1540. },
  1541. focus: function() {
  1542. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1543. },
  1544. blur: function() { this.div.blur(); },
  1545. getField: function() { return this.div; },
  1546. supportsTouch: function() { return true; },
  1547. receivedFocus: function() {
  1548. var input = this;
  1549. if (this.selectionInEditor())
  1550. this.pollSelection();
  1551. else
  1552. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  1553. function poll() {
  1554. if (input.cm.state.focused) {
  1555. input.pollSelection();
  1556. input.polling.set(input.cm.options.pollInterval, poll);
  1557. }
  1558. }
  1559. this.polling.set(this.cm.options.pollInterval, poll);
  1560. },
  1561. selectionChanged: function() {
  1562. var sel = window.getSelection();
  1563. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1564. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  1565. },
  1566. pollSelection: function() {
  1567. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  1568. var sel = window.getSelection(), cm = this.cm;
  1569. this.rememberSelection();
  1570. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1571. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1572. if (anchor && head) runInOp(cm, function() {
  1573. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1574. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1575. });
  1576. }
  1577. },
  1578. pollContent: function() {
  1579. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1580. var from = sel.from(), to = sel.to();
  1581. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1582. var fromIndex;
  1583. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1584. var fromLine = lineNo(display.view[0].line);
  1585. var fromNode = display.view[0].node;
  1586. } else {
  1587. var fromLine = lineNo(display.view[fromIndex].line);
  1588. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1589. }
  1590. var toIndex = findViewIndex(cm, to.line);
  1591. if (toIndex == display.view.length - 1) {
  1592. var toLine = display.viewTo - 1;
  1593. var toNode = display.lineDiv.lastChild;
  1594. } else {
  1595. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1596. var toNode = display.view[toIndex + 1].node.previousSibling;
  1597. }
  1598. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1599. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1600. while (newText.length > 1 && oldText.length > 1) {
  1601. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1602. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1603. else break;
  1604. }
  1605. var cutFront = 0, cutEnd = 0;
  1606. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1607. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1608. ++cutFront;
  1609. var newBot = lst(newText), oldBot = lst(oldText);
  1610. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1611. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1612. while (cutEnd < maxCutEnd &&
  1613. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1614. ++cutEnd;
  1615. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1616. newText[0] = newText[0].slice(cutFront);
  1617. var chFrom = Pos(fromLine, cutFront);
  1618. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1619. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1620. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1621. return true;
  1622. }
  1623. },
  1624. ensurePolled: function() {
  1625. this.forceCompositionEnd();
  1626. },
  1627. reset: function() {
  1628. this.forceCompositionEnd();
  1629. },
  1630. forceCompositionEnd: function() {
  1631. if (!this.composing || this.composing.handled) return;
  1632. this.applyComposition(this.composing);
  1633. this.composing.handled = true;
  1634. this.div.blur();
  1635. this.div.focus();
  1636. },
  1637. applyComposition: function(composing) {
  1638. if (this.cm.isReadOnly())
  1639. operation(this.cm, regChange)(this.cm)
  1640. else if (composing.data && composing.data != composing.startData)
  1641. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1642. },
  1643. setUneditable: function(node) {
  1644. node.contentEditable = "false"
  1645. },
  1646. onKeyPress: function(e) {
  1647. e.preventDefault();
  1648. if (!this.cm.isReadOnly())
  1649. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1650. },
  1651. readOnlyChanged: function(val) {
  1652. this.div.contentEditable = String(val != "nocursor")
  1653. },
  1654. onContextMenu: nothing,
  1655. resetPosition: nothing,
  1656. needsContentAttribute: true
  1657. }, ContentEditableInput.prototype);
  1658. function posToDOM(cm, pos) {
  1659. var view = findViewForLine(cm, pos.line);
  1660. if (!view || view.hidden) return null;
  1661. var line = getLine(cm.doc, pos.line);
  1662. var info = mapFromLineView(view, line, pos.line);
  1663. var order = getOrder(line), side = "left";
  1664. if (order) {
  1665. var partPos = getBidiPartAt(order, pos.ch);
  1666. side = partPos % 2 ? "right" : "left";
  1667. }
  1668. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  1669. result.offset = result.collapse == "right" ? result.end : result.start;
  1670. return result;
  1671. }
  1672. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1673. function domToPos(cm, node, offset) {
  1674. var lineNode;
  1675. if (node == cm.display.lineDiv) {
  1676. lineNode = cm.display.lineDiv.childNodes[offset];
  1677. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1678. node = null; offset = 0;
  1679. } else {
  1680. for (lineNode = node;; lineNode = lineNode.parentNode) {
  1681. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1682. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1683. }
  1684. }
  1685. for (var i = 0; i < cm.display.view.length; i++) {
  1686. var lineView = cm.display.view[i];
  1687. if (lineView.node == lineNode)
  1688. return locateNodeInLineView(lineView, node, offset);
  1689. }
  1690. }
  1691. function locateNodeInLineView(lineView, node, offset) {
  1692. var wrapper = lineView.text.firstChild, bad = false;
  1693. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1694. if (node == wrapper) {
  1695. bad = true;
  1696. node = wrapper.childNodes[offset];
  1697. offset = 0;
  1698. if (!node) {
  1699. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1700. return badPos(Pos(lineNo(line), line.text.length), bad);
  1701. }
  1702. }
  1703. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1704. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1705. textNode = node.firstChild;
  1706. if (offset) offset = textNode.nodeValue.length;
  1707. }
  1708. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1709. var measure = lineView.measure, maps = measure.maps;
  1710. function find(textNode, topNode, offset) {
  1711. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1712. var map = i < 0 ? measure.map : maps[i];
  1713. for (var j = 0; j < map.length; j += 3) {
  1714. var curNode = map[j + 2];
  1715. if (curNode == textNode || curNode == topNode) {
  1716. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1717. var ch = map[j] + offset;
  1718. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1719. return Pos(line, ch);
  1720. }
  1721. }
  1722. }
  1723. }
  1724. var found = find(textNode, topNode, offset);
  1725. if (found) return badPos(found, bad);
  1726. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1727. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1728. found = find(after, after.firstChild, 0);
  1729. if (found)
  1730. return badPos(Pos(found.line, found.ch - dist), bad);
  1731. else
  1732. dist += after.textContent.length;
  1733. }
  1734. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1735. found = find(before, before.firstChild, -1);
  1736. if (found)
  1737. return badPos(Pos(found.line, found.ch + dist), bad);
  1738. else
  1739. dist += after.textContent.length;
  1740. }
  1741. }
  1742. function domTextBetween(cm, from, to, fromLine, toLine) {
  1743. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  1744. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  1745. function walk(node) {
  1746. if (node.nodeType == 1) {
  1747. var cmText = node.getAttribute("cm-text");
  1748. if (cmText != null) {
  1749. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1750. text += cmText;
  1751. return;
  1752. }
  1753. var markerID = node.getAttribute("cm-marker"), range;
  1754. if (markerID) {
  1755. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1756. if (found.length && (range = found[0].find()))
  1757. text += getBetween(cm.doc, range.from, range.to).join(lineSep);
  1758. return;
  1759. }
  1760. if (node.getAttribute("contenteditable") == "false") return;
  1761. for (var i = 0; i < node.childNodes.length; i++)
  1762. walk(node.childNodes[i]);
  1763. if (/^(pre|div|p)$/i.test(node.nodeName))
  1764. closing = true;
  1765. } else if (node.nodeType == 3) {
  1766. var val = node.nodeValue;
  1767. if (!val) return;
  1768. if (closing) {
  1769. text += lineSep;
  1770. closing = false;
  1771. }
  1772. text += val;
  1773. }
  1774. }
  1775. for (;;) {
  1776. walk(from);
  1777. if (from == to) break;
  1778. from = from.nextSibling;
  1779. }
  1780. return text;
  1781. }
  1782. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  1783. // SELECTION / CURSOR
  1784. // Selection objects are immutable. A new one is created every time
  1785. // the selection changes. A selection is one or more non-overlapping
  1786. // (and non-touching) ranges, sorted, and an integer that indicates
  1787. // which one is the primary selection (the one that's scrolled into
  1788. // view, that getCursor returns, etc).
  1789. function Selection(ranges, primIndex) {
  1790. this.ranges = ranges;
  1791. this.primIndex = primIndex;
  1792. }
  1793. Selection.prototype = {
  1794. primary: function() { return this.ranges[this.primIndex]; },
  1795. equals: function(other) {
  1796. if (other == this) return true;
  1797. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1798. for (var i = 0; i < this.ranges.length; i++) {
  1799. var here = this.ranges[i], there = other.ranges[i];
  1800. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1801. }
  1802. return true;
  1803. },
  1804. deepCopy: function() {
  1805. for (var out = [], i = 0; i < this.ranges.length; i++)
  1806. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1807. return new Selection(out, this.primIndex);
  1808. },
  1809. somethingSelected: function() {
  1810. for (var i = 0; i < this.ranges.length; i++)
  1811. if (!this.ranges[i].empty()) return true;
  1812. return false;
  1813. },
  1814. contains: function(pos, end) {
  1815. if (!end) end = pos;
  1816. for (var i = 0; i < this.ranges.length; i++) {
  1817. var range = this.ranges[i];
  1818. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1819. return i;
  1820. }
  1821. return -1;
  1822. }
  1823. };
  1824. function Range(anchor, head) {
  1825. this.anchor = anchor; this.head = head;
  1826. }
  1827. Range.prototype = {
  1828. from: function() { return minPos(this.anchor, this.head); },
  1829. to: function() { return maxPos(this.anchor, this.head); },
  1830. empty: function() {
  1831. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1832. }
  1833. };
  1834. // Take an unsorted, potentially overlapping set of ranges, and
  1835. // build a selection out of it. 'Consumes' ranges array (modifying
  1836. // it).
  1837. function normalizeSelection(ranges, primIndex) {
  1838. var prim = ranges[primIndex];
  1839. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1840. primIndex = indexOf(ranges, prim);
  1841. for (var i = 1; i < ranges.length; i++) {
  1842. var cur = ranges[i], prev = ranges[i - 1];
  1843. if (cmp(prev.to(), cur.from()) >= 0) {
  1844. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1845. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1846. if (i <= primIndex) --primIndex;
  1847. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1848. }
  1849. }
  1850. return new Selection(ranges, primIndex);
  1851. }
  1852. function simpleSelection(anchor, head) {
  1853. return new Selection([new Range(anchor, head || anchor)], 0);
  1854. }
  1855. // Most of the external API clips given positions to make sure they
  1856. // actually exist within the document.
  1857. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1858. function clipPos(doc, pos) {
  1859. if (pos.line < doc.first) return Pos(doc.first, 0);
  1860. var last = doc.first + doc.size - 1;
  1861. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1862. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1863. }
  1864. function clipToLen(pos, linelen) {
  1865. var ch = pos.ch;
  1866. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1867. else if (ch < 0) return Pos(pos.line, 0);
  1868. else return pos;
  1869. }
  1870. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1871. function clipPosArray(doc, array) {
  1872. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1873. return out;
  1874. }
  1875. // SELECTION UPDATES
  1876. // The 'scroll' parameter given to many of these indicated whether
  1877. // the new cursor position should be scrolled into view after
  1878. // modifying the selection.
  1879. // If shift is held or the extend flag is set, extends a range to
  1880. // include a given position (and optionally a second position).
  1881. // Otherwise, simply returns the range between the given positions.
  1882. // Used for cursor motion and such.
  1883. function extendRange(doc, range, head, other) {
  1884. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1885. var anchor = range.anchor;
  1886. if (other) {
  1887. var posBefore = cmp(head, anchor) < 0;
  1888. if (posBefore != (cmp(other, anchor) < 0)) {
  1889. anchor = head;
  1890. head = other;
  1891. } else if (posBefore != (cmp(head, other) < 0)) {
  1892. head = other;
  1893. }
  1894. }
  1895. return new Range(anchor, head);
  1896. } else {
  1897. return new Range(other || head, head);
  1898. }
  1899. }
  1900. // Extend the primary selection range, discard the rest.
  1901. function extendSelection(doc, head, other, options) {
  1902. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1903. }
  1904. // Extend all selections (pos is an array of selections with length
  1905. // equal the number of selections)
  1906. function extendSelections(doc, heads, options) {
  1907. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1908. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1909. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1910. setSelection(doc, newSel, options);
  1911. }
  1912. // Updates a single range in the selection.
  1913. function replaceOneSelection(doc, i, range, options) {
  1914. var ranges = doc.sel.ranges.slice(0);
  1915. ranges[i] = range;
  1916. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1917. }
  1918. // Reset the selection to a single range.
  1919. function setSimpleSelection(doc, anchor, head, options) {
  1920. setSelection(doc, simpleSelection(anchor, head), options);
  1921. }
  1922. // Give beforeSelectionChange handlers a change to influence a
  1923. // selection update.
  1924. function filterSelectionChange(doc, sel, options) {
  1925. var obj = {
  1926. ranges: sel.ranges,
  1927. update: function(ranges) {
  1928. this.ranges = [];
  1929. for (var i = 0; i < ranges.length; i++)
  1930. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1931. clipPos(doc, ranges[i].head));
  1932. },
  1933. origin: options && options.origin
  1934. };
  1935. signal(doc, "beforeSelectionChange", doc, obj);
  1936. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1937. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1938. else return sel;
  1939. }
  1940. function setSelectionReplaceHistory(doc, sel, options) {
  1941. var done = doc.history.done, last = lst(done);
  1942. if (last && last.ranges) {
  1943. done[done.length - 1] = sel;
  1944. setSelectionNoUndo(doc, sel, options);
  1945. } else {
  1946. setSelection(doc, sel, options);
  1947. }
  1948. }
  1949. // Set a new selection.
  1950. function setSelection(doc, sel, options) {
  1951. setSelectionNoUndo(doc, sel, options);
  1952. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1953. }
  1954. function setSelectionNoUndo(doc, sel, options) {
  1955. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1956. sel = filterSelectionChange(doc, sel, options);
  1957. var bias = options && options.bias ||
  1958. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1959. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1960. if (!(options && options.scroll === false) && doc.cm)
  1961. ensureCursorVisible(doc.cm);
  1962. }
  1963. function setSelectionInner(doc, sel) {
  1964. if (sel.equals(doc.sel)) return;
  1965. doc.sel = sel;
  1966. if (doc.cm) {
  1967. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1968. signalCursorActivity(doc.cm);
  1969. }
  1970. signalLater(doc, "cursorActivity", doc);
  1971. }
  1972. // Verify that the selection does not partially select any atomic
  1973. // marked ranges.
  1974. function reCheckSelection(doc) {
  1975. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1976. }
  1977. // Return a selection that does not partially select any atomic
  1978. // ranges.
  1979. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1980. var out;
  1981. for (var i = 0; i < sel.ranges.length; i++) {
  1982. var range = sel.ranges[i];
  1983. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  1984. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  1985. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  1986. if (out || newAnchor != range.anchor || newHead != range.head) {
  1987. if (!out) out = sel.ranges.slice(0, i);
  1988. out[i] = new Range(newAnchor, newHead);
  1989. }
  1990. }
  1991. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1992. }
  1993. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  1994. var line = getLine(doc, pos.line);
  1995. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  1996. var sp = line.markedSpans[i], m = sp.marker;
  1997. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  1998. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  1999. if (mayClear) {
  2000. signal(m, "beforeCursorEnter");
  2001. if (m.explicitlyCleared) {
  2002. if (!line.markedSpans) break;
  2003. else {--i; continue;}
  2004. }
  2005. }
  2006. if (!m.atomic) continue;
  2007. if (oldPos) {
  2008. var near = m.find(dir < 0 ? 1 : -1), diff;
  2009. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  2010. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
  2011. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  2012. return skipAtomicInner(doc, near, pos, dir, mayClear);
  2013. }
  2014. var far = m.find(dir < 0 ? -1 : 1);
  2015. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  2016. far = movePos(doc, far, dir, far.line == pos.line ? line : null);
  2017. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
  2018. }
  2019. }
  2020. return pos;
  2021. }
  2022. // Ensure a given position is not inside an atomic range.
  2023. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  2024. var dir = bias || 1;
  2025. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  2026. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  2027. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  2028. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  2029. if (!found) {
  2030. doc.cantEdit = true;
  2031. return Pos(doc.first, 0);
  2032. }
  2033. return found;
  2034. }
  2035. function movePos(doc, pos, dir, line) {
  2036. if (dir < 0 && pos.ch == 0) {
  2037. if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
  2038. else return null;
  2039. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  2040. if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
  2041. else return null;
  2042. } else {
  2043. return new Pos(pos.line, pos.ch + dir);
  2044. }
  2045. }
  2046. // SELECTION DRAWING
  2047. function updateSelection(cm) {
  2048. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2049. }
  2050. function prepareSelection(cm, primary) {
  2051. var doc = cm.doc, result = {};
  2052. var curFragment = result.cursors = document.createDocumentFragment();
  2053. var selFragment = result.selection = document.createDocumentFragment();
  2054. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2055. if (primary === false && i == doc.sel.primIndex) continue;
  2056. var range = doc.sel.ranges[i];
  2057. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
  2058. var collapsed = range.empty();
  2059. if (collapsed || cm.options.showCursorWhenSelecting)
  2060. drawSelectionCursor(cm, range.head, curFragment);
  2061. if (!collapsed)
  2062. drawSelectionRange(cm, range, selFragment);
  2063. }
  2064. return result;
  2065. }
  2066. // Draws a cursor for the given range
  2067. function drawSelectionCursor(cm, head, output) {
  2068. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2069. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2070. cursor.style.left = pos.left + "px";
  2071. cursor.style.top = pos.top + "px";
  2072. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2073. if (pos.other) {
  2074. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2075. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2076. otherCursor.style.display = "";
  2077. otherCursor.style.left = pos.other.left + "px";
  2078. otherCursor.style.top = pos.other.top + "px";
  2079. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2080. }
  2081. }
  2082. // Draws the given range as a highlighted selection
  2083. function drawSelectionRange(cm, range, output) {
  2084. var display = cm.display, doc = cm.doc;
  2085. var fragment = document.createDocumentFragment();
  2086. var padding = paddingH(cm.display), leftSide = padding.left;
  2087. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2088. function add(left, top, width, bottom) {
  2089. if (top < 0) top = 0;
  2090. top = Math.round(top);
  2091. bottom = Math.round(bottom);
  2092. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  2093. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  2094. "px; height: " + (bottom - top) + "px"));
  2095. }
  2096. function drawForLine(line, fromArg, toArg) {
  2097. var lineObj = getLine(doc, line);
  2098. var lineLen = lineObj.text.length;
  2099. var start, end;
  2100. function coords(ch, bias) {
  2101. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2102. }
  2103. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  2104. var leftPos = coords(from, "left"), rightPos, left, right;
  2105. if (from == to) {
  2106. rightPos = leftPos;
  2107. left = right = leftPos.left;
  2108. } else {
  2109. rightPos = coords(to - 1, "right");
  2110. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2111. left = leftPos.left;
  2112. right = rightPos.right;
  2113. }
  2114. if (fromArg == null && from == 0) left = leftSide;
  2115. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2116. add(left, leftPos.top, null, leftPos.bottom);
  2117. left = leftSide;
  2118. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2119. }
  2120. if (toArg == null && to == lineLen) right = rightSide;
  2121. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2122. start = leftPos;
  2123. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2124. end = rightPos;
  2125. if (left < leftSide + 1) left = leftSide;
  2126. add(left, rightPos.top, right - left, rightPos.bottom);
  2127. });
  2128. return {start: start, end: end};
  2129. }
  2130. var sFrom = range.from(), sTo = range.to();
  2131. if (sFrom.line == sTo.line) {
  2132. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2133. } else {
  2134. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2135. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2136. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2137. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2138. if (singleVLine) {
  2139. if (leftEnd.top < rightStart.top - 2) {
  2140. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2141. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2142. } else {
  2143. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2144. }
  2145. }
  2146. if (leftEnd.bottom < rightStart.top)
  2147. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2148. }
  2149. output.appendChild(fragment);
  2150. }
  2151. // Cursor-blinking
  2152. function restartBlink(cm) {
  2153. if (!cm.state.focused) return;
  2154. var display = cm.display;
  2155. clearInterval(display.blinker);
  2156. var on = true;
  2157. display.cursorDiv.style.visibility = "";
  2158. if (cm.options.cursorBlinkRate > 0)
  2159. display.blinker = setInterval(function() {
  2160. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2161. }, cm.options.cursorBlinkRate);
  2162. else if (cm.options.cursorBlinkRate < 0)
  2163. display.cursorDiv.style.visibility = "hidden";
  2164. }
  2165. // HIGHLIGHT WORKER
  2166. function startWorker(cm, time) {
  2167. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2168. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2169. }
  2170. function highlightWorker(cm) {
  2171. var doc = cm.doc;
  2172. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2173. if (doc.frontier >= cm.display.viewTo) return;
  2174. var end = +new Date + cm.options.workTime;
  2175. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2176. var changedLines = [];
  2177. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  2178. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2179. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  2180. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  2181. line.styles = highlighted.styles;
  2182. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2183. if (newCls) line.styleClasses = newCls;
  2184. else if (oldCls) line.styleClasses = null;
  2185. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2186. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2187. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2188. if (ischange) changedLines.push(doc.frontier);
  2189. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  2190. } else {
  2191. if (line.text.length <= cm.options.maxHighlightLength)
  2192. processLine(cm, line.text, state);
  2193. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2194. }
  2195. ++doc.frontier;
  2196. if (+new Date > end) {
  2197. startWorker(cm, cm.options.workDelay);
  2198. return true;
  2199. }
  2200. });
  2201. if (changedLines.length) runInOp(cm, function() {
  2202. for (var i = 0; i < changedLines.length; i++)
  2203. regLineChange(cm, changedLines[i], "text");
  2204. });
  2205. }
  2206. // Finds the line to start with when starting a parse. Tries to
  2207. // find a line with a stateAfter, so that it can start with a
  2208. // valid state. If that fails, it returns the line with the
  2209. // smallest indentation, which tends to need the least context to
  2210. // parse correctly.
  2211. function findStartLine(cm, n, precise) {
  2212. var minindent, minline, doc = cm.doc;
  2213. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2214. for (var search = n; search > lim; --search) {
  2215. if (search <= doc.first) return doc.first;
  2216. var line = getLine(doc, search - 1);
  2217. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2218. var indented = countColumn(line.text, null, cm.options.tabSize);
  2219. if (minline == null || minindent > indented) {
  2220. minline = search - 1;
  2221. minindent = indented;
  2222. }
  2223. }
  2224. return minline;
  2225. }
  2226. function getStateBefore(cm, n, precise) {
  2227. var doc = cm.doc, display = cm.display;
  2228. if (!doc.mode.startState) return true;
  2229. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  2230. if (!state) state = startState(doc.mode);
  2231. else state = copyState(doc.mode, state);
  2232. doc.iter(pos, n, function(line) {
  2233. processLine(cm, line.text, state);
  2234. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2235. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2236. ++pos;
  2237. });
  2238. if (precise) doc.frontier = pos;
  2239. return state;
  2240. }
  2241. // POSITION MEASUREMENT
  2242. function paddingTop(display) {return display.lineSpace.offsetTop;}
  2243. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  2244. function paddingH(display) {
  2245. if (display.cachedPaddingH) return display.cachedPaddingH;
  2246. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2247. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2248. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2249. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2250. return data;
  2251. }
  2252. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2253. function displayWidth(cm) {
  2254. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2255. }
  2256. function displayHeight(cm) {
  2257. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2258. }
  2259. // Ensure the lineView.wrapping.heights array is populated. This is
  2260. // an array of bottom offsets for the lines that make up a drawn
  2261. // line. When lineWrapping is on, there might be more than one
  2262. // height.
  2263. function ensureLineHeights(cm, lineView, rect) {
  2264. var wrapping = cm.options.lineWrapping;
  2265. var curWidth = wrapping && displayWidth(cm);
  2266. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2267. var heights = lineView.measure.heights = [];
  2268. if (wrapping) {
  2269. lineView.measure.width = curWidth;
  2270. var rects = lineView.text.firstChild.getClientRects();
  2271. for (var i = 0; i < rects.length - 1; i++) {
  2272. var cur = rects[i], next = rects[i + 1];
  2273. if (Math.abs(cur.bottom - next.bottom) > 2)
  2274. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2275. }
  2276. }
  2277. heights.push(rect.bottom - rect.top);
  2278. }
  2279. }
  2280. // Find a line map (mapping character offsets to text nodes) and a
  2281. // measurement cache for the given line number. (A line view might
  2282. // contain multiple lines when collapsed ranges are present.)
  2283. function mapFromLineView(lineView, line, lineN) {
  2284. if (lineView.line == line)
  2285. return {map: lineView.measure.map, cache: lineView.measure.cache};
  2286. for (var i = 0; i < lineView.rest.length; i++)
  2287. if (lineView.rest[i] == line)
  2288. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  2289. for (var i = 0; i < lineView.rest.length; i++)
  2290. if (lineNo(lineView.rest[i]) > lineN)
  2291. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  2292. }
  2293. // Render a line into the hidden node display.externalMeasured. Used
  2294. // when measurement is needed for a line that's not in the viewport.
  2295. function updateExternalMeasurement(cm, line) {
  2296. line = visualLine(line);
  2297. var lineN = lineNo(line);
  2298. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2299. view.lineN = lineN;
  2300. var built = view.built = buildLineContent(cm, view);
  2301. view.text = built.pre;
  2302. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2303. return view;
  2304. }
  2305. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2306. // for a given character.
  2307. function measureChar(cm, line, ch, bias) {
  2308. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2309. }
  2310. // Find a line view that corresponds to the given line number.
  2311. function findViewForLine(cm, lineN) {
  2312. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2313. return cm.display.view[findViewIndex(cm, lineN)];
  2314. var ext = cm.display.externalMeasured;
  2315. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2316. return ext;
  2317. }
  2318. // Measurement can be split in two steps, the set-up work that
  2319. // applies to the whole line, and the measurement of the actual
  2320. // character. Functions like coordsChar, that need to do a lot of
  2321. // measurements in a row, can thus ensure that the set-up work is
  2322. // only done once.
  2323. function prepareMeasureForLine(cm, line) {
  2324. var lineN = lineNo(line);
  2325. var view = findViewForLine(cm, lineN);
  2326. if (view && !view.text) {
  2327. view = null;
  2328. } else if (view && view.changes) {
  2329. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2330. cm.curOp.forceUpdate = true;
  2331. }
  2332. if (!view)
  2333. view = updateExternalMeasurement(cm, line);
  2334. var info = mapFromLineView(view, line, lineN);
  2335. return {
  2336. line: line, view: view, rect: null,
  2337. map: info.map, cache: info.cache, before: info.before,
  2338. hasHeights: false
  2339. };
  2340. }
  2341. // Given a prepared measurement object, measures the position of an
  2342. // actual character (or fetches it from the cache).
  2343. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2344. if (prepared.before) ch = -1;
  2345. var key = ch + (bias || ""), found;
  2346. if (prepared.cache.hasOwnProperty(key)) {
  2347. found = prepared.cache[key];
  2348. } else {
  2349. if (!prepared.rect)
  2350. prepared.rect = prepared.view.text.getBoundingClientRect();
  2351. if (!prepared.hasHeights) {
  2352. ensureLineHeights(cm, prepared.view, prepared.rect);
  2353. prepared.hasHeights = true;
  2354. }
  2355. found = measureCharInner(cm, prepared, ch, bias);
  2356. if (!found.bogus) prepared.cache[key] = found;
  2357. }
  2358. return {left: found.left, right: found.right,
  2359. top: varHeight ? found.rtop : found.top,
  2360. bottom: varHeight ? found.rbottom : found.bottom};
  2361. }
  2362. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2363. function nodeAndOffsetInLineMap(map, ch, bias) {
  2364. var node, start, end, collapse;
  2365. // First, search the line map for the text node corresponding to,
  2366. // or closest to, the target character.
  2367. for (var i = 0; i < map.length; i += 3) {
  2368. var mStart = map[i], mEnd = map[i + 1];
  2369. if (ch < mStart) {
  2370. start = 0; end = 1;
  2371. collapse = "left";
  2372. } else if (ch < mEnd) {
  2373. start = ch - mStart;
  2374. end = start + 1;
  2375. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2376. end = mEnd - mStart;
  2377. start = end - 1;
  2378. if (ch >= mEnd) collapse = "right";
  2379. }
  2380. if (start != null) {
  2381. node = map[i + 2];
  2382. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2383. collapse = bias;
  2384. if (bias == "left" && start == 0)
  2385. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2386. node = map[(i -= 3) + 2];
  2387. collapse = "left";
  2388. }
  2389. if (bias == "right" && start == mEnd - mStart)
  2390. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2391. node = map[(i += 3) + 2];
  2392. collapse = "right";
  2393. }
  2394. break;
  2395. }
  2396. }
  2397. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  2398. }
  2399. function getUsefulRect(rects, bias) {
  2400. var rect = nullRect
  2401. if (bias == "left") for (var i = 0; i < rects.length; i++) {
  2402. if ((rect = rects[i]).left != rect.right) break
  2403. } else for (var i = rects.length - 1; i >= 0; i--) {
  2404. if ((rect = rects[i]).left != rect.right) break
  2405. }
  2406. return rect
  2407. }
  2408. function measureCharInner(cm, prepared, ch, bias) {
  2409. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2410. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2411. var rect;
  2412. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2413. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2414. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  2415. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  2416. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2417. rect = node.parentNode.getBoundingClientRect();
  2418. else
  2419. rect = getUsefulRect(range(node, start, end).getClientRects(), bias)
  2420. if (rect.left || rect.right || start == 0) break;
  2421. end = start;
  2422. start = start - 1;
  2423. collapse = "right";
  2424. }
  2425. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2426. } else { // If it is a widget, simply get the box for the whole widget.
  2427. if (start > 0) collapse = bias = "right";
  2428. var rects;
  2429. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2430. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2431. else
  2432. rect = node.getBoundingClientRect();
  2433. }
  2434. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2435. var rSpan = node.parentNode.getClientRects()[0];
  2436. if (rSpan)
  2437. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  2438. else
  2439. rect = nullRect;
  2440. }
  2441. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2442. var mid = (rtop + rbot) / 2;
  2443. var heights = prepared.view.measure.heights;
  2444. for (var i = 0; i < heights.length - 1; i++)
  2445. if (mid < heights[i]) break;
  2446. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2447. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2448. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2449. top: top, bottom: bot};
  2450. if (!rect.left && !rect.right) result.bogus = true;
  2451. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2452. return result;
  2453. }
  2454. // Work around problem with bounding client rects on ranges being
  2455. // returned incorrectly when zoomed on IE10 and below.
  2456. function maybeUpdateRectForZooming(measure, rect) {
  2457. if (!window.screen || screen.logicalXDPI == null ||
  2458. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2459. return rect;
  2460. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2461. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2462. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2463. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  2464. }
  2465. function clearLineMeasurementCacheFor(lineView) {
  2466. if (lineView.measure) {
  2467. lineView.measure.cache = {};
  2468. lineView.measure.heights = null;
  2469. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2470. lineView.measure.caches[i] = {};
  2471. }
  2472. }
  2473. function clearLineMeasurementCache(cm) {
  2474. cm.display.externalMeasure = null;
  2475. removeChildren(cm.display.lineMeasure);
  2476. for (var i = 0; i < cm.display.view.length; i++)
  2477. clearLineMeasurementCacheFor(cm.display.view[i]);
  2478. }
  2479. function clearCaches(cm) {
  2480. clearLineMeasurementCache(cm);
  2481. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2482. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2483. cm.display.lineNumChars = null;
  2484. }
  2485. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2486. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2487. // Converts a {top, bottom, left, right} box from line-local
  2488. // coordinates into another coordinate system. Context may be one of
  2489. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2490. // or "page".
  2491. function intoCoordSystem(cm, lineObj, rect, context) {
  2492. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2493. var size = widgetHeight(lineObj.widgets[i]);
  2494. rect.top += size; rect.bottom += size;
  2495. }
  2496. if (context == "line") return rect;
  2497. if (!context) context = "local";
  2498. var yOff = heightAtLine(lineObj);
  2499. if (context == "local") yOff += paddingTop(cm.display);
  2500. else yOff -= cm.display.viewOffset;
  2501. if (context == "page" || context == "window") {
  2502. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2503. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2504. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2505. rect.left += xOff; rect.right += xOff;
  2506. }
  2507. rect.top += yOff; rect.bottom += yOff;
  2508. return rect;
  2509. }
  2510. // Coverts a box from "div" coords to another coordinate system.
  2511. // Context may be "window", "page", "div", or "local"/null.
  2512. function fromCoordSystem(cm, coords, context) {
  2513. if (context == "div") return coords;
  2514. var left = coords.left, top = coords.top;
  2515. // First move into "page" coordinate system
  2516. if (context == "page") {
  2517. left -= pageScrollX();
  2518. top -= pageScrollY();
  2519. } else if (context == "local" || !context) {
  2520. var localBox = cm.display.sizer.getBoundingClientRect();
  2521. left += localBox.left;
  2522. top += localBox.top;
  2523. }
  2524. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2525. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  2526. }
  2527. function charCoords(cm, pos, context, lineObj, bias) {
  2528. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2529. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2530. }
  2531. // Returns a box for a given cursor position, which may have an
  2532. // 'other' property containing the position of the secondary cursor
  2533. // on a bidi boundary.
  2534. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2535. lineObj = lineObj || getLine(cm.doc, pos.line);
  2536. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2537. function get(ch, right) {
  2538. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2539. if (right) m.left = m.right; else m.right = m.left;
  2540. return intoCoordSystem(cm, lineObj, m, context);
  2541. }
  2542. function getBidi(ch, partPos) {
  2543. var part = order[partPos], right = part.level % 2;
  2544. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2545. part = order[--partPos];
  2546. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2547. right = true;
  2548. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2549. part = order[++partPos];
  2550. ch = bidiLeft(part) - part.level % 2;
  2551. right = false;
  2552. }
  2553. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2554. return get(ch, right);
  2555. }
  2556. var order = getOrder(lineObj), ch = pos.ch;
  2557. if (!order) return get(ch);
  2558. var partPos = getBidiPartAt(order, ch);
  2559. var val = getBidi(ch, partPos);
  2560. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2561. return val;
  2562. }
  2563. // Used to cheaply estimate the coordinates for a position. Used for
  2564. // intermediate scroll updates.
  2565. function estimateCoords(cm, pos) {
  2566. var left = 0, pos = clipPos(cm.doc, pos);
  2567. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2568. var lineObj = getLine(cm.doc, pos.line);
  2569. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2570. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  2571. }
  2572. // Positions returned by coordsChar contain some extra information.
  2573. // xRel is the relative x position of the input coordinates compared
  2574. // to the found position (so xRel > 0 means the coordinates are to
  2575. // the right of the character position, for example). When outside
  2576. // is true, that means the coordinates lie outside the line's
  2577. // vertical range.
  2578. function PosWithInfo(line, ch, outside, xRel) {
  2579. var pos = Pos(line, ch);
  2580. pos.xRel = xRel;
  2581. if (outside) pos.outside = true;
  2582. return pos;
  2583. }
  2584. // Compute the character position closest to the given coordinates.
  2585. // Input must be lineSpace-local ("div" coordinate system).
  2586. function coordsChar(cm, x, y) {
  2587. var doc = cm.doc;
  2588. y += cm.display.viewOffset;
  2589. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2590. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2591. if (lineN > last)
  2592. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2593. if (x < 0) x = 0;
  2594. var lineObj = getLine(doc, lineN);
  2595. for (;;) {
  2596. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2597. var merged = collapsedSpanAtEnd(lineObj);
  2598. var mergedPos = merged && merged.find(0, true);
  2599. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2600. lineN = lineNo(lineObj = mergedPos.to.line);
  2601. else
  2602. return found;
  2603. }
  2604. }
  2605. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2606. var innerOff = y - heightAtLine(lineObj);
  2607. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2608. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2609. function getX(ch) {
  2610. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2611. wrongLine = true;
  2612. if (innerOff > sp.bottom) return sp.left - adjust;
  2613. else if (innerOff < sp.top) return sp.left + adjust;
  2614. else wrongLine = false;
  2615. return sp.left;
  2616. }
  2617. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2618. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2619. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2620. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2621. // Do a binary search between these bounds.
  2622. for (;;) {
  2623. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2624. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2625. var outside = ch == from ? fromOutside : toOutside
  2626. var xDiff = x - (ch == from ? fromX : toX);
  2627. // This is a kludge to handle the case where the coordinates
  2628. // are after a line-wrapped line. We should replace it with a
  2629. // more general handling of cursor positions around line
  2630. // breaks. (Issue #4078)
  2631. if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 &&
  2632. ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) {
  2633. var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right");
  2634. if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) {
  2635. outside = false
  2636. ch++
  2637. xDiff = x - charSize.right
  2638. }
  2639. }
  2640. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  2641. var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2642. return pos;
  2643. }
  2644. var step = Math.ceil(dist / 2), middle = from + step;
  2645. if (bidi) {
  2646. middle = from;
  2647. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2648. }
  2649. var middleX = getX(middle);
  2650. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  2651. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  2652. }
  2653. }
  2654. var measureText;
  2655. // Compute the default text height.
  2656. function textHeight(display) {
  2657. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2658. if (measureText == null) {
  2659. measureText = elt("pre");
  2660. // Measure a bunch of lines, for browsers that compute
  2661. // fractional heights.
  2662. for (var i = 0; i < 49; ++i) {
  2663. measureText.appendChild(document.createTextNode("x"));
  2664. measureText.appendChild(elt("br"));
  2665. }
  2666. measureText.appendChild(document.createTextNode("x"));
  2667. }
  2668. removeChildrenAndAdd(display.measure, measureText);
  2669. var height = measureText.offsetHeight / 50;
  2670. if (height > 3) display.cachedTextHeight = height;
  2671. removeChildren(display.measure);
  2672. return height || 1;
  2673. }
  2674. // Compute the default character width.
  2675. function charWidth(display) {
  2676. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2677. var anchor = elt("span", "xxxxxxxxxx");
  2678. var pre = elt("pre", [anchor]);
  2679. removeChildrenAndAdd(display.measure, pre);
  2680. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2681. if (width > 2) display.cachedCharWidth = width;
  2682. return width || 10;
  2683. }
  2684. // OPERATIONS
  2685. // Operations are used to wrap a series of changes to the editor
  2686. // state in such a way that each change won't have to update the
  2687. // cursor and display (which would be awkward, slow, and
  2688. // error-prone). Instead, display updates are batched and then all
  2689. // combined and executed at once.
  2690. var operationGroup = null;
  2691. var nextOpId = 0;
  2692. // Start a new operation.
  2693. function startOperation(cm) {
  2694. cm.curOp = {
  2695. cm: cm,
  2696. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2697. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2698. forceUpdate: false, // Used to force a redraw
  2699. updateInput: null, // Whether to reset the input textarea
  2700. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2701. changeObjs: null, // Accumulated changes, for firing change events
  2702. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2703. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2704. selectionChanged: false, // Whether the selection needs to be redrawn
  2705. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2706. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2707. scrollToPos: null, // Used to scroll to a specific position
  2708. focus: false,
  2709. id: ++nextOpId // Unique ID
  2710. };
  2711. if (operationGroup) {
  2712. operationGroup.ops.push(cm.curOp);
  2713. } else {
  2714. cm.curOp.ownsGroup = operationGroup = {
  2715. ops: [cm.curOp],
  2716. delayedCallbacks: []
  2717. };
  2718. }
  2719. }
  2720. function fireCallbacksForOps(group) {
  2721. // Calls delayed callbacks and cursorActivity handlers until no
  2722. // new ones appear
  2723. var callbacks = group.delayedCallbacks, i = 0;
  2724. do {
  2725. for (; i < callbacks.length; i++)
  2726. callbacks[i].call(null);
  2727. for (var j = 0; j < group.ops.length; j++) {
  2728. var op = group.ops[j];
  2729. if (op.cursorActivityHandlers)
  2730. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2731. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  2732. }
  2733. } while (i < callbacks.length);
  2734. }
  2735. // Finish an operation, updating the display and signalling delayed events
  2736. function endOperation(cm) {
  2737. var op = cm.curOp, group = op.ownsGroup;
  2738. if (!group) return;
  2739. try { fireCallbacksForOps(group); }
  2740. finally {
  2741. operationGroup = null;
  2742. for (var i = 0; i < group.ops.length; i++)
  2743. group.ops[i].cm.curOp = null;
  2744. endOperations(group);
  2745. }
  2746. }
  2747. // The DOM updates done when an operation finishes are batched so
  2748. // that the minimum number of relayouts are required.
  2749. function endOperations(group) {
  2750. var ops = group.ops;
  2751. for (var i = 0; i < ops.length; i++) // Read DOM
  2752. endOperation_R1(ops[i]);
  2753. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2754. endOperation_W1(ops[i]);
  2755. for (var i = 0; i < ops.length; i++) // Read DOM
  2756. endOperation_R2(ops[i]);
  2757. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2758. endOperation_W2(ops[i]);
  2759. for (var i = 0; i < ops.length; i++) // Read DOM
  2760. endOperation_finish(ops[i]);
  2761. }
  2762. function endOperation_R1(op) {
  2763. var cm = op.cm, display = cm.display;
  2764. maybeClipScrollbars(cm);
  2765. if (op.updateMaxLine) findMaxLine(cm);
  2766. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2767. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2768. op.scrollToPos.to.line >= display.viewTo) ||
  2769. display.maxLineChanged && cm.options.lineWrapping;
  2770. op.update = op.mustUpdate &&
  2771. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  2772. }
  2773. function endOperation_W1(op) {
  2774. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2775. }
  2776. function endOperation_R2(op) {
  2777. var cm = op.cm, display = cm.display;
  2778. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2779. op.barMeasure = measureForScrollbars(cm);
  2780. // If the max line changed since it was last measured, measure it,
  2781. // and ensure the document's width matches it.
  2782. // updateDisplay_W2 will use these properties to do the actual resizing
  2783. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2784. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2785. cm.display.sizerWidth = op.adjustWidthTo;
  2786. op.barMeasure.scrollWidth =
  2787. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2788. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2789. }
  2790. if (op.updatedDisplay || op.selectionChanged)
  2791. op.preparedSelection = display.input.prepareSelection(op.focus);
  2792. }
  2793. function endOperation_W2(op) {
  2794. var cm = op.cm;
  2795. if (op.adjustWidthTo != null) {
  2796. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2797. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2798. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2799. cm.display.maxLineChanged = false;
  2800. }
  2801. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  2802. if (op.preparedSelection)
  2803. cm.display.input.showSelection(op.preparedSelection, takeFocus);
  2804. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2805. updateScrollbars(cm, op.barMeasure);
  2806. if (op.updatedDisplay)
  2807. setDocumentHeight(cm, op.barMeasure);
  2808. if (op.selectionChanged) restartBlink(cm);
  2809. if (cm.state.focused && op.updateInput)
  2810. cm.display.input.reset(op.typing);
  2811. if (takeFocus) ensureFocus(op.cm);
  2812. }
  2813. function endOperation_finish(op) {
  2814. var cm = op.cm, display = cm.display, doc = cm.doc;
  2815. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2816. // Abort mouse wheel delta measurement, when scrolling explicitly
  2817. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2818. display.wheelStartX = display.wheelStartY = null;
  2819. // Propagate the scroll position to the actual DOM scroller
  2820. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2821. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2822. display.scrollbars.setScrollTop(doc.scrollTop);
  2823. display.scroller.scrollTop = doc.scrollTop;
  2824. }
  2825. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2826. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  2827. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2828. display.scroller.scrollLeft = doc.scrollLeft;
  2829. alignHorizontally(cm);
  2830. }
  2831. // If we need to scroll a specific position into view, do so.
  2832. if (op.scrollToPos) {
  2833. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2834. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2835. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2836. }
  2837. // Fire events for markers that are hidden/unidden by editing or
  2838. // undoing
  2839. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2840. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2841. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2842. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2843. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2844. if (display.wrapper.offsetHeight)
  2845. doc.scrollTop = cm.display.scroller.scrollTop;
  2846. // Fire change events, and delayed event handlers
  2847. if (op.changeObjs)
  2848. signal(cm, "changes", cm, op.changeObjs);
  2849. if (op.update)
  2850. op.update.finish();
  2851. }
  2852. // Run the given function in an operation
  2853. function runInOp(cm, f) {
  2854. if (cm.curOp) return f();
  2855. startOperation(cm);
  2856. try { return f(); }
  2857. finally { endOperation(cm); }
  2858. }
  2859. // Wraps a function in an operation. Returns the wrapped function.
  2860. function operation(cm, f) {
  2861. return function() {
  2862. if (cm.curOp) return f.apply(cm, arguments);
  2863. startOperation(cm);
  2864. try { return f.apply(cm, arguments); }
  2865. finally { endOperation(cm); }
  2866. };
  2867. }
  2868. // Used to add methods to editor and doc instances, wrapping them in
  2869. // operations.
  2870. function methodOp(f) {
  2871. return function() {
  2872. if (this.curOp) return f.apply(this, arguments);
  2873. startOperation(this);
  2874. try { return f.apply(this, arguments); }
  2875. finally { endOperation(this); }
  2876. };
  2877. }
  2878. function docMethodOp(f) {
  2879. return function() {
  2880. var cm = this.cm;
  2881. if (!cm || cm.curOp) return f.apply(this, arguments);
  2882. startOperation(cm);
  2883. try { return f.apply(this, arguments); }
  2884. finally { endOperation(cm); }
  2885. };
  2886. }
  2887. // VIEW TRACKING
  2888. // These objects are used to represent the visible (currently drawn)
  2889. // part of the document. A LineView may correspond to multiple
  2890. // logical lines, if those are connected by collapsed ranges.
  2891. function LineView(doc, line, lineN) {
  2892. // The starting line
  2893. this.line = line;
  2894. // Continuing lines, if any
  2895. this.rest = visualLineContinued(line);
  2896. // Number of logical lines in this visual line
  2897. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2898. this.node = this.text = null;
  2899. this.hidden = lineIsHidden(doc, line);
  2900. }
  2901. // Create a range of LineView objects for the given lines.
  2902. function buildViewArray(cm, from, to) {
  2903. var array = [], nextPos;
  2904. for (var pos = from; pos < to; pos = nextPos) {
  2905. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2906. nextPos = pos + view.size;
  2907. array.push(view);
  2908. }
  2909. return array;
  2910. }
  2911. // Updates the display.view data structure for a given change to the
  2912. // document. From and to are in pre-change coordinates. Lendiff is
  2913. // the amount of lines added or subtracted by the change. This is
  2914. // used for changes that span multiple lines, or change the way
  2915. // lines are divided into visual lines. regLineChange (below)
  2916. // registers single-line changes.
  2917. function regChange(cm, from, to, lendiff) {
  2918. if (from == null) from = cm.doc.first;
  2919. if (to == null) to = cm.doc.first + cm.doc.size;
  2920. if (!lendiff) lendiff = 0;
  2921. var display = cm.display;
  2922. if (lendiff && to < display.viewTo &&
  2923. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2924. display.updateLineNumbers = from;
  2925. cm.curOp.viewChanged = true;
  2926. if (from >= display.viewTo) { // Change after
  2927. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2928. resetView(cm);
  2929. } else if (to <= display.viewFrom) { // Change before
  2930. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2931. resetView(cm);
  2932. } else {
  2933. display.viewFrom += lendiff;
  2934. display.viewTo += lendiff;
  2935. }
  2936. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2937. resetView(cm);
  2938. } else if (from <= display.viewFrom) { // Top overlap
  2939. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2940. if (cut) {
  2941. display.view = display.view.slice(cut.index);
  2942. display.viewFrom = cut.lineN;
  2943. display.viewTo += lendiff;
  2944. } else {
  2945. resetView(cm);
  2946. }
  2947. } else if (to >= display.viewTo) { // Bottom overlap
  2948. var cut = viewCuttingPoint(cm, from, from, -1);
  2949. if (cut) {
  2950. display.view = display.view.slice(0, cut.index);
  2951. display.viewTo = cut.lineN;
  2952. } else {
  2953. resetView(cm);
  2954. }
  2955. } else { // Gap in the middle
  2956. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2957. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2958. if (cutTop && cutBot) {
  2959. display.view = display.view.slice(0, cutTop.index)
  2960. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2961. .concat(display.view.slice(cutBot.index));
  2962. display.viewTo += lendiff;
  2963. } else {
  2964. resetView(cm);
  2965. }
  2966. }
  2967. var ext = display.externalMeasured;
  2968. if (ext) {
  2969. if (to < ext.lineN)
  2970. ext.lineN += lendiff;
  2971. else if (from < ext.lineN + ext.size)
  2972. display.externalMeasured = null;
  2973. }
  2974. }
  2975. // Register a change to a single line. Type must be one of "text",
  2976. // "gutter", "class", "widget"
  2977. function regLineChange(cm, line, type) {
  2978. cm.curOp.viewChanged = true;
  2979. var display = cm.display, ext = cm.display.externalMeasured;
  2980. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2981. display.externalMeasured = null;
  2982. if (line < display.viewFrom || line >= display.viewTo) return;
  2983. var lineView = display.view[findViewIndex(cm, line)];
  2984. if (lineView.node == null) return;
  2985. var arr = lineView.changes || (lineView.changes = []);
  2986. if (indexOf(arr, type) == -1) arr.push(type);
  2987. }
  2988. // Clear the view.
  2989. function resetView(cm) {
  2990. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2991. cm.display.view = [];
  2992. cm.display.viewOffset = 0;
  2993. }
  2994. // Find the view element corresponding to a given line. Return null
  2995. // when the line isn't visible.
  2996. function findViewIndex(cm, n) {
  2997. if (n >= cm.display.viewTo) return null;
  2998. n -= cm.display.viewFrom;
  2999. if (n < 0) return null;
  3000. var view = cm.display.view;
  3001. for (var i = 0; i < view.length; i++) {
  3002. n -= view[i].size;
  3003. if (n < 0) return i;
  3004. }
  3005. }
  3006. function viewCuttingPoint(cm, oldN, newN, dir) {
  3007. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  3008. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3009. return {index: index, lineN: newN};
  3010. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  3011. n += view[i].size;
  3012. if (n != oldN) {
  3013. if (dir > 0) {
  3014. if (index == view.length - 1) return null;
  3015. diff = (n + view[index].size) - oldN;
  3016. index++;
  3017. } else {
  3018. diff = n - oldN;
  3019. }
  3020. oldN += diff; newN += diff;
  3021. }
  3022. while (visualLineNo(cm.doc, newN) != newN) {
  3023. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  3024. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3025. index += dir;
  3026. }
  3027. return {index: index, lineN: newN};
  3028. }
  3029. // Force the view to cover a given range, adding empty view element
  3030. // or clipping off existing ones as needed.
  3031. function adjustView(cm, from, to) {
  3032. var display = cm.display, view = display.view;
  3033. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3034. display.view = buildViewArray(cm, from, to);
  3035. display.viewFrom = from;
  3036. } else {
  3037. if (display.viewFrom > from)
  3038. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  3039. else if (display.viewFrom < from)
  3040. display.view = display.view.slice(findViewIndex(cm, from));
  3041. display.viewFrom = from;
  3042. if (display.viewTo < to)
  3043. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  3044. else if (display.viewTo > to)
  3045. display.view = display.view.slice(0, findViewIndex(cm, to));
  3046. }
  3047. display.viewTo = to;
  3048. }
  3049. // Count the number of lines in the view whose DOM representation is
  3050. // out of date (or nonexistent).
  3051. function countDirtyView(cm) {
  3052. var view = cm.display.view, dirty = 0;
  3053. for (var i = 0; i < view.length; i++) {
  3054. var lineView = view[i];
  3055. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  3056. }
  3057. return dirty;
  3058. }
  3059. // EVENT HANDLERS
  3060. // Attach the necessary event handlers when initializing the editor
  3061. function registerEventHandlers(cm) {
  3062. var d = cm.display;
  3063. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  3064. // Older IE's will not fire a second mousedown for a double click
  3065. if (ie && ie_version < 11)
  3066. on(d.scroller, "dblclick", operation(cm, function(e) {
  3067. if (signalDOMEvent(cm, e)) return;
  3068. var pos = posFromMouse(cm, e);
  3069. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  3070. e_preventDefault(e);
  3071. var word = cm.findWordAt(pos);
  3072. extendSelection(cm.doc, word.anchor, word.head);
  3073. }));
  3074. else
  3075. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  3076. // Some browsers fire contextmenu *after* opening the menu, at
  3077. // which point we can't mess with it anymore. Context menu is
  3078. // handled in onMouseDown for these browsers.
  3079. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  3080. // Used to suppress mouse event handling when a touch happens
  3081. var touchFinished, prevTouch = {end: 0};
  3082. function finishTouch() {
  3083. if (d.activeTouch) {
  3084. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  3085. prevTouch = d.activeTouch;
  3086. prevTouch.end = +new Date;
  3087. }
  3088. };
  3089. function isMouseLikeTouchEvent(e) {
  3090. if (e.touches.length != 1) return false;
  3091. var touch = e.touches[0];
  3092. return touch.radiusX <= 1 && touch.radiusY <= 1;
  3093. }
  3094. function farAway(touch, other) {
  3095. if (other.left == null) return true;
  3096. var dx = other.left - touch.left, dy = other.top - touch.top;
  3097. return dx * dx + dy * dy > 20 * 20;
  3098. }
  3099. on(d.scroller, "touchstart", function(e) {
  3100. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  3101. clearTimeout(touchFinished);
  3102. var now = +new Date;
  3103. d.activeTouch = {start: now, moved: false,
  3104. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  3105. if (e.touches.length == 1) {
  3106. d.activeTouch.left = e.touches[0].pageX;
  3107. d.activeTouch.top = e.touches[0].pageY;
  3108. }
  3109. }
  3110. });
  3111. on(d.scroller, "touchmove", function() {
  3112. if (d.activeTouch) d.activeTouch.moved = true;
  3113. });
  3114. on(d.scroller, "touchend", function(e) {
  3115. var touch = d.activeTouch;
  3116. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3117. !touch.moved && new Date - touch.start < 300) {
  3118. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3119. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3120. range = new Range(pos, pos);
  3121. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3122. range = cm.findWordAt(pos);
  3123. else // Triple tap
  3124. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3125. cm.setSelection(range.anchor, range.head);
  3126. cm.focus();
  3127. e_preventDefault(e);
  3128. }
  3129. finishTouch();
  3130. });
  3131. on(d.scroller, "touchcancel", finishTouch);
  3132. // Sync scrolling between fake scrollbars and real scrollable
  3133. // area, ensure viewport is updated when scrolling.
  3134. on(d.scroller, "scroll", function() {
  3135. if (d.scroller.clientHeight) {
  3136. setScrollTop(cm, d.scroller.scrollTop);
  3137. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3138. signal(cm, "scroll", cm);
  3139. }
  3140. });
  3141. // Listen to wheel events in order to try and update the viewport on time.
  3142. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  3143. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  3144. // Prevent wrapper from ever scrolling
  3145. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3146. d.dragFunctions = {
  3147. enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  3148. over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  3149. start: function(e){onDragStart(cm, e);},
  3150. drop: operation(cm, onDrop),
  3151. leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  3152. };
  3153. var inp = d.input.getField();
  3154. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  3155. on(inp, "keydown", operation(cm, onKeyDown));
  3156. on(inp, "keypress", operation(cm, onKeyPress));
  3157. on(inp, "focus", bind(onFocus, cm));
  3158. on(inp, "blur", bind(onBlur, cm));
  3159. }
  3160. function dragDropChanged(cm, value, old) {
  3161. var wasOn = old && old != CodeMirror.Init;
  3162. if (!value != !wasOn) {
  3163. var funcs = cm.display.dragFunctions;
  3164. var toggle = value ? on : off;
  3165. toggle(cm.display.scroller, "dragstart", funcs.start);
  3166. toggle(cm.display.scroller, "dragenter", funcs.enter);
  3167. toggle(cm.display.scroller, "dragover", funcs.over);
  3168. toggle(cm.display.scroller, "dragleave", funcs.leave);
  3169. toggle(cm.display.scroller, "drop", funcs.drop);
  3170. }
  3171. }
  3172. // Called when the window resizes
  3173. function onResize(cm) {
  3174. var d = cm.display;
  3175. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3176. return;
  3177. // Might be a text scaling operation, clear size caches.
  3178. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3179. d.scrollbarsClipped = false;
  3180. cm.setSize();
  3181. }
  3182. // MOUSE EVENTS
  3183. // Return true when the given mouse event happened in a widget
  3184. function eventInWidget(display, e) {
  3185. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3186. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3187. (n.parentNode == display.sizer && n != display.mover))
  3188. return true;
  3189. }
  3190. }
  3191. // Given a mouse event, find the corresponding position. If liberal
  3192. // is false, it checks whether a gutter or scrollbar was clicked,
  3193. // and returns null if it was. forRect is used by rectangular
  3194. // selections, and tries to estimate a character position even for
  3195. // coordinates beyond the right of the text.
  3196. function posFromMouse(cm, e, liberal, forRect) {
  3197. var display = cm.display;
  3198. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3199. var x, y, space = display.lineSpace.getBoundingClientRect();
  3200. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3201. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3202. catch (e) { return null; }
  3203. var coords = coordsChar(cm, x, y), line;
  3204. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3205. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3206. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3207. }
  3208. return coords;
  3209. }
  3210. // A mouse down can be a single click, double click, triple click,
  3211. // start of selection drag, start of text drag, new cursor
  3212. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3213. // middle-click-paste. Or it might be a click on something we should
  3214. // not interfere with, such as a scrollbar or widget.
  3215. function onMouseDown(e) {
  3216. var cm = this, display = cm.display;
  3217. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
  3218. display.shift = e.shiftKey;
  3219. if (eventInWidget(display, e)) {
  3220. if (!webkit) {
  3221. // Briefly turn off draggability, to allow widgets to do
  3222. // normal dragging things.
  3223. display.scroller.draggable = false;
  3224. setTimeout(function(){display.scroller.draggable = true;}, 100);
  3225. }
  3226. return;
  3227. }
  3228. if (clickInGutter(cm, e)) return;
  3229. var start = posFromMouse(cm, e);
  3230. window.focus();
  3231. switch (e_button(e)) {
  3232. case 1:
  3233. // #3261: make sure, that we're not starting a second selection
  3234. if (cm.state.selectingText)
  3235. cm.state.selectingText(e);
  3236. else if (start)
  3237. leftButtonDown(cm, e, start);
  3238. else if (e_target(e) == display.scroller)
  3239. e_preventDefault(e);
  3240. break;
  3241. case 2:
  3242. if (webkit) cm.state.lastMiddleDown = +new Date;
  3243. if (start) extendSelection(cm.doc, start);
  3244. setTimeout(function() {display.input.focus();}, 20);
  3245. e_preventDefault(e);
  3246. break;
  3247. case 3:
  3248. if (captureRightClick) onContextMenu(cm, e);
  3249. else delayBlurEvent(cm);
  3250. break;
  3251. }
  3252. }
  3253. var lastClick, lastDoubleClick;
  3254. function leftButtonDown(cm, e, start) {
  3255. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3256. else cm.curOp.focus = activeElt();
  3257. var now = +new Date, type;
  3258. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3259. type = "triple";
  3260. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3261. type = "double";
  3262. lastDoubleClick = {time: now, pos: start};
  3263. } else {
  3264. type = "single";
  3265. lastClick = {time: now, pos: start};
  3266. }
  3267. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3268. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  3269. type == "single" && (contained = sel.contains(start)) > -1 &&
  3270. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  3271. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  3272. leftButtonStartDrag(cm, e, start, modifier);
  3273. else
  3274. leftButtonSelect(cm, e, start, type, modifier);
  3275. }
  3276. // Start a text drag. When it ends, see if any dragging actually
  3277. // happen, and treat as a click if it didn't.
  3278. function leftButtonStartDrag(cm, e, start, modifier) {
  3279. var display = cm.display, startTime = +new Date;
  3280. var dragEnd = operation(cm, function(e2) {
  3281. if (webkit) display.scroller.draggable = false;
  3282. cm.state.draggingText = false;
  3283. off(document, "mouseup", dragEnd);
  3284. off(display.scroller, "drop", dragEnd);
  3285. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3286. e_preventDefault(e2);
  3287. if (!modifier && +new Date - 200 < startTime)
  3288. extendSelection(cm.doc, start);
  3289. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  3290. if (webkit || ie && ie_version == 9)
  3291. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  3292. else
  3293. display.input.focus();
  3294. }
  3295. });
  3296. // Let the drag handler handle this.
  3297. if (webkit) display.scroller.draggable = true;
  3298. cm.state.draggingText = dragEnd;
  3299. dragEnd.copy = mac ? e.altKey : e.ctrlKey
  3300. // IE's approach to draggable
  3301. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3302. on(document, "mouseup", dragEnd);
  3303. on(display.scroller, "drop", dragEnd);
  3304. }
  3305. // Normal selection, as opposed to text dragging.
  3306. function leftButtonSelect(cm, e, start, type, addNew) {
  3307. var display = cm.display, doc = cm.doc;
  3308. e_preventDefault(e);
  3309. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3310. if (addNew && !e.shiftKey) {
  3311. ourIndex = doc.sel.contains(start);
  3312. if (ourIndex > -1)
  3313. ourRange = ranges[ourIndex];
  3314. else
  3315. ourRange = new Range(start, start);
  3316. } else {
  3317. ourRange = doc.sel.primary();
  3318. ourIndex = doc.sel.primIndex;
  3319. }
  3320. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  3321. type = "rect";
  3322. if (!addNew) ourRange = new Range(start, start);
  3323. start = posFromMouse(cm, e, true, true);
  3324. ourIndex = -1;
  3325. } else if (type == "double") {
  3326. var word = cm.findWordAt(start);
  3327. if (cm.display.shift || doc.extend)
  3328. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3329. else
  3330. ourRange = word;
  3331. } else if (type == "triple") {
  3332. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3333. if (cm.display.shift || doc.extend)
  3334. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3335. else
  3336. ourRange = line;
  3337. } else {
  3338. ourRange = extendRange(doc, ourRange, start);
  3339. }
  3340. if (!addNew) {
  3341. ourIndex = 0;
  3342. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3343. startSel = doc.sel;
  3344. } else if (ourIndex == -1) {
  3345. ourIndex = ranges.length;
  3346. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3347. {scroll: false, origin: "*mouse"});
  3348. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  3349. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  3350. {scroll: false, origin: "*mouse"});
  3351. startSel = doc.sel;
  3352. } else {
  3353. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3354. }
  3355. var lastPos = start;
  3356. function extendTo(pos) {
  3357. if (cmp(lastPos, pos) == 0) return;
  3358. lastPos = pos;
  3359. if (type == "rect") {
  3360. var ranges = [], tabSize = cm.options.tabSize;
  3361. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3362. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3363. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3364. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3365. line <= end; line++) {
  3366. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3367. if (left == right)
  3368. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3369. else if (text.length > leftPos)
  3370. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3371. }
  3372. if (!ranges.length) ranges.push(new Range(start, start));
  3373. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3374. {origin: "*mouse", scroll: false});
  3375. cm.scrollIntoView(pos);
  3376. } else {
  3377. var oldRange = ourRange;
  3378. var anchor = oldRange.anchor, head = pos;
  3379. if (type != "single") {
  3380. if (type == "double")
  3381. var range = cm.findWordAt(pos);
  3382. else
  3383. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3384. if (cmp(range.anchor, anchor) > 0) {
  3385. head = range.head;
  3386. anchor = minPos(oldRange.from(), range.anchor);
  3387. } else {
  3388. head = range.anchor;
  3389. anchor = maxPos(oldRange.to(), range.head);
  3390. }
  3391. }
  3392. var ranges = startSel.ranges.slice(0);
  3393. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3394. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3395. }
  3396. }
  3397. var editorSize = display.wrapper.getBoundingClientRect();
  3398. // Used to ensure timeout re-tries don't fire when another extend
  3399. // happened in the meantime (clearTimeout isn't reliable -- at
  3400. // least on Chrome, the timeouts still happen even when cleared,
  3401. // if the clear happens after their scheduled firing time).
  3402. var counter = 0;
  3403. function extend(e) {
  3404. var curCount = ++counter;
  3405. var cur = posFromMouse(cm, e, true, type == "rect");
  3406. if (!cur) return;
  3407. if (cmp(cur, lastPos) != 0) {
  3408. cm.curOp.focus = activeElt();
  3409. extendTo(cur);
  3410. var visible = visibleLines(display, doc);
  3411. if (cur.line >= visible.to || cur.line < visible.from)
  3412. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  3413. } else {
  3414. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3415. if (outside) setTimeout(operation(cm, function() {
  3416. if (counter != curCount) return;
  3417. display.scroller.scrollTop += outside;
  3418. extend(e);
  3419. }), 50);
  3420. }
  3421. }
  3422. function done(e) {
  3423. cm.state.selectingText = false;
  3424. counter = Infinity;
  3425. e_preventDefault(e);
  3426. display.input.focus();
  3427. off(document, "mousemove", move);
  3428. off(document, "mouseup", up);
  3429. doc.history.lastSelOrigin = null;
  3430. }
  3431. var move = operation(cm, function(e) {
  3432. if (!e_button(e)) done(e);
  3433. else extend(e);
  3434. });
  3435. var up = operation(cm, done);
  3436. cm.state.selectingText = up;
  3437. on(document, "mousemove", move);
  3438. on(document, "mouseup", up);
  3439. }
  3440. // Determines whether an event happened in the gutter, and fires the
  3441. // handlers for the corresponding event.
  3442. function gutterEvent(cm, e, type, prevent) {
  3443. try { var mX = e.clientX, mY = e.clientY; }
  3444. catch(e) { return false; }
  3445. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3446. if (prevent) e_preventDefault(e);
  3447. var display = cm.display;
  3448. var lineBox = display.lineDiv.getBoundingClientRect();
  3449. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3450. mY -= lineBox.top - display.viewOffset;
  3451. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3452. var g = display.gutters.childNodes[i];
  3453. if (g && g.getBoundingClientRect().right >= mX) {
  3454. var line = lineAtHeight(cm.doc, mY);
  3455. var gutter = cm.options.gutters[i];
  3456. signal(cm, type, cm, line, gutter, e);
  3457. return e_defaultPrevented(e);
  3458. }
  3459. }
  3460. }
  3461. function clickInGutter(cm, e) {
  3462. return gutterEvent(cm, e, "gutterClick", true);
  3463. }
  3464. // Kludge to work around strange IE behavior where it'll sometimes
  3465. // re-fire a series of drag-related events right after the drop (#1551)
  3466. var lastDrop = 0;
  3467. function onDrop(e) {
  3468. var cm = this;
  3469. clearDragCursor(cm);
  3470. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3471. return;
  3472. e_preventDefault(e);
  3473. if (ie) lastDrop = +new Date;
  3474. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3475. if (!pos || cm.isReadOnly()) return;
  3476. // Might be a file drop, in which case we simply extract the text
  3477. // and insert it.
  3478. if (files && files.length && window.FileReader && window.File) {
  3479. var n = files.length, text = Array(n), read = 0;
  3480. var loadFile = function(file, i) {
  3481. if (cm.options.allowDropFileTypes &&
  3482. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  3483. return;
  3484. var reader = new FileReader;
  3485. reader.onload = operation(cm, function() {
  3486. var content = reader.result;
  3487. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
  3488. text[i] = content;
  3489. if (++read == n) {
  3490. pos = clipPos(cm.doc, pos);
  3491. var change = {from: pos, to: pos,
  3492. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  3493. origin: "paste"};
  3494. makeChange(cm.doc, change);
  3495. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3496. }
  3497. });
  3498. reader.readAsText(file);
  3499. };
  3500. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3501. } else { // Normal drop
  3502. // Don't do a replace if the drop happened inside of the selected text.
  3503. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3504. cm.state.draggingText(e);
  3505. // Ensure the editor is re-focused
  3506. setTimeout(function() {cm.display.input.focus();}, 20);
  3507. return;
  3508. }
  3509. try {
  3510. var text = e.dataTransfer.getData("Text");
  3511. if (text) {
  3512. if (cm.state.draggingText && !cm.state.draggingText.copy)
  3513. var selected = cm.listSelections();
  3514. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3515. if (selected) for (var i = 0; i < selected.length; ++i)
  3516. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3517. cm.replaceSelection(text, "around", "paste");
  3518. cm.display.input.focus();
  3519. }
  3520. }
  3521. catch(e){}
  3522. }
  3523. }
  3524. function onDragStart(cm, e) {
  3525. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3526. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3527. e.dataTransfer.setData("Text", cm.getSelection());
  3528. e.dataTransfer.effectAllowed = "copyMove"
  3529. // Use dummy image instead of default browsers image.
  3530. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3531. if (e.dataTransfer.setDragImage && !safari) {
  3532. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3533. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3534. if (presto) {
  3535. img.width = img.height = 1;
  3536. cm.display.wrapper.appendChild(img);
  3537. // Force a relayout, or Opera won't use our image for some obscure reason
  3538. img._top = img.offsetTop;
  3539. }
  3540. e.dataTransfer.setDragImage(img, 0, 0);
  3541. if (presto) img.parentNode.removeChild(img);
  3542. }
  3543. }
  3544. function onDragOver(cm, e) {
  3545. var pos = posFromMouse(cm, e);
  3546. if (!pos) return;
  3547. var frag = document.createDocumentFragment();
  3548. drawSelectionCursor(cm, pos, frag);
  3549. if (!cm.display.dragCursor) {
  3550. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  3551. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  3552. }
  3553. removeChildrenAndAdd(cm.display.dragCursor, frag);
  3554. }
  3555. function clearDragCursor(cm) {
  3556. if (cm.display.dragCursor) {
  3557. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  3558. cm.display.dragCursor = null;
  3559. }
  3560. }
  3561. // SCROLL EVENTS
  3562. // Sync the scrollable area and scrollbars, ensure the viewport
  3563. // covers the visible area.
  3564. function setScrollTop(cm, val) {
  3565. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3566. cm.doc.scrollTop = val;
  3567. if (!gecko) updateDisplaySimple(cm, {top: val});
  3568. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3569. cm.display.scrollbars.setScrollTop(val);
  3570. if (gecko) updateDisplaySimple(cm);
  3571. startWorker(cm, 100);
  3572. }
  3573. // Sync scroller and scrollbar, ensure the gutter elements are
  3574. // aligned.
  3575. function setScrollLeft(cm, val, isScroller) {
  3576. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3577. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3578. cm.doc.scrollLeft = val;
  3579. alignHorizontally(cm);
  3580. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3581. cm.display.scrollbars.setScrollLeft(val);
  3582. }
  3583. // Since the delta values reported on mouse wheel events are
  3584. // unstandardized between browsers and even browser versions, and
  3585. // generally horribly unpredictable, this code starts by measuring
  3586. // the scroll effect that the first few mouse wheel events have,
  3587. // and, from that, detects the way it can convert deltas to pixel
  3588. // offsets afterwards.
  3589. //
  3590. // The reason we want to know the amount a wheel event will scroll
  3591. // is that it gives us a chance to update the display before the
  3592. // actual scrolling happens, reducing flickering.
  3593. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3594. // Fill in a browser-detected starting value on browsers where we
  3595. // know one. These don't have to be accurate -- the result of them
  3596. // being wrong would just be a slight flicker on the first wheel
  3597. // scroll (if it is large enough).
  3598. if (ie) wheelPixelsPerUnit = -.53;
  3599. else if (gecko) wheelPixelsPerUnit = 15;
  3600. else if (chrome) wheelPixelsPerUnit = -.7;
  3601. else if (safari) wheelPixelsPerUnit = -1/3;
  3602. var wheelEventDelta = function(e) {
  3603. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3604. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3605. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3606. else if (dy == null) dy = e.wheelDelta;
  3607. return {x: dx, y: dy};
  3608. };
  3609. CodeMirror.wheelEventPixels = function(e) {
  3610. var delta = wheelEventDelta(e);
  3611. delta.x *= wheelPixelsPerUnit;
  3612. delta.y *= wheelPixelsPerUnit;
  3613. return delta;
  3614. };
  3615. function onScrollWheel(cm, e) {
  3616. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3617. var display = cm.display, scroll = display.scroller;
  3618. // Quit if there's nothing to scroll here
  3619. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  3620. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  3621. if (!(dx && canScrollX || dy && canScrollY)) return;
  3622. // Webkit browsers on OS X abort momentum scrolls when the target
  3623. // of the scroll event is removed from the scrollable element.
  3624. // This hack (see related code in patchDisplay) makes sure the
  3625. // element is kept around.
  3626. if (dy && mac && webkit) {
  3627. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3628. for (var i = 0; i < view.length; i++) {
  3629. if (view[i].node == cur) {
  3630. cm.display.currentWheelTarget = cur;
  3631. break outer;
  3632. }
  3633. }
  3634. }
  3635. }
  3636. // On some browsers, horizontal scrolling will cause redraws to
  3637. // happen before the gutter has been realigned, causing it to
  3638. // wriggle around in a most unseemly way. When we have an
  3639. // estimated pixels/delta value, we just handle horizontal
  3640. // scrolling entirely here. It'll be slightly off from native, but
  3641. // better than glitching out.
  3642. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3643. if (dy && canScrollY)
  3644. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3645. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3646. // Only prevent default scrolling if vertical scrolling is
  3647. // actually possible. Otherwise, it causes vertical scroll
  3648. // jitter on OSX trackpads when deltaX is small and deltaY
  3649. // is large (issue #3579)
  3650. if (!dy || (dy && canScrollY))
  3651. e_preventDefault(e);
  3652. display.wheelStartX = null; // Abort measurement, if in progress
  3653. return;
  3654. }
  3655. // 'Project' the visible viewport to cover the area that is being
  3656. // scrolled into view (if we know enough to estimate it).
  3657. if (dy && wheelPixelsPerUnit != null) {
  3658. var pixels = dy * wheelPixelsPerUnit;
  3659. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3660. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3661. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3662. updateDisplaySimple(cm, {top: top, bottom: bot});
  3663. }
  3664. if (wheelSamples < 20) {
  3665. if (display.wheelStartX == null) {
  3666. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3667. display.wheelDX = dx; display.wheelDY = dy;
  3668. setTimeout(function() {
  3669. if (display.wheelStartX == null) return;
  3670. var movedX = scroll.scrollLeft - display.wheelStartX;
  3671. var movedY = scroll.scrollTop - display.wheelStartY;
  3672. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3673. (movedX && display.wheelDX && movedX / display.wheelDX);
  3674. display.wheelStartX = display.wheelStartY = null;
  3675. if (!sample) return;
  3676. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3677. ++wheelSamples;
  3678. }, 200);
  3679. } else {
  3680. display.wheelDX += dx; display.wheelDY += dy;
  3681. }
  3682. }
  3683. }
  3684. // KEY EVENTS
  3685. // Run a handler that was bound to a key.
  3686. function doHandleBinding(cm, bound, dropShift) {
  3687. if (typeof bound == "string") {
  3688. bound = commands[bound];
  3689. if (!bound) return false;
  3690. }
  3691. // Ensure previous input has been read, so that the handler sees a
  3692. // consistent view of the document
  3693. cm.display.input.ensurePolled();
  3694. var prevShift = cm.display.shift, done = false;
  3695. try {
  3696. if (cm.isReadOnly()) cm.state.suppressEdits = true;
  3697. if (dropShift) cm.display.shift = false;
  3698. done = bound(cm) != Pass;
  3699. } finally {
  3700. cm.display.shift = prevShift;
  3701. cm.state.suppressEdits = false;
  3702. }
  3703. return done;
  3704. }
  3705. function lookupKeyForEditor(cm, name, handle) {
  3706. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3707. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3708. if (result) return result;
  3709. }
  3710. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3711. || lookupKey(name, cm.options.keyMap, handle, cm);
  3712. }
  3713. var stopSeq = new Delayed;
  3714. function dispatchKey(cm, name, e, handle) {
  3715. var seq = cm.state.keySeq;
  3716. if (seq) {
  3717. if (isModifierKey(name)) return "handled";
  3718. stopSeq.set(50, function() {
  3719. if (cm.state.keySeq == seq) {
  3720. cm.state.keySeq = null;
  3721. cm.display.input.reset();
  3722. }
  3723. });
  3724. name = seq + " " + name;
  3725. }
  3726. var result = lookupKeyForEditor(cm, name, handle);
  3727. if (result == "multi")
  3728. cm.state.keySeq = name;
  3729. if (result == "handled")
  3730. signalLater(cm, "keyHandled", cm, name, e);
  3731. if (result == "handled" || result == "multi") {
  3732. e_preventDefault(e);
  3733. restartBlink(cm);
  3734. }
  3735. if (seq && !result && /\'$/.test(name)) {
  3736. e_preventDefault(e);
  3737. return true;
  3738. }
  3739. return !!result;
  3740. }
  3741. // Handle a key from the keydown event.
  3742. function handleKeyBinding(cm, e) {
  3743. var name = keyName(e, true);
  3744. if (!name) return false;
  3745. if (e.shiftKey && !cm.state.keySeq) {
  3746. // First try to resolve full name (including 'Shift-'). Failing
  3747. // that, see if there is a cursor-motion command (starting with
  3748. // 'go') bound to the keyname without 'Shift-'.
  3749. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3750. || dispatchKey(cm, name, e, function(b) {
  3751. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3752. return doHandleBinding(cm, b);
  3753. });
  3754. } else {
  3755. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3756. }
  3757. }
  3758. // Handle a key from the keypress event
  3759. function handleCharBinding(cm, e, ch) {
  3760. return dispatchKey(cm, "'" + ch + "'", e,
  3761. function(b) { return doHandleBinding(cm, b, true); });
  3762. }
  3763. var lastStoppedKey = null;
  3764. function onKeyDown(e) {
  3765. var cm = this;
  3766. cm.curOp.focus = activeElt();
  3767. if (signalDOMEvent(cm, e)) return;
  3768. // IE does strange things with escape.
  3769. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3770. var code = e.keyCode;
  3771. cm.display.shift = code == 16 || e.shiftKey;
  3772. var handled = handleKeyBinding(cm, e);
  3773. if (presto) {
  3774. lastStoppedKey = handled ? code : null;
  3775. // Opera has no cut event... we try to at least catch the key combo
  3776. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3777. cm.replaceSelection("", null, "cut");
  3778. }
  3779. // Turn mouse into crosshair when Alt is held on Mac.
  3780. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3781. showCrossHair(cm);
  3782. }
  3783. function showCrossHair(cm) {
  3784. var lineDiv = cm.display.lineDiv;
  3785. addClass(lineDiv, "CodeMirror-crosshair");
  3786. function up(e) {
  3787. if (e.keyCode == 18 || !e.altKey) {
  3788. rmClass(lineDiv, "CodeMirror-crosshair");
  3789. off(document, "keyup", up);
  3790. off(document, "mouseover", up);
  3791. }
  3792. }
  3793. on(document, "keyup", up);
  3794. on(document, "mouseover", up);
  3795. }
  3796. function onKeyUp(e) {
  3797. if (e.keyCode == 16) this.doc.sel.shift = false;
  3798. signalDOMEvent(this, e);
  3799. }
  3800. function onKeyPress(e) {
  3801. var cm = this;
  3802. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3803. var keyCode = e.keyCode, charCode = e.charCode;
  3804. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3805. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3806. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3807. if (handleCharBinding(cm, e, ch)) return;
  3808. cm.display.input.onKeyPress(e);
  3809. }
  3810. // FOCUS/BLUR EVENTS
  3811. function delayBlurEvent(cm) {
  3812. cm.state.delayingBlurEvent = true;
  3813. setTimeout(function() {
  3814. if (cm.state.delayingBlurEvent) {
  3815. cm.state.delayingBlurEvent = false;
  3816. onBlur(cm);
  3817. }
  3818. }, 100);
  3819. }
  3820. function onFocus(cm) {
  3821. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  3822. if (cm.options.readOnly == "nocursor") return;
  3823. if (!cm.state.focused) {
  3824. signal(cm, "focus", cm);
  3825. cm.state.focused = true;
  3826. addClass(cm.display.wrapper, "CodeMirror-focused");
  3827. // This test prevents this from firing when a context
  3828. // menu is closed (since the input reset would kill the
  3829. // select-all detection hack)
  3830. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3831. cm.display.input.reset();
  3832. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  3833. }
  3834. cm.display.input.receivedFocus();
  3835. }
  3836. restartBlink(cm);
  3837. }
  3838. function onBlur(cm) {
  3839. if (cm.state.delayingBlurEvent) return;
  3840. if (cm.state.focused) {
  3841. signal(cm, "blur", cm);
  3842. cm.state.focused = false;
  3843. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3844. }
  3845. clearInterval(cm.display.blinker);
  3846. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3847. }
  3848. // CONTEXT MENU HANDLING
  3849. // To make the context menu work, we need to briefly unhide the
  3850. // textarea (making it as unobtrusive as possible) to let the
  3851. // right-click take effect on it.
  3852. function onContextMenu(cm, e) {
  3853. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3854. if (signalDOMEvent(cm, e, "contextmenu")) return;
  3855. cm.display.input.onContextMenu(e);
  3856. }
  3857. function contextMenuInGutter(cm, e) {
  3858. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3859. return gutterEvent(cm, e, "gutterContextMenu", false);
  3860. }
  3861. // UPDATING
  3862. // Compute the position of the end of a change (its 'to' property
  3863. // refers to the pre-change end).
  3864. var changeEnd = CodeMirror.changeEnd = function(change) {
  3865. if (!change.text) return change.to;
  3866. return Pos(change.from.line + change.text.length - 1,
  3867. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3868. };
  3869. // Adjust a position to refer to the post-change position of the
  3870. // same text, or the end of the change if the change covers it.
  3871. function adjustForChange(pos, change) {
  3872. if (cmp(pos, change.from) < 0) return pos;
  3873. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3874. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3875. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3876. return Pos(line, ch);
  3877. }
  3878. function computeSelAfterChange(doc, change) {
  3879. var out = [];
  3880. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3881. var range = doc.sel.ranges[i];
  3882. out.push(new Range(adjustForChange(range.anchor, change),
  3883. adjustForChange(range.head, change)));
  3884. }
  3885. return normalizeSelection(out, doc.sel.primIndex);
  3886. }
  3887. function offsetPos(pos, old, nw) {
  3888. if (pos.line == old.line)
  3889. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3890. else
  3891. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3892. }
  3893. // Used by replaceSelections to allow moving the selection to the
  3894. // start or around the replaced test. Hint may be "start" or "around".
  3895. function computeReplacedSel(doc, changes, hint) {
  3896. var out = [];
  3897. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3898. for (var i = 0; i < changes.length; i++) {
  3899. var change = changes[i];
  3900. var from = offsetPos(change.from, oldPrev, newPrev);
  3901. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3902. oldPrev = change.to;
  3903. newPrev = to;
  3904. if (hint == "around") {
  3905. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3906. out[i] = new Range(inv ? to : from, inv ? from : to);
  3907. } else {
  3908. out[i] = new Range(from, from);
  3909. }
  3910. }
  3911. return new Selection(out, doc.sel.primIndex);
  3912. }
  3913. // Allow "beforeChange" event handlers to influence a change
  3914. function filterChange(doc, change, update) {
  3915. var obj = {
  3916. canceled: false,
  3917. from: change.from,
  3918. to: change.to,
  3919. text: change.text,
  3920. origin: change.origin,
  3921. cancel: function() { this.canceled = true; }
  3922. };
  3923. if (update) obj.update = function(from, to, text, origin) {
  3924. if (from) this.from = clipPos(doc, from);
  3925. if (to) this.to = clipPos(doc, to);
  3926. if (text) this.text = text;
  3927. if (origin !== undefined) this.origin = origin;
  3928. };
  3929. signal(doc, "beforeChange", doc, obj);
  3930. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3931. if (obj.canceled) return null;
  3932. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3933. }
  3934. // Apply a change to a document, and add it to the document's
  3935. // history, and propagating it to all linked documents.
  3936. function makeChange(doc, change, ignoreReadOnly) {
  3937. if (doc.cm) {
  3938. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3939. if (doc.cm.state.suppressEdits) return;
  3940. }
  3941. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3942. change = filterChange(doc, change, true);
  3943. if (!change) return;
  3944. }
  3945. // Possibly split or suppress the update based on the presence
  3946. // of read-only spans in its range.
  3947. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3948. if (split) {
  3949. for (var i = split.length - 1; i >= 0; --i)
  3950. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3951. } else {
  3952. makeChangeInner(doc, change);
  3953. }
  3954. }
  3955. function makeChangeInner(doc, change) {
  3956. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3957. var selAfter = computeSelAfterChange(doc, change);
  3958. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3959. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3960. var rebased = [];
  3961. linkedDocs(doc, function(doc, sharedHist) {
  3962. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3963. rebaseHist(doc.history, change);
  3964. rebased.push(doc.history);
  3965. }
  3966. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3967. });
  3968. }
  3969. // Revert a change stored in a document's history.
  3970. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3971. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) return;
  3972. var hist = doc.history, event, selAfter = doc.sel;
  3973. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3974. // Verify that there is a useable event (so that ctrl-z won't
  3975. // needlessly clear selection events)
  3976. for (var i = 0; i < source.length; i++) {
  3977. event = source[i];
  3978. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3979. break;
  3980. }
  3981. if (i == source.length) return;
  3982. hist.lastOrigin = hist.lastSelOrigin = null;
  3983. for (;;) {
  3984. event = source.pop();
  3985. if (event.ranges) {
  3986. pushSelectionToHistory(event, dest);
  3987. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3988. setSelection(doc, event, {clearRedo: false});
  3989. return;
  3990. }
  3991. selAfter = event;
  3992. }
  3993. else break;
  3994. }
  3995. // Build up a reverse change object to add to the opposite history
  3996. // stack (redo when undoing, and vice versa).
  3997. var antiChanges = [];
  3998. pushSelectionToHistory(selAfter, dest);
  3999. dest.push({changes: antiChanges, generation: hist.generation});
  4000. hist.generation = event.generation || ++hist.maxGeneration;
  4001. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4002. for (var i = event.changes.length - 1; i >= 0; --i) {
  4003. var change = event.changes[i];
  4004. change.origin = type;
  4005. if (filter && !filterChange(doc, change, false)) {
  4006. source.length = 0;
  4007. return;
  4008. }
  4009. antiChanges.push(historyChangeFromChange(doc, change));
  4010. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4011. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4012. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  4013. var rebased = [];
  4014. // Propagate to the linked documents
  4015. linkedDocs(doc, function(doc, sharedHist) {
  4016. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4017. rebaseHist(doc.history, change);
  4018. rebased.push(doc.history);
  4019. }
  4020. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4021. });
  4022. }
  4023. }
  4024. // Sub-views need their line numbers shifted when text is added
  4025. // above or below them in the parent document.
  4026. function shiftDoc(doc, distance) {
  4027. if (distance == 0) return;
  4028. doc.first += distance;
  4029. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  4030. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  4031. Pos(range.head.line + distance, range.head.ch));
  4032. }), doc.sel.primIndex);
  4033. if (doc.cm) {
  4034. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4035. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4036. regLineChange(doc.cm, l, "gutter");
  4037. }
  4038. }
  4039. // More lower-level change function, handling only a single document
  4040. // (not linked ones).
  4041. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4042. if (doc.cm && !doc.cm.curOp)
  4043. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  4044. if (change.to.line < doc.first) {
  4045. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4046. return;
  4047. }
  4048. if (change.from.line > doc.lastLine()) return;
  4049. // Clip the change to the size of this doc
  4050. if (change.from.line < doc.first) {
  4051. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4052. shiftDoc(doc, shift);
  4053. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4054. text: [lst(change.text)], origin: change.origin};
  4055. }
  4056. var last = doc.lastLine();
  4057. if (change.to.line > last) {
  4058. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4059. text: [change.text[0]], origin: change.origin};
  4060. }
  4061. change.removed = getBetween(doc, change.from, change.to);
  4062. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  4063. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  4064. else updateDoc(doc, change, spans);
  4065. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4066. }
  4067. // Handle the interaction of a change to a document with the editor
  4068. // that this document is part of.
  4069. function makeChangeSingleDocInEditor(cm, change, spans) {
  4070. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4071. var recomputeMaxLength = false, checkWidthStart = from.line;
  4072. if (!cm.options.lineWrapping) {
  4073. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4074. doc.iter(checkWidthStart, to.line + 1, function(line) {
  4075. if (line == display.maxLine) {
  4076. recomputeMaxLength = true;
  4077. return true;
  4078. }
  4079. });
  4080. }
  4081. if (doc.sel.contains(change.from, change.to) > -1)
  4082. signalCursorActivity(cm);
  4083. updateDoc(doc, change, spans, estimateHeight(cm));
  4084. if (!cm.options.lineWrapping) {
  4085. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  4086. var len = lineLength(line);
  4087. if (len > display.maxLineLength) {
  4088. display.maxLine = line;
  4089. display.maxLineLength = len;
  4090. display.maxLineChanged = true;
  4091. recomputeMaxLength = false;
  4092. }
  4093. });
  4094. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  4095. }
  4096. // Adjust frontier, schedule worker
  4097. doc.frontier = Math.min(doc.frontier, from.line);
  4098. startWorker(cm, 400);
  4099. var lendiff = change.text.length - (to.line - from.line) - 1;
  4100. // Remember that these lines changed, for updating the display
  4101. if (change.full)
  4102. regChange(cm);
  4103. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4104. regLineChange(cm, from.line, "text");
  4105. else
  4106. regChange(cm, from.line, to.line + 1, lendiff);
  4107. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4108. if (changeHandler || changesHandler) {
  4109. var obj = {
  4110. from: from, to: to,
  4111. text: change.text,
  4112. removed: change.removed,
  4113. origin: change.origin
  4114. };
  4115. if (changeHandler) signalLater(cm, "change", cm, obj);
  4116. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  4117. }
  4118. cm.display.selForContextMenu = null;
  4119. }
  4120. function replaceRange(doc, code, from, to, origin) {
  4121. if (!to) to = from;
  4122. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  4123. if (typeof code == "string") code = doc.splitLines(code);
  4124. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4125. }
  4126. // SCROLLING THINGS INTO VIEW
  4127. // If an editor sits on the top or bottom of the window, partially
  4128. // scrolled out of view, this ensures that the cursor is visible.
  4129. function maybeScrollWindow(cm, coords) {
  4130. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  4131. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4132. if (coords.top + box.top < 0) doScroll = true;
  4133. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  4134. if (doScroll != null && !phantom) {
  4135. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  4136. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  4137. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  4138. coords.left + "px; width: 2px;");
  4139. cm.display.lineSpace.appendChild(scrollNode);
  4140. scrollNode.scrollIntoView(doScroll);
  4141. cm.display.lineSpace.removeChild(scrollNode);
  4142. }
  4143. }
  4144. // Scroll a given position into view (immediately), verifying that
  4145. // it actually became visible (as line heights are accurately
  4146. // measured, the position of something may 'drift' during drawing).
  4147. function scrollPosIntoView(cm, pos, end, margin) {
  4148. if (margin == null) margin = 0;
  4149. for (var limit = 0; limit < 5; limit++) {
  4150. var changed = false, coords = cursorCoords(cm, pos);
  4151. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4152. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  4153. Math.min(coords.top, endCoords.top) - margin,
  4154. Math.max(coords.left, endCoords.left),
  4155. Math.max(coords.bottom, endCoords.bottom) + margin);
  4156. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4157. if (scrollPos.scrollTop != null) {
  4158. setScrollTop(cm, scrollPos.scrollTop);
  4159. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  4160. }
  4161. if (scrollPos.scrollLeft != null) {
  4162. setScrollLeft(cm, scrollPos.scrollLeft);
  4163. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  4164. }
  4165. if (!changed) break;
  4166. }
  4167. return coords;
  4168. }
  4169. // Scroll a given set of coordinates into view (immediately).
  4170. function scrollIntoView(cm, x1, y1, x2, y2) {
  4171. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  4172. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  4173. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  4174. }
  4175. // Calculate a new scroll position needed to scroll the given
  4176. // rectangle into view. Returns an object with scrollTop and
  4177. // scrollLeft properties. When these are undefined, the
  4178. // vertical/horizontal position does not need to be adjusted.
  4179. function calculateScrollPos(cm, x1, y1, x2, y2) {
  4180. var display = cm.display, snapMargin = textHeight(cm.display);
  4181. if (y1 < 0) y1 = 0;
  4182. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4183. var screen = displayHeight(cm), result = {};
  4184. if (y2 - y1 > screen) y2 = y1 + screen;
  4185. var docBottom = cm.doc.height + paddingVert(display);
  4186. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4187. if (y1 < screentop) {
  4188. result.scrollTop = atTop ? 0 : y1;
  4189. } else if (y2 > screentop + screen) {
  4190. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4191. if (newTop != screentop) result.scrollTop = newTop;
  4192. }
  4193. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4194. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4195. var tooWide = x2 - x1 > screenw;
  4196. if (tooWide) x2 = x1 + screenw;
  4197. if (x1 < 10)
  4198. result.scrollLeft = 0;
  4199. else if (x1 < screenleft)
  4200. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4201. else if (x2 > screenw + screenleft - 3)
  4202. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4203. return result;
  4204. }
  4205. // Store a relative adjustment to the scroll position in the current
  4206. // operation (to be applied when the operation finishes).
  4207. function addToScrollPos(cm, left, top) {
  4208. if (left != null || top != null) resolveScrollToPos(cm);
  4209. if (left != null)
  4210. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4211. if (top != null)
  4212. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4213. }
  4214. // Make sure that at the end of the operation the current cursor is
  4215. // shown.
  4216. function ensureCursorVisible(cm) {
  4217. resolveScrollToPos(cm);
  4218. var cur = cm.getCursor(), from = cur, to = cur;
  4219. if (!cm.options.lineWrapping) {
  4220. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4221. to = Pos(cur.line, cur.ch + 1);
  4222. }
  4223. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  4224. }
  4225. // When an operation has its scrollToPos property set, and another
  4226. // scroll action is applied before the end of the operation, this
  4227. // 'simulates' scrolling that position into view in a cheap way, so
  4228. // that the effect of intermediate scroll commands is not ignored.
  4229. function resolveScrollToPos(cm) {
  4230. var range = cm.curOp.scrollToPos;
  4231. if (range) {
  4232. cm.curOp.scrollToPos = null;
  4233. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4234. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4235. Math.min(from.top, to.top) - range.margin,
  4236. Math.max(from.right, to.right),
  4237. Math.max(from.bottom, to.bottom) + range.margin);
  4238. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4239. }
  4240. }
  4241. // API UTILITIES
  4242. // Indent the given line. The how parameter can be "smart",
  4243. // "add"/null, "subtract", or "prev". When aggressive is false
  4244. // (typically set to true for forced single-line indents), empty
  4245. // lines are not indented, and places where the mode returns Pass
  4246. // are left alone.
  4247. function indentLine(cm, n, how, aggressive) {
  4248. var doc = cm.doc, state;
  4249. if (how == null) how = "add";
  4250. if (how == "smart") {
  4251. // Fall back to "prev" when the mode doesn't have an indentation
  4252. // method.
  4253. if (!doc.mode.indent) how = "prev";
  4254. else state = getStateBefore(cm, n);
  4255. }
  4256. var tabSize = cm.options.tabSize;
  4257. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4258. if (line.stateAfter) line.stateAfter = null;
  4259. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4260. if (!aggressive && !/\S/.test(line.text)) {
  4261. indentation = 0;
  4262. how = "not";
  4263. } else if (how == "smart") {
  4264. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4265. if (indentation == Pass || indentation > 150) {
  4266. if (!aggressive) return;
  4267. how = "prev";
  4268. }
  4269. }
  4270. if (how == "prev") {
  4271. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  4272. else indentation = 0;
  4273. } else if (how == "add") {
  4274. indentation = curSpace + cm.options.indentUnit;
  4275. } else if (how == "subtract") {
  4276. indentation = curSpace - cm.options.indentUnit;
  4277. } else if (typeof how == "number") {
  4278. indentation = curSpace + how;
  4279. }
  4280. indentation = Math.max(0, indentation);
  4281. var indentString = "", pos = 0;
  4282. if (cm.options.indentWithTabs)
  4283. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  4284. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4285. if (indentString != curSpaceString) {
  4286. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4287. line.stateAfter = null;
  4288. return true;
  4289. } else {
  4290. // Ensure that, if the cursor was in the whitespace at the start
  4291. // of the line, it is moved to the end of that space.
  4292. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4293. var range = doc.sel.ranges[i];
  4294. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4295. var pos = Pos(n, curSpaceString.length);
  4296. replaceOneSelection(doc, i, new Range(pos, pos));
  4297. break;
  4298. }
  4299. }
  4300. }
  4301. }
  4302. // Utility for applying a change to a line by handle or number,
  4303. // returning the number and optionally registering the line as
  4304. // changed.
  4305. function changeLine(doc, handle, changeType, op) {
  4306. var no = handle, line = handle;
  4307. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4308. else no = lineNo(handle);
  4309. if (no == null) return null;
  4310. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4311. return line;
  4312. }
  4313. // Helper for deleting text near the selection(s), used to implement
  4314. // backspace, delete, and similar functionality.
  4315. function deleteNearSelection(cm, compute) {
  4316. var ranges = cm.doc.sel.ranges, kill = [];
  4317. // Build up a set of ranges to kill first, merging overlapping
  4318. // ranges.
  4319. for (var i = 0; i < ranges.length; i++) {
  4320. var toKill = compute(ranges[i]);
  4321. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4322. var replaced = kill.pop();
  4323. if (cmp(replaced.from, toKill.from) < 0) {
  4324. toKill.from = replaced.from;
  4325. break;
  4326. }
  4327. }
  4328. kill.push(toKill);
  4329. }
  4330. // Next, remove those actual ranges.
  4331. runInOp(cm, function() {
  4332. for (var i = kill.length - 1; i >= 0; i--)
  4333. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4334. ensureCursorVisible(cm);
  4335. });
  4336. }
  4337. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4338. // right), unit can be "char", "column" (like char, but doesn't
  4339. // cross line boundaries), "word" (across next word), or "group" (to
  4340. // the start of next group of word or non-word-non-whitespace
  4341. // chars). The visually param controls whether, in right-to-left
  4342. // text, direction 1 means to move towards the next index in the
  4343. // string, or towards the character to the right of the current
  4344. // position. The resulting position will have a hitSide=true
  4345. // property if it reached the end of the document.
  4346. function findPosH(doc, pos, dir, unit, visually) {
  4347. var line = pos.line, ch = pos.ch, origDir = dir;
  4348. var lineObj = getLine(doc, line);
  4349. function findNextLine() {
  4350. var l = line + dir;
  4351. if (l < doc.first || l >= doc.first + doc.size) return false
  4352. line = l;
  4353. return lineObj = getLine(doc, l);
  4354. }
  4355. function moveOnce(boundToLine) {
  4356. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4357. if (next == null) {
  4358. if (!boundToLine && findNextLine()) {
  4359. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4360. else ch = dir < 0 ? lineObj.text.length : 0;
  4361. } else return false
  4362. } else ch = next;
  4363. return true;
  4364. }
  4365. if (unit == "char") {
  4366. moveOnce()
  4367. } else if (unit == "column") {
  4368. moveOnce(true)
  4369. } else if (unit == "word" || unit == "group") {
  4370. var sawType = null, group = unit == "group";
  4371. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4372. for (var first = true;; first = false) {
  4373. if (dir < 0 && !moveOnce(!first)) break;
  4374. var cur = lineObj.text.charAt(ch) || "\n";
  4375. var type = isWordChar(cur, helper) ? "w"
  4376. : group && cur == "\n" ? "n"
  4377. : !group || /\s/.test(cur) ? null
  4378. : "p";
  4379. if (group && !first && !type) type = "s";
  4380. if (sawType && sawType != type) {
  4381. if (dir < 0) {dir = 1; moveOnce();}
  4382. break;
  4383. }
  4384. if (type) sawType = type;
  4385. if (dir > 0 && !moveOnce(!first)) break;
  4386. }
  4387. }
  4388. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
  4389. if (!cmp(pos, result)) result.hitSide = true;
  4390. return result;
  4391. }
  4392. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4393. // "page" or "line". The resulting position will have a hitSide=true
  4394. // property if it reached the end of the document.
  4395. function findPosV(cm, pos, dir, unit) {
  4396. var doc = cm.doc, x = pos.left, y;
  4397. if (unit == "page") {
  4398. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4399. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4400. } else if (unit == "line") {
  4401. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4402. }
  4403. for (;;) {
  4404. var target = coordsChar(cm, x, y);
  4405. if (!target.outside) break;
  4406. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4407. y += dir * 5;
  4408. }
  4409. return target;
  4410. }
  4411. // EDITOR METHODS
  4412. // The publicly visible API. Note that methodOp(f) means
  4413. // 'wrap f in an operation, performed on its `this` parameter'.
  4414. // This is not the complete set of editor methods. Most of the
  4415. // methods defined on the Doc type are also injected into
  4416. // CodeMirror.prototype, for backwards compatibility and
  4417. // convenience.
  4418. CodeMirror.prototype = {
  4419. constructor: CodeMirror,
  4420. focus: function(){window.focus(); this.display.input.focus();},
  4421. setOption: function(option, value) {
  4422. var options = this.options, old = options[option];
  4423. if (options[option] == value && option != "mode") return;
  4424. options[option] = value;
  4425. if (optionHandlers.hasOwnProperty(option))
  4426. operation(this, optionHandlers[option])(this, value, old);
  4427. },
  4428. getOption: function(option) {return this.options[option];},
  4429. getDoc: function() {return this.doc;},
  4430. addKeyMap: function(map, bottom) {
  4431. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4432. },
  4433. removeKeyMap: function(map) {
  4434. var maps = this.state.keyMaps;
  4435. for (var i = 0; i < maps.length; ++i)
  4436. if (maps[i] == map || maps[i].name == map) {
  4437. maps.splice(i, 1);
  4438. return true;
  4439. }
  4440. },
  4441. addOverlay: methodOp(function(spec, options) {
  4442. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4443. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4444. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  4445. this.state.modeGen++;
  4446. regChange(this);
  4447. }),
  4448. removeOverlay: methodOp(function(spec) {
  4449. var overlays = this.state.overlays;
  4450. for (var i = 0; i < overlays.length; ++i) {
  4451. var cur = overlays[i].modeSpec;
  4452. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4453. overlays.splice(i, 1);
  4454. this.state.modeGen++;
  4455. regChange(this);
  4456. return;
  4457. }
  4458. }
  4459. }),
  4460. indentLine: methodOp(function(n, dir, aggressive) {
  4461. if (typeof dir != "string" && typeof dir != "number") {
  4462. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4463. else dir = dir ? "add" : "subtract";
  4464. }
  4465. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4466. }),
  4467. indentSelection: methodOp(function(how) {
  4468. var ranges = this.doc.sel.ranges, end = -1;
  4469. for (var i = 0; i < ranges.length; i++) {
  4470. var range = ranges[i];
  4471. if (!range.empty()) {
  4472. var from = range.from(), to = range.to();
  4473. var start = Math.max(end, from.line);
  4474. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4475. for (var j = start; j < end; ++j)
  4476. indentLine(this, j, how);
  4477. var newRanges = this.doc.sel.ranges;
  4478. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4479. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4480. } else if (range.head.line > end) {
  4481. indentLine(this, range.head.line, how, true);
  4482. end = range.head.line;
  4483. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4484. }
  4485. }
  4486. }),
  4487. // Fetch the parser token for a given character. Useful for hacks
  4488. // that want to inspect the mode state (say, for completion).
  4489. getTokenAt: function(pos, precise) {
  4490. return takeToken(this, pos, precise);
  4491. },
  4492. getLineTokens: function(line, precise) {
  4493. return takeToken(this, Pos(line), precise, true);
  4494. },
  4495. getTokenTypeAt: function(pos) {
  4496. pos = clipPos(this.doc, pos);
  4497. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4498. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4499. var type;
  4500. if (ch == 0) type = styles[2];
  4501. else for (;;) {
  4502. var mid = (before + after) >> 1;
  4503. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4504. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4505. else { type = styles[mid * 2 + 2]; break; }
  4506. }
  4507. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4508. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4509. },
  4510. getModeAt: function(pos) {
  4511. var mode = this.doc.mode;
  4512. if (!mode.innerMode) return mode;
  4513. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4514. },
  4515. getHelper: function(pos, type) {
  4516. return this.getHelpers(pos, type)[0];
  4517. },
  4518. getHelpers: function(pos, type) {
  4519. var found = [];
  4520. if (!helpers.hasOwnProperty(type)) return found;
  4521. var help = helpers[type], mode = this.getModeAt(pos);
  4522. if (typeof mode[type] == "string") {
  4523. if (help[mode[type]]) found.push(help[mode[type]]);
  4524. } else if (mode[type]) {
  4525. for (var i = 0; i < mode[type].length; i++) {
  4526. var val = help[mode[type][i]];
  4527. if (val) found.push(val);
  4528. }
  4529. } else if (mode.helperType && help[mode.helperType]) {
  4530. found.push(help[mode.helperType]);
  4531. } else if (help[mode.name]) {
  4532. found.push(help[mode.name]);
  4533. }
  4534. for (var i = 0; i < help._global.length; i++) {
  4535. var cur = help._global[i];
  4536. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4537. found.push(cur.val);
  4538. }
  4539. return found;
  4540. },
  4541. getStateAfter: function(line, precise) {
  4542. var doc = this.doc;
  4543. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  4544. return getStateBefore(this, line + 1, precise);
  4545. },
  4546. cursorCoords: function(start, mode) {
  4547. var pos, range = this.doc.sel.primary();
  4548. if (start == null) pos = range.head;
  4549. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4550. else pos = start ? range.from() : range.to();
  4551. return cursorCoords(this, pos, mode || "page");
  4552. },
  4553. charCoords: function(pos, mode) {
  4554. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4555. },
  4556. coordsChar: function(coords, mode) {
  4557. coords = fromCoordSystem(this, coords, mode || "page");
  4558. return coordsChar(this, coords.left, coords.top);
  4559. },
  4560. lineAtHeight: function(height, mode) {
  4561. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  4562. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4563. },
  4564. heightAtLine: function(line, mode) {
  4565. var end = false, lineObj;
  4566. if (typeof line == "number") {
  4567. var last = this.doc.first + this.doc.size - 1;
  4568. if (line < this.doc.first) line = this.doc.first;
  4569. else if (line > last) { line = last; end = true; }
  4570. lineObj = getLine(this.doc, line);
  4571. } else {
  4572. lineObj = line;
  4573. }
  4574. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  4575. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4576. },
  4577. defaultTextHeight: function() { return textHeight(this.display); },
  4578. defaultCharWidth: function() { return charWidth(this.display); },
  4579. setGutterMarker: methodOp(function(line, gutterID, value) {
  4580. return changeLine(this.doc, line, "gutter", function(line) {
  4581. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4582. markers[gutterID] = value;
  4583. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4584. return true;
  4585. });
  4586. }),
  4587. clearGutter: methodOp(function(gutterID) {
  4588. var cm = this, doc = cm.doc, i = doc.first;
  4589. doc.iter(function(line) {
  4590. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4591. line.gutterMarkers[gutterID] = null;
  4592. regLineChange(cm, i, "gutter");
  4593. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4594. }
  4595. ++i;
  4596. });
  4597. }),
  4598. lineInfo: function(line) {
  4599. if (typeof line == "number") {
  4600. if (!isLine(this.doc, line)) return null;
  4601. var n = line;
  4602. line = getLine(this.doc, line);
  4603. if (!line) return null;
  4604. } else {
  4605. var n = lineNo(line);
  4606. if (n == null) return null;
  4607. }
  4608. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4609. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4610. widgets: line.widgets};
  4611. },
  4612. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  4613. addWidget: function(pos, node, scroll, vert, horiz) {
  4614. var display = this.display;
  4615. pos = cursorCoords(this, clipPos(this.doc, pos));
  4616. var top = pos.bottom, left = pos.left;
  4617. node.style.position = "absolute";
  4618. node.setAttribute("cm-ignore-events", "true");
  4619. this.display.input.setUneditable(node);
  4620. display.sizer.appendChild(node);
  4621. if (vert == "over") {
  4622. top = pos.top;
  4623. } else if (vert == "above" || vert == "near") {
  4624. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4625. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4626. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4627. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4628. top = pos.top - node.offsetHeight;
  4629. else if (pos.bottom + node.offsetHeight <= vspace)
  4630. top = pos.bottom;
  4631. if (left + node.offsetWidth > hspace)
  4632. left = hspace - node.offsetWidth;
  4633. }
  4634. node.style.top = top + "px";
  4635. node.style.left = node.style.right = "";
  4636. if (horiz == "right") {
  4637. left = display.sizer.clientWidth - node.offsetWidth;
  4638. node.style.right = "0px";
  4639. } else {
  4640. if (horiz == "left") left = 0;
  4641. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4642. node.style.left = left + "px";
  4643. }
  4644. if (scroll)
  4645. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4646. },
  4647. triggerOnKeyDown: methodOp(onKeyDown),
  4648. triggerOnKeyPress: methodOp(onKeyPress),
  4649. triggerOnKeyUp: onKeyUp,
  4650. execCommand: function(cmd) {
  4651. if (commands.hasOwnProperty(cmd))
  4652. return commands[cmd].call(null, this);
  4653. },
  4654. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  4655. findPosH: function(from, amount, unit, visually) {
  4656. var dir = 1;
  4657. if (amount < 0) { dir = -1; amount = -amount; }
  4658. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4659. cur = findPosH(this.doc, cur, dir, unit, visually);
  4660. if (cur.hitSide) break;
  4661. }
  4662. return cur;
  4663. },
  4664. moveH: methodOp(function(dir, unit) {
  4665. var cm = this;
  4666. cm.extendSelectionsBy(function(range) {
  4667. if (cm.display.shift || cm.doc.extend || range.empty())
  4668. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4669. else
  4670. return dir < 0 ? range.from() : range.to();
  4671. }, sel_move);
  4672. }),
  4673. deleteH: methodOp(function(dir, unit) {
  4674. var sel = this.doc.sel, doc = this.doc;
  4675. if (sel.somethingSelected())
  4676. doc.replaceSelection("", null, "+delete");
  4677. else
  4678. deleteNearSelection(this, function(range) {
  4679. var other = findPosH(doc, range.head, dir, unit, false);
  4680. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4681. });
  4682. }),
  4683. findPosV: function(from, amount, unit, goalColumn) {
  4684. var dir = 1, x = goalColumn;
  4685. if (amount < 0) { dir = -1; amount = -amount; }
  4686. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4687. var coords = cursorCoords(this, cur, "div");
  4688. if (x == null) x = coords.left;
  4689. else coords.left = x;
  4690. cur = findPosV(this, coords, dir, unit);
  4691. if (cur.hitSide) break;
  4692. }
  4693. return cur;
  4694. },
  4695. moveV: methodOp(function(dir, unit) {
  4696. var cm = this, doc = this.doc, goals = [];
  4697. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4698. doc.extendSelectionsBy(function(range) {
  4699. if (collapse)
  4700. return dir < 0 ? range.from() : range.to();
  4701. var headPos = cursorCoords(cm, range.head, "div");
  4702. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4703. goals.push(headPos.left);
  4704. var pos = findPosV(cm, headPos, dir, unit);
  4705. if (unit == "page" && range == doc.sel.primary())
  4706. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4707. return pos;
  4708. }, sel_move);
  4709. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4710. doc.sel.ranges[i].goalColumn = goals[i];
  4711. }),
  4712. // Find the word at the given position (as returned by coordsChar).
  4713. findWordAt: function(pos) {
  4714. var doc = this.doc, line = getLine(doc, pos.line).text;
  4715. var start = pos.ch, end = pos.ch;
  4716. if (line) {
  4717. var helper = this.getHelper(pos, "wordChars");
  4718. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4719. var startChar = line.charAt(start);
  4720. var check = isWordChar(startChar, helper)
  4721. ? function(ch) { return isWordChar(ch, helper); }
  4722. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4723. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4724. while (start > 0 && check(line.charAt(start - 1))) --start;
  4725. while (end < line.length && check(line.charAt(end))) ++end;
  4726. }
  4727. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4728. },
  4729. toggleOverwrite: function(value) {
  4730. if (value != null && value == this.state.overwrite) return;
  4731. if (this.state.overwrite = !this.state.overwrite)
  4732. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4733. else
  4734. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4735. signal(this, "overwriteToggle", this, this.state.overwrite);
  4736. },
  4737. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  4738. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  4739. scrollTo: methodOp(function(x, y) {
  4740. if (x != null || y != null) resolveScrollToPos(this);
  4741. if (x != null) this.curOp.scrollLeft = x;
  4742. if (y != null) this.curOp.scrollTop = y;
  4743. }),
  4744. getScrollInfo: function() {
  4745. var scroller = this.display.scroller;
  4746. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4747. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4748. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4749. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4750. },
  4751. scrollIntoView: methodOp(function(range, margin) {
  4752. if (range == null) {
  4753. range = {from: this.doc.sel.primary().head, to: null};
  4754. if (margin == null) margin = this.options.cursorScrollMargin;
  4755. } else if (typeof range == "number") {
  4756. range = {from: Pos(range, 0), to: null};
  4757. } else if (range.from == null) {
  4758. range = {from: range, to: null};
  4759. }
  4760. if (!range.to) range.to = range.from;
  4761. range.margin = margin || 0;
  4762. if (range.from.line != null) {
  4763. resolveScrollToPos(this);
  4764. this.curOp.scrollToPos = range;
  4765. } else {
  4766. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4767. Math.min(range.from.top, range.to.top) - range.margin,
  4768. Math.max(range.from.right, range.to.right),
  4769. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4770. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4771. }
  4772. }),
  4773. setSize: methodOp(function(width, height) {
  4774. var cm = this;
  4775. function interpret(val) {
  4776. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4777. }
  4778. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4779. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4780. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4781. var lineNo = cm.display.viewFrom;
  4782. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4783. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4784. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4785. ++lineNo;
  4786. });
  4787. cm.curOp.forceUpdate = true;
  4788. signal(cm, "refresh", this);
  4789. }),
  4790. operation: function(f){return runInOp(this, f);},
  4791. refresh: methodOp(function() {
  4792. var oldHeight = this.display.cachedTextHeight;
  4793. regChange(this);
  4794. this.curOp.forceUpdate = true;
  4795. clearCaches(this);
  4796. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4797. updateGutterSpace(this);
  4798. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4799. estimateLineHeights(this);
  4800. signal(this, "refresh", this);
  4801. }),
  4802. swapDoc: methodOp(function(doc) {
  4803. var old = this.doc;
  4804. old.cm = null;
  4805. attachDoc(this, doc);
  4806. clearCaches(this);
  4807. this.display.input.reset();
  4808. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4809. this.curOp.forceScroll = true;
  4810. signalLater(this, "swapDoc", this, old);
  4811. return old;
  4812. }),
  4813. getInputField: function(){return this.display.input.getField();},
  4814. getWrapperElement: function(){return this.display.wrapper;},
  4815. getScrollerElement: function(){return this.display.scroller;},
  4816. getGutterElement: function(){return this.display.gutters;}
  4817. };
  4818. eventMixin(CodeMirror);
  4819. // OPTION DEFAULTS
  4820. // The default configuration options.
  4821. var defaults = CodeMirror.defaults = {};
  4822. // Functions to run when options are changed.
  4823. var optionHandlers = CodeMirror.optionHandlers = {};
  4824. function option(name, deflt, handle, notOnInit) {
  4825. CodeMirror.defaults[name] = deflt;
  4826. if (handle) optionHandlers[name] =
  4827. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4828. }
  4829. // Passed to option handlers when there is no old value.
  4830. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4831. // These two are, on init, called from the constructor because they
  4832. // have to be initialized before the editor can start at all.
  4833. option("value", "", function(cm, val) {
  4834. cm.setValue(val);
  4835. }, true);
  4836. option("mode", null, function(cm, val) {
  4837. cm.doc.modeOption = val;
  4838. loadMode(cm);
  4839. }, true);
  4840. option("indentUnit", 2, loadMode, true);
  4841. option("indentWithTabs", false);
  4842. option("smartIndent", true);
  4843. option("tabSize", 4, function(cm) {
  4844. resetModeState(cm);
  4845. clearCaches(cm);
  4846. regChange(cm);
  4847. }, true);
  4848. option("lineSeparator", null, function(cm, val) {
  4849. cm.doc.lineSep = val;
  4850. if (!val) return;
  4851. var newBreaks = [], lineNo = cm.doc.first;
  4852. cm.doc.iter(function(line) {
  4853. for (var pos = 0;;) {
  4854. var found = line.text.indexOf(val, pos);
  4855. if (found == -1) break;
  4856. pos = found + val.length;
  4857. newBreaks.push(Pos(lineNo, found));
  4858. }
  4859. lineNo++;
  4860. });
  4861. for (var i = newBreaks.length - 1; i >= 0; i--)
  4862. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  4863. });
  4864. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  4865. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4866. if (old != CodeMirror.Init) cm.refresh();
  4867. });
  4868. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4869. option("electricChars", true);
  4870. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  4871. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4872. }, true);
  4873. option("rtlMoveVisually", !windows);
  4874. option("wholeLineUpdateBefore", true);
  4875. option("theme", "default", function(cm) {
  4876. themeChanged(cm);
  4877. guttersChanged(cm);
  4878. }, true);
  4879. option("keyMap", "default", function(cm, val, old) {
  4880. var next = getKeyMap(val);
  4881. var prev = old != CodeMirror.Init && getKeyMap(old);
  4882. if (prev && prev.detach) prev.detach(cm, next);
  4883. if (next.attach) next.attach(cm, prev || null);
  4884. });
  4885. option("extraKeys", null);
  4886. option("lineWrapping", false, wrappingChanged, true);
  4887. option("gutters", [], function(cm) {
  4888. setGuttersForLineNumbers(cm.options);
  4889. guttersChanged(cm);
  4890. }, true);
  4891. option("fixedGutter", true, function(cm, val) {
  4892. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4893. cm.refresh();
  4894. }, true);
  4895. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4896. option("scrollbarStyle", "native", function(cm) {
  4897. initScrollbars(cm);
  4898. updateScrollbars(cm);
  4899. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4900. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4901. }, true);
  4902. option("lineNumbers", false, function(cm) {
  4903. setGuttersForLineNumbers(cm.options);
  4904. guttersChanged(cm);
  4905. }, true);
  4906. option("firstLineNumber", 1, guttersChanged, true);
  4907. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4908. option("showCursorWhenSelecting", false, updateSelection, true);
  4909. option("resetSelectionOnContextMenu", true);
  4910. option("lineWiseCopyCut", true);
  4911. option("readOnly", false, function(cm, val) {
  4912. if (val == "nocursor") {
  4913. onBlur(cm);
  4914. cm.display.input.blur();
  4915. cm.display.disabled = true;
  4916. } else {
  4917. cm.display.disabled = false;
  4918. }
  4919. cm.display.input.readOnlyChanged(val)
  4920. });
  4921. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  4922. option("dragDrop", true, dragDropChanged);
  4923. option("allowDropFileTypes", null);
  4924. option("cursorBlinkRate", 530);
  4925. option("cursorScrollMargin", 0);
  4926. option("cursorHeight", 1, updateSelection, true);
  4927. option("singleCursorHeightPerLine", true, updateSelection, true);
  4928. option("workTime", 100);
  4929. option("workDelay", 100);
  4930. option("flattenSpans", true, resetModeState, true);
  4931. option("addModeClass", false, resetModeState, true);
  4932. option("pollInterval", 100);
  4933. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4934. option("historyEventDelay", 1250);
  4935. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4936. option("maxHighlightLength", 10000, resetModeState, true);
  4937. option("moveInputWithCursor", true, function(cm, val) {
  4938. if (!val) cm.display.input.resetPosition();
  4939. });
  4940. option("tabindex", null, function(cm, val) {
  4941. cm.display.input.getField().tabIndex = val || "";
  4942. });
  4943. option("autofocus", null);
  4944. // MODE DEFINITION AND QUERYING
  4945. // Known modes, by name and by MIME
  4946. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4947. // Extra arguments are stored as the mode's dependencies, which is
  4948. // used by (legacy) mechanisms like loadmode.js to automatically
  4949. // load a mode. (Preferred mechanism is the require/define calls.)
  4950. CodeMirror.defineMode = function(name, mode) {
  4951. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4952. if (arguments.length > 2)
  4953. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4954. modes[name] = mode;
  4955. };
  4956. CodeMirror.defineMIME = function(mime, spec) {
  4957. mimeModes[mime] = spec;
  4958. };
  4959. // Given a MIME type, a {name, ...options} config object, or a name
  4960. // string, return a mode config object.
  4961. CodeMirror.resolveMode = function(spec) {
  4962. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4963. spec = mimeModes[spec];
  4964. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4965. var found = mimeModes[spec.name];
  4966. if (typeof found == "string") found = {name: found};
  4967. spec = createObj(found, spec);
  4968. spec.name = found.name;
  4969. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4970. return CodeMirror.resolveMode("application/xml");
  4971. }
  4972. if (typeof spec == "string") return {name: spec};
  4973. else return spec || {name: "null"};
  4974. };
  4975. // Given a mode spec (anything that resolveMode accepts), find and
  4976. // initialize an actual mode object.
  4977. CodeMirror.getMode = function(options, spec) {
  4978. var spec = CodeMirror.resolveMode(spec);
  4979. var mfactory = modes[spec.name];
  4980. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4981. var modeObj = mfactory(options, spec);
  4982. if (modeExtensions.hasOwnProperty(spec.name)) {
  4983. var exts = modeExtensions[spec.name];
  4984. for (var prop in exts) {
  4985. if (!exts.hasOwnProperty(prop)) continue;
  4986. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4987. modeObj[prop] = exts[prop];
  4988. }
  4989. }
  4990. modeObj.name = spec.name;
  4991. if (spec.helperType) modeObj.helperType = spec.helperType;
  4992. if (spec.modeProps) for (var prop in spec.modeProps)
  4993. modeObj[prop] = spec.modeProps[prop];
  4994. return modeObj;
  4995. };
  4996. // Minimal default mode.
  4997. CodeMirror.defineMode("null", function() {
  4998. return {token: function(stream) {stream.skipToEnd();}};
  4999. });
  5000. CodeMirror.defineMIME("text/plain", "null");
  5001. // This can be used to attach properties to mode objects from
  5002. // outside the actual mode definition.
  5003. var modeExtensions = CodeMirror.modeExtensions = {};
  5004. CodeMirror.extendMode = function(mode, properties) {
  5005. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  5006. copyObj(properties, exts);
  5007. };
  5008. // EXTENSIONS
  5009. CodeMirror.defineExtension = function(name, func) {
  5010. CodeMirror.prototype[name] = func;
  5011. };
  5012. CodeMirror.defineDocExtension = function(name, func) {
  5013. Doc.prototype[name] = func;
  5014. };
  5015. CodeMirror.defineOption = option;
  5016. var initHooks = [];
  5017. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  5018. var helpers = CodeMirror.helpers = {};
  5019. CodeMirror.registerHelper = function(type, name, value) {
  5020. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  5021. helpers[type][name] = value;
  5022. };
  5023. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  5024. CodeMirror.registerHelper(type, name, value);
  5025. helpers[type]._global.push({pred: predicate, val: value});
  5026. };
  5027. // MODE STATE HANDLING
  5028. // Utility functions for working with state. Exported because nested
  5029. // modes need to do this for their inner modes.
  5030. var copyState = CodeMirror.copyState = function(mode, state) {
  5031. if (state === true) return state;
  5032. if (mode.copyState) return mode.copyState(state);
  5033. var nstate = {};
  5034. for (var n in state) {
  5035. var val = state[n];
  5036. if (val instanceof Array) val = val.concat([]);
  5037. nstate[n] = val;
  5038. }
  5039. return nstate;
  5040. };
  5041. var startState = CodeMirror.startState = function(mode, a1, a2) {
  5042. return mode.startState ? mode.startState(a1, a2) : true;
  5043. };
  5044. // Given a mode and a state (for that mode), find the inner mode and
  5045. // state at the position that the state refers to.
  5046. CodeMirror.innerMode = function(mode, state) {
  5047. while (mode.innerMode) {
  5048. var info = mode.innerMode(state);
  5049. if (!info || info.mode == mode) break;
  5050. state = info.state;
  5051. mode = info.mode;
  5052. }
  5053. return info || {mode: mode, state: state};
  5054. };
  5055. // STANDARD COMMANDS
  5056. // Commands are parameter-less actions that can be performed on an
  5057. // editor, mostly used for keybindings.
  5058. var commands = CodeMirror.commands = {
  5059. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  5060. singleSelection: function(cm) {
  5061. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  5062. },
  5063. killLine: function(cm) {
  5064. deleteNearSelection(cm, function(range) {
  5065. if (range.empty()) {
  5066. var len = getLine(cm.doc, range.head.line).text.length;
  5067. if (range.head.ch == len && range.head.line < cm.lastLine())
  5068. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  5069. else
  5070. return {from: range.head, to: Pos(range.head.line, len)};
  5071. } else {
  5072. return {from: range.from(), to: range.to()};
  5073. }
  5074. });
  5075. },
  5076. deleteLine: function(cm) {
  5077. deleteNearSelection(cm, function(range) {
  5078. return {from: Pos(range.from().line, 0),
  5079. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  5080. });
  5081. },
  5082. delLineLeft: function(cm) {
  5083. deleteNearSelection(cm, function(range) {
  5084. return {from: Pos(range.from().line, 0), to: range.from()};
  5085. });
  5086. },
  5087. delWrappedLineLeft: function(cm) {
  5088. deleteNearSelection(cm, function(range) {
  5089. var top = cm.charCoords(range.head, "div").top + 5;
  5090. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  5091. return {from: leftPos, to: range.from()};
  5092. });
  5093. },
  5094. delWrappedLineRight: function(cm) {
  5095. deleteNearSelection(cm, function(range) {
  5096. var top = cm.charCoords(range.head, "div").top + 5;
  5097. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5098. return {from: range.from(), to: rightPos };
  5099. });
  5100. },
  5101. undo: function(cm) {cm.undo();},
  5102. redo: function(cm) {cm.redo();},
  5103. undoSelection: function(cm) {cm.undoSelection();},
  5104. redoSelection: function(cm) {cm.redoSelection();},
  5105. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  5106. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  5107. goLineStart: function(cm) {
  5108. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  5109. {origin: "+move", bias: 1});
  5110. },
  5111. goLineStartSmart: function(cm) {
  5112. cm.extendSelectionsBy(function(range) {
  5113. return lineStartSmart(cm, range.head);
  5114. }, {origin: "+move", bias: 1});
  5115. },
  5116. goLineEnd: function(cm) {
  5117. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  5118. {origin: "+move", bias: -1});
  5119. },
  5120. goLineRight: function(cm) {
  5121. cm.extendSelectionsBy(function(range) {
  5122. var top = cm.charCoords(range.head, "div").top + 5;
  5123. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5124. }, sel_move);
  5125. },
  5126. goLineLeft: function(cm) {
  5127. cm.extendSelectionsBy(function(range) {
  5128. var top = cm.charCoords(range.head, "div").top + 5;
  5129. return cm.coordsChar({left: 0, top: top}, "div");
  5130. }, sel_move);
  5131. },
  5132. goLineLeftSmart: function(cm) {
  5133. cm.extendSelectionsBy(function(range) {
  5134. var top = cm.charCoords(range.head, "div").top + 5;
  5135. var pos = cm.coordsChar({left: 0, top: top}, "div");
  5136. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  5137. return pos;
  5138. }, sel_move);
  5139. },
  5140. goLineUp: function(cm) {cm.moveV(-1, "line");},
  5141. goLineDown: function(cm) {cm.moveV(1, "line");},
  5142. goPageUp: function(cm) {cm.moveV(-1, "page");},
  5143. goPageDown: function(cm) {cm.moveV(1, "page");},
  5144. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  5145. goCharRight: function(cm) {cm.moveH(1, "char");},
  5146. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  5147. goColumnRight: function(cm) {cm.moveH(1, "column");},
  5148. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  5149. goGroupRight: function(cm) {cm.moveH(1, "group");},
  5150. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  5151. goWordRight: function(cm) {cm.moveH(1, "word");},
  5152. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  5153. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  5154. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  5155. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  5156. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  5157. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  5158. indentAuto: function(cm) {cm.indentSelection("smart");},
  5159. indentMore: function(cm) {cm.indentSelection("add");},
  5160. indentLess: function(cm) {cm.indentSelection("subtract");},
  5161. insertTab: function(cm) {cm.replaceSelection("\t");},
  5162. insertSoftTab: function(cm) {
  5163. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  5164. for (var i = 0; i < ranges.length; i++) {
  5165. var pos = ranges[i].from();
  5166. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  5167. spaces.push(spaceStr(tabSize - col % tabSize));
  5168. }
  5169. cm.replaceSelections(spaces);
  5170. },
  5171. defaultTab: function(cm) {
  5172. if (cm.somethingSelected()) cm.indentSelection("add");
  5173. else cm.execCommand("insertTab");
  5174. },
  5175. transposeChars: function(cm) {
  5176. runInOp(cm, function() {
  5177. var ranges = cm.listSelections(), newSel = [];
  5178. for (var i = 0; i < ranges.length; i++) {
  5179. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  5180. if (line) {
  5181. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  5182. if (cur.ch > 0) {
  5183. cur = new Pos(cur.line, cur.ch + 1);
  5184. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5185. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  5186. } else if (cur.line > cm.doc.first) {
  5187. var prev = getLine(cm.doc, cur.line - 1).text;
  5188. if (prev)
  5189. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  5190. prev.charAt(prev.length - 1),
  5191. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  5192. }
  5193. }
  5194. newSel.push(new Range(cur, cur));
  5195. }
  5196. cm.setSelections(newSel);
  5197. });
  5198. },
  5199. newlineAndIndent: function(cm) {
  5200. runInOp(cm, function() {
  5201. var len = cm.listSelections().length;
  5202. for (var i = 0; i < len; i++) {
  5203. var range = cm.listSelections()[i];
  5204. cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
  5205. cm.indentLine(range.from().line + 1, null, true);
  5206. }
  5207. ensureCursorVisible(cm);
  5208. });
  5209. },
  5210. openLine: function(cm) {cm.replaceSelection("\n", "start")},
  5211. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  5212. };
  5213. // STANDARD KEYMAPS
  5214. var keyMap = CodeMirror.keyMap = {};
  5215. keyMap.basic = {
  5216. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5217. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5218. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5219. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5220. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5221. "Esc": "singleSelection"
  5222. };
  5223. // Note that the save and find-related commands aren't defined by
  5224. // default. User code or addons can define them. Unknown commands
  5225. // are simply ignored.
  5226. keyMap.pcDefault = {
  5227. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5228. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5229. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5230. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5231. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5232. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5233. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5234. fallthrough: "basic"
  5235. };
  5236. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5237. keyMap.emacsy = {
  5238. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5239. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5240. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5241. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5242. "Ctrl-O": "openLine"
  5243. };
  5244. keyMap.macDefault = {
  5245. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5246. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5247. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5248. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5249. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5250. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5251. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5252. fallthrough: ["basic", "emacsy"]
  5253. };
  5254. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5255. // KEYMAP DISPATCH
  5256. function normalizeKeyName(name) {
  5257. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5258. var alt, ctrl, shift, cmd;
  5259. for (var i = 0; i < parts.length - 1; i++) {
  5260. var mod = parts[i];
  5261. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5262. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5263. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5264. else if (/^s(hift)$/i.test(mod)) shift = true;
  5265. else throw new Error("Unrecognized modifier name: " + mod);
  5266. }
  5267. if (alt) name = "Alt-" + name;
  5268. if (ctrl) name = "Ctrl-" + name;
  5269. if (cmd) name = "Cmd-" + name;
  5270. if (shift) name = "Shift-" + name;
  5271. return name;
  5272. }
  5273. // This is a kludge to keep keymaps mostly working as raw objects
  5274. // (backwards compatibility) while at the same time support features
  5275. // like normalization and multi-stroke key bindings. It compiles a
  5276. // new normalized keymap, and then updates the old object to reflect
  5277. // this.
  5278. CodeMirror.normalizeKeyMap = function(keymap) {
  5279. var copy = {};
  5280. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5281. var value = keymap[keyname];
  5282. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5283. if (value == "...") { delete keymap[keyname]; continue; }
  5284. var keys = map(keyname.split(" "), normalizeKeyName);
  5285. for (var i = 0; i < keys.length; i++) {
  5286. var val, name;
  5287. if (i == keys.length - 1) {
  5288. name = keys.join(" ");
  5289. val = value;
  5290. } else {
  5291. name = keys.slice(0, i + 1).join(" ");
  5292. val = "...";
  5293. }
  5294. var prev = copy[name];
  5295. if (!prev) copy[name] = val;
  5296. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5297. }
  5298. delete keymap[keyname];
  5299. }
  5300. for (var prop in copy) keymap[prop] = copy[prop];
  5301. return keymap;
  5302. };
  5303. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  5304. map = getKeyMap(map);
  5305. var found = map.call ? map.call(key, context) : map[key];
  5306. if (found === false) return "nothing";
  5307. if (found === "...") return "multi";
  5308. if (found != null && handle(found)) return "handled";
  5309. if (map.fallthrough) {
  5310. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5311. return lookupKey(key, map.fallthrough, handle, context);
  5312. for (var i = 0; i < map.fallthrough.length; i++) {
  5313. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5314. if (result) return result;
  5315. }
  5316. }
  5317. };
  5318. // Modifier key presses don't count as 'real' key presses for the
  5319. // purpose of keymap fallthrough.
  5320. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  5321. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5322. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5323. };
  5324. // Look up the name of a key as indicated by an event object.
  5325. var keyName = CodeMirror.keyName = function(event, noShift) {
  5326. if (presto && event.keyCode == 34 && event["char"]) return false;
  5327. var base = keyNames[event.keyCode], name = base;
  5328. if (name == null || event.altGraphKey) return false;
  5329. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5330. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5331. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5332. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5333. return name;
  5334. };
  5335. function getKeyMap(val) {
  5336. return typeof val == "string" ? keyMap[val] : val;
  5337. }
  5338. // FROMTEXTAREA
  5339. CodeMirror.fromTextArea = function(textarea, options) {
  5340. options = options ? copyObj(options) : {};
  5341. options.value = textarea.value;
  5342. if (!options.tabindex && textarea.tabIndex)
  5343. options.tabindex = textarea.tabIndex;
  5344. if (!options.placeholder && textarea.placeholder)
  5345. options.placeholder = textarea.placeholder;
  5346. // Set autofocus to true if this textarea is focused, or if it has
  5347. // autofocus and no other element is focused.
  5348. if (options.autofocus == null) {
  5349. var hasFocus = activeElt();
  5350. options.autofocus = hasFocus == textarea ||
  5351. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5352. }
  5353. function save() {textarea.value = cm.getValue();}
  5354. if (textarea.form) {
  5355. on(textarea.form, "submit", save);
  5356. // Deplorable hack to make the submit method do the right thing.
  5357. if (!options.leaveSubmitMethodAlone) {
  5358. var form = textarea.form, realSubmit = form.submit;
  5359. try {
  5360. var wrappedSubmit = form.submit = function() {
  5361. save();
  5362. form.submit = realSubmit;
  5363. form.submit();
  5364. form.submit = wrappedSubmit;
  5365. };
  5366. } catch(e) {}
  5367. }
  5368. }
  5369. options.finishInit = function(cm) {
  5370. cm.save = save;
  5371. cm.getTextArea = function() { return textarea; };
  5372. cm.toTextArea = function() {
  5373. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5374. save();
  5375. textarea.parentNode.removeChild(cm.getWrapperElement());
  5376. textarea.style.display = "";
  5377. if (textarea.form) {
  5378. off(textarea.form, "submit", save);
  5379. if (typeof textarea.form.submit == "function")
  5380. textarea.form.submit = realSubmit;
  5381. }
  5382. };
  5383. };
  5384. textarea.style.display = "none";
  5385. var cm = CodeMirror(function(node) {
  5386. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5387. }, options);
  5388. return cm;
  5389. };
  5390. // STRING STREAM
  5391. // Fed to the mode parsers, provides helper functions to make
  5392. // parsers more succinct.
  5393. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  5394. this.pos = this.start = 0;
  5395. this.string = string;
  5396. this.tabSize = tabSize || 8;
  5397. this.lastColumnPos = this.lastColumnValue = 0;
  5398. this.lineStart = 0;
  5399. };
  5400. StringStream.prototype = {
  5401. eol: function() {return this.pos >= this.string.length;},
  5402. sol: function() {return this.pos == this.lineStart;},
  5403. peek: function() {return this.string.charAt(this.pos) || undefined;},
  5404. next: function() {
  5405. if (this.pos < this.string.length)
  5406. return this.string.charAt(this.pos++);
  5407. },
  5408. eat: function(match) {
  5409. var ch = this.string.charAt(this.pos);
  5410. if (typeof match == "string") var ok = ch == match;
  5411. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5412. if (ok) {++this.pos; return ch;}
  5413. },
  5414. eatWhile: function(match) {
  5415. var start = this.pos;
  5416. while (this.eat(match)){}
  5417. return this.pos > start;
  5418. },
  5419. eatSpace: function() {
  5420. var start = this.pos;
  5421. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  5422. return this.pos > start;
  5423. },
  5424. skipToEnd: function() {this.pos = this.string.length;},
  5425. skipTo: function(ch) {
  5426. var found = this.string.indexOf(ch, this.pos);
  5427. if (found > -1) {this.pos = found; return true;}
  5428. },
  5429. backUp: function(n) {this.pos -= n;},
  5430. column: function() {
  5431. if (this.lastColumnPos < this.start) {
  5432. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5433. this.lastColumnPos = this.start;
  5434. }
  5435. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5436. },
  5437. indentation: function() {
  5438. return countColumn(this.string, null, this.tabSize) -
  5439. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5440. },
  5441. match: function(pattern, consume, caseInsensitive) {
  5442. if (typeof pattern == "string") {
  5443. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  5444. var substr = this.string.substr(this.pos, pattern.length);
  5445. if (cased(substr) == cased(pattern)) {
  5446. if (consume !== false) this.pos += pattern.length;
  5447. return true;
  5448. }
  5449. } else {
  5450. var match = this.string.slice(this.pos).match(pattern);
  5451. if (match && match.index > 0) return null;
  5452. if (match && consume !== false) this.pos += match[0].length;
  5453. return match;
  5454. }
  5455. },
  5456. current: function(){return this.string.slice(this.start, this.pos);},
  5457. hideFirstChars: function(n, inner) {
  5458. this.lineStart += n;
  5459. try { return inner(); }
  5460. finally { this.lineStart -= n; }
  5461. }
  5462. };
  5463. // TEXTMARKERS
  5464. // Created with markText and setBookmark methods. A TextMarker is a
  5465. // handle that can be used to clear or find a marked position in the
  5466. // document. Line objects hold arrays (markedSpans) containing
  5467. // {from, to, marker} object pointing to such marker objects, and
  5468. // indicating that such a marker is present on that line. Multiple
  5469. // lines may point to the same marker when it spans across lines.
  5470. // The spans will have null for their from/to properties when the
  5471. // marker continues beyond the start/end of the line. Markers have
  5472. // links back to the lines they currently touch.
  5473. var nextMarkerId = 0;
  5474. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  5475. this.lines = [];
  5476. this.type = type;
  5477. this.doc = doc;
  5478. this.id = ++nextMarkerId;
  5479. };
  5480. eventMixin(TextMarker);
  5481. // Clear the marker.
  5482. TextMarker.prototype.clear = function() {
  5483. if (this.explicitlyCleared) return;
  5484. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5485. if (withOp) startOperation(cm);
  5486. if (hasHandler(this, "clear")) {
  5487. var found = this.find();
  5488. if (found) signalLater(this, "clear", found.from, found.to);
  5489. }
  5490. var min = null, max = null;
  5491. for (var i = 0; i < this.lines.length; ++i) {
  5492. var line = this.lines[i];
  5493. var span = getMarkedSpanFor(line.markedSpans, this);
  5494. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5495. else if (cm) {
  5496. if (span.to != null) max = lineNo(line);
  5497. if (span.from != null) min = lineNo(line);
  5498. }
  5499. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5500. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5501. updateLineHeight(line, textHeight(cm.display));
  5502. }
  5503. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5504. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5505. if (len > cm.display.maxLineLength) {
  5506. cm.display.maxLine = visual;
  5507. cm.display.maxLineLength = len;
  5508. cm.display.maxLineChanged = true;
  5509. }
  5510. }
  5511. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5512. this.lines.length = 0;
  5513. this.explicitlyCleared = true;
  5514. if (this.atomic && this.doc.cantEdit) {
  5515. this.doc.cantEdit = false;
  5516. if (cm) reCheckSelection(cm.doc);
  5517. }
  5518. if (cm) signalLater(cm, "markerCleared", cm, this);
  5519. if (withOp) endOperation(cm);
  5520. if (this.parent) this.parent.clear();
  5521. };
  5522. // Find the position of the marker in the document. Returns a {from,
  5523. // to} object by default. Side can be passed to get a specific side
  5524. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5525. // Pos objects returned contain a line object, rather than a line
  5526. // number (used to prevent looking up the same line twice).
  5527. TextMarker.prototype.find = function(side, lineObj) {
  5528. if (side == null && this.type == "bookmark") side = 1;
  5529. var from, to;
  5530. for (var i = 0; i < this.lines.length; ++i) {
  5531. var line = this.lines[i];
  5532. var span = getMarkedSpanFor(line.markedSpans, this);
  5533. if (span.from != null) {
  5534. from = Pos(lineObj ? line : lineNo(line), span.from);
  5535. if (side == -1) return from;
  5536. }
  5537. if (span.to != null) {
  5538. to = Pos(lineObj ? line : lineNo(line), span.to);
  5539. if (side == 1) return to;
  5540. }
  5541. }
  5542. return from && {from: from, to: to};
  5543. };
  5544. // Signals that the marker's widget changed, and surrounding layout
  5545. // should be recomputed.
  5546. TextMarker.prototype.changed = function() {
  5547. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5548. if (!pos || !cm) return;
  5549. runInOp(cm, function() {
  5550. var line = pos.line, lineN = lineNo(pos.line);
  5551. var view = findViewForLine(cm, lineN);
  5552. if (view) {
  5553. clearLineMeasurementCacheFor(view);
  5554. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5555. }
  5556. cm.curOp.updateMaxLine = true;
  5557. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5558. var oldHeight = widget.height;
  5559. widget.height = null;
  5560. var dHeight = widgetHeight(widget) - oldHeight;
  5561. if (dHeight)
  5562. updateLineHeight(line, line.height + dHeight);
  5563. }
  5564. });
  5565. };
  5566. TextMarker.prototype.attachLine = function(line) {
  5567. if (!this.lines.length && this.doc.cm) {
  5568. var op = this.doc.cm.curOp;
  5569. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5570. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5571. }
  5572. this.lines.push(line);
  5573. };
  5574. TextMarker.prototype.detachLine = function(line) {
  5575. this.lines.splice(indexOf(this.lines, line), 1);
  5576. if (!this.lines.length && this.doc.cm) {
  5577. var op = this.doc.cm.curOp;
  5578. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5579. }
  5580. };
  5581. // Collapsed markers have unique ids, in order to be able to order
  5582. // them, which is needed for uniquely determining an outer marker
  5583. // when they overlap (they may nest, but not partially overlap).
  5584. var nextMarkerId = 0;
  5585. // Create a marker, wire it up to the right lines, and
  5586. function markText(doc, from, to, options, type) {
  5587. // Shared markers (across linked documents) are handled separately
  5588. // (markTextShared will call out to this again, once per
  5589. // document).
  5590. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5591. // Ensure we are in an operation.
  5592. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5593. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5594. if (options) copyObj(options, marker, false);
  5595. // Don't connect empty markers unless clearWhenEmpty is false
  5596. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5597. return marker;
  5598. if (marker.replacedWith) {
  5599. // Showing up as a widget implies collapsed (widget replaces text)
  5600. marker.collapsed = true;
  5601. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5602. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5603. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5604. }
  5605. if (marker.collapsed) {
  5606. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5607. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5608. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5609. sawCollapsedSpans = true;
  5610. }
  5611. if (marker.addToHistory)
  5612. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  5613. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5614. doc.iter(curLine, to.line + 1, function(line) {
  5615. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5616. updateMaxLine = true;
  5617. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5618. addMarkedSpan(line, new MarkedSpan(marker,
  5619. curLine == from.line ? from.ch : null,
  5620. curLine == to.line ? to.ch : null));
  5621. ++curLine;
  5622. });
  5623. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5624. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  5625. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5626. });
  5627. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  5628. if (marker.readOnly) {
  5629. sawReadOnlySpans = true;
  5630. if (doc.history.done.length || doc.history.undone.length)
  5631. doc.clearHistory();
  5632. }
  5633. if (marker.collapsed) {
  5634. marker.id = ++nextMarkerId;
  5635. marker.atomic = true;
  5636. }
  5637. if (cm) {
  5638. // Sync editor state
  5639. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5640. if (marker.collapsed)
  5641. regChange(cm, from.line, to.line + 1);
  5642. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5643. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5644. if (marker.atomic) reCheckSelection(cm.doc);
  5645. signalLater(cm, "markerAdded", cm, marker);
  5646. }
  5647. return marker;
  5648. }
  5649. // SHARED TEXTMARKERS
  5650. // A shared marker spans multiple linked documents. It is
  5651. // implemented as a meta-marker-object controlling multiple normal
  5652. // markers.
  5653. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  5654. this.markers = markers;
  5655. this.primary = primary;
  5656. for (var i = 0; i < markers.length; ++i)
  5657. markers[i].parent = this;
  5658. };
  5659. eventMixin(SharedTextMarker);
  5660. SharedTextMarker.prototype.clear = function() {
  5661. if (this.explicitlyCleared) return;
  5662. this.explicitlyCleared = true;
  5663. for (var i = 0; i < this.markers.length; ++i)
  5664. this.markers[i].clear();
  5665. signalLater(this, "clear");
  5666. };
  5667. SharedTextMarker.prototype.find = function(side, lineObj) {
  5668. return this.primary.find(side, lineObj);
  5669. };
  5670. function markTextShared(doc, from, to, options, type) {
  5671. options = copyObj(options);
  5672. options.shared = false;
  5673. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5674. var widget = options.widgetNode;
  5675. linkedDocs(doc, function(doc) {
  5676. if (widget) options.widgetNode = widget.cloneNode(true);
  5677. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5678. for (var i = 0; i < doc.linked.length; ++i)
  5679. if (doc.linked[i].isParent) return;
  5680. primary = lst(markers);
  5681. });
  5682. return new SharedTextMarker(markers, primary);
  5683. }
  5684. function findSharedMarkers(doc) {
  5685. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5686. function(m) { return m.parent; });
  5687. }
  5688. function copySharedMarkers(doc, markers) {
  5689. for (var i = 0; i < markers.length; i++) {
  5690. var marker = markers[i], pos = marker.find();
  5691. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5692. if (cmp(mFrom, mTo)) {
  5693. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5694. marker.markers.push(subMark);
  5695. subMark.parent = marker;
  5696. }
  5697. }
  5698. }
  5699. function detachSharedMarkers(markers) {
  5700. for (var i = 0; i < markers.length; i++) {
  5701. var marker = markers[i], linked = [marker.primary.doc];;
  5702. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5703. for (var j = 0; j < marker.markers.length; j++) {
  5704. var subMarker = marker.markers[j];
  5705. if (indexOf(linked, subMarker.doc) == -1) {
  5706. subMarker.parent = null;
  5707. marker.markers.splice(j--, 1);
  5708. }
  5709. }
  5710. }
  5711. }
  5712. // TEXTMARKER SPANS
  5713. function MarkedSpan(marker, from, to) {
  5714. this.marker = marker;
  5715. this.from = from; this.to = to;
  5716. }
  5717. // Search an array of spans for a span matching the given marker.
  5718. function getMarkedSpanFor(spans, marker) {
  5719. if (spans) for (var i = 0; i < spans.length; ++i) {
  5720. var span = spans[i];
  5721. if (span.marker == marker) return span;
  5722. }
  5723. }
  5724. // Remove a span from an array, returning undefined if no spans are
  5725. // left (we don't store arrays for lines without spans).
  5726. function removeMarkedSpan(spans, span) {
  5727. for (var r, i = 0; i < spans.length; ++i)
  5728. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5729. return r;
  5730. }
  5731. // Add a span to a line.
  5732. function addMarkedSpan(line, span) {
  5733. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5734. span.marker.attachLine(line);
  5735. }
  5736. // Used for the algorithm that adjusts markers for a change in the
  5737. // document. These functions cut an array of spans at a given
  5738. // character position, returning an array of remaining chunks (or
  5739. // undefined if nothing remains).
  5740. function markedSpansBefore(old, startCh, isInsert) {
  5741. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5742. var span = old[i], marker = span.marker;
  5743. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5744. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5745. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5746. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5747. }
  5748. }
  5749. return nw;
  5750. }
  5751. function markedSpansAfter(old, endCh, isInsert) {
  5752. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5753. var span = old[i], marker = span.marker;
  5754. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5755. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5756. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5757. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5758. span.to == null ? null : span.to - endCh));
  5759. }
  5760. }
  5761. return nw;
  5762. }
  5763. // Given a change object, compute the new set of marker spans that
  5764. // cover the line in which the change took place. Removes spans
  5765. // entirely within the change, reconnects spans belonging to the
  5766. // same marker that appear on both sides of the change, and cuts off
  5767. // spans partially within the change. Returns an array of span
  5768. // arrays with one element for each line in (after) the change.
  5769. function stretchSpansOverChange(doc, change) {
  5770. if (change.full) return null;
  5771. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5772. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5773. if (!oldFirst && !oldLast) return null;
  5774. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5775. // Get the spans that 'stick out' on both sides
  5776. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5777. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5778. // Next, merge those two ends
  5779. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5780. if (first) {
  5781. // Fix up .to properties of first
  5782. for (var i = 0; i < first.length; ++i) {
  5783. var span = first[i];
  5784. if (span.to == null) {
  5785. var found = getMarkedSpanFor(last, span.marker);
  5786. if (!found) span.to = startCh;
  5787. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5788. }
  5789. }
  5790. }
  5791. if (last) {
  5792. // Fix up .from in last (or move them into first in case of sameLine)
  5793. for (var i = 0; i < last.length; ++i) {
  5794. var span = last[i];
  5795. if (span.to != null) span.to += offset;
  5796. if (span.from == null) {
  5797. var found = getMarkedSpanFor(first, span.marker);
  5798. if (!found) {
  5799. span.from = offset;
  5800. if (sameLine) (first || (first = [])).push(span);
  5801. }
  5802. } else {
  5803. span.from += offset;
  5804. if (sameLine) (first || (first = [])).push(span);
  5805. }
  5806. }
  5807. }
  5808. // Make sure we didn't create any zero-length spans
  5809. if (first) first = clearEmptySpans(first);
  5810. if (last && last != first) last = clearEmptySpans(last);
  5811. var newMarkers = [first];
  5812. if (!sameLine) {
  5813. // Fill gap with whole-line-spans
  5814. var gap = change.text.length - 2, gapMarkers;
  5815. if (gap > 0 && first)
  5816. for (var i = 0; i < first.length; ++i)
  5817. if (first[i].to == null)
  5818. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5819. for (var i = 0; i < gap; ++i)
  5820. newMarkers.push(gapMarkers);
  5821. newMarkers.push(last);
  5822. }
  5823. return newMarkers;
  5824. }
  5825. // Remove spans that are empty and don't have a clearWhenEmpty
  5826. // option of false.
  5827. function clearEmptySpans(spans) {
  5828. for (var i = 0; i < spans.length; ++i) {
  5829. var span = spans[i];
  5830. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5831. spans.splice(i--, 1);
  5832. }
  5833. if (!spans.length) return null;
  5834. return spans;
  5835. }
  5836. // Used for un/re-doing changes from the history. Combines the
  5837. // result of computing the existing spans with the set of spans that
  5838. // existed in the history (so that deleting around a span and then
  5839. // undoing brings back the span).
  5840. function mergeOldSpans(doc, change) {
  5841. var old = getOldSpans(doc, change);
  5842. var stretched = stretchSpansOverChange(doc, change);
  5843. if (!old) return stretched;
  5844. if (!stretched) return old;
  5845. for (var i = 0; i < old.length; ++i) {
  5846. var oldCur = old[i], stretchCur = stretched[i];
  5847. if (oldCur && stretchCur) {
  5848. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5849. var span = stretchCur[j];
  5850. for (var k = 0; k < oldCur.length; ++k)
  5851. if (oldCur[k].marker == span.marker) continue spans;
  5852. oldCur.push(span);
  5853. }
  5854. } else if (stretchCur) {
  5855. old[i] = stretchCur;
  5856. }
  5857. }
  5858. return old;
  5859. }
  5860. // Used to 'clip' out readOnly ranges when making a change.
  5861. function removeReadOnlyRanges(doc, from, to) {
  5862. var markers = null;
  5863. doc.iter(from.line, to.line + 1, function(line) {
  5864. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5865. var mark = line.markedSpans[i].marker;
  5866. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5867. (markers || (markers = [])).push(mark);
  5868. }
  5869. });
  5870. if (!markers) return null;
  5871. var parts = [{from: from, to: to}];
  5872. for (var i = 0; i < markers.length; ++i) {
  5873. var mk = markers[i], m = mk.find(0);
  5874. for (var j = 0; j < parts.length; ++j) {
  5875. var p = parts[j];
  5876. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5877. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5878. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5879. newParts.push({from: p.from, to: m.from});
  5880. if (dto > 0 || !mk.inclusiveRight && !dto)
  5881. newParts.push({from: m.to, to: p.to});
  5882. parts.splice.apply(parts, newParts);
  5883. j += newParts.length - 1;
  5884. }
  5885. }
  5886. return parts;
  5887. }
  5888. // Connect or disconnect spans from a line.
  5889. function detachMarkedSpans(line) {
  5890. var spans = line.markedSpans;
  5891. if (!spans) return;
  5892. for (var i = 0; i < spans.length; ++i)
  5893. spans[i].marker.detachLine(line);
  5894. line.markedSpans = null;
  5895. }
  5896. function attachMarkedSpans(line, spans) {
  5897. if (!spans) return;
  5898. for (var i = 0; i < spans.length; ++i)
  5899. spans[i].marker.attachLine(line);
  5900. line.markedSpans = spans;
  5901. }
  5902. // Helpers used when computing which overlapping collapsed span
  5903. // counts as the larger one.
  5904. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5905. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5906. // Returns a number indicating which of two overlapping collapsed
  5907. // spans is larger (and thus includes the other). Falls back to
  5908. // comparing ids when the spans cover exactly the same range.
  5909. function compareCollapsedMarkers(a, b) {
  5910. var lenDiff = a.lines.length - b.lines.length;
  5911. if (lenDiff != 0) return lenDiff;
  5912. var aPos = a.find(), bPos = b.find();
  5913. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5914. if (fromCmp) return -fromCmp;
  5915. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5916. if (toCmp) return toCmp;
  5917. return b.id - a.id;
  5918. }
  5919. // Find out whether a line ends or starts in a collapsed span. If
  5920. // so, return the marker for that span.
  5921. function collapsedSpanAtSide(line, start) {
  5922. var sps = sawCollapsedSpans && line.markedSpans, found;
  5923. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5924. sp = sps[i];
  5925. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5926. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5927. found = sp.marker;
  5928. }
  5929. return found;
  5930. }
  5931. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5932. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5933. // Test whether there exists a collapsed span that partially
  5934. // overlaps (covers the start or end, but not both) of a new span.
  5935. // Such overlap is not allowed.
  5936. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5937. var line = getLine(doc, lineNo);
  5938. var sps = sawCollapsedSpans && line.markedSpans;
  5939. if (sps) for (var i = 0; i < sps.length; ++i) {
  5940. var sp = sps[i];
  5941. if (!sp.marker.collapsed) continue;
  5942. var found = sp.marker.find(0);
  5943. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5944. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5945. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5946. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  5947. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  5948. return true;
  5949. }
  5950. }
  5951. // A visual line is a line as drawn on the screen. Folding, for
  5952. // example, can cause multiple logical lines to appear on the same
  5953. // visual line. This finds the start of the visual line that the
  5954. // given line is part of (usually that is the line itself).
  5955. function visualLine(line) {
  5956. var merged;
  5957. while (merged = collapsedSpanAtStart(line))
  5958. line = merged.find(-1, true).line;
  5959. return line;
  5960. }
  5961. // Returns an array of logical lines that continue the visual line
  5962. // started by the argument, or undefined if there are no such lines.
  5963. function visualLineContinued(line) {
  5964. var merged, lines;
  5965. while (merged = collapsedSpanAtEnd(line)) {
  5966. line = merged.find(1, true).line;
  5967. (lines || (lines = [])).push(line);
  5968. }
  5969. return lines;
  5970. }
  5971. // Get the line number of the start of the visual line that the
  5972. // given line number is part of.
  5973. function visualLineNo(doc, lineN) {
  5974. var line = getLine(doc, lineN), vis = visualLine(line);
  5975. if (line == vis) return lineN;
  5976. return lineNo(vis);
  5977. }
  5978. // Get the line number of the start of the next visual line after
  5979. // the given line.
  5980. function visualLineEndNo(doc, lineN) {
  5981. if (lineN > doc.lastLine()) return lineN;
  5982. var line = getLine(doc, lineN), merged;
  5983. if (!lineIsHidden(doc, line)) return lineN;
  5984. while (merged = collapsedSpanAtEnd(line))
  5985. line = merged.find(1, true).line;
  5986. return lineNo(line) + 1;
  5987. }
  5988. // Compute whether a line is hidden. Lines count as hidden when they
  5989. // are part of a visual line that starts with another line, or when
  5990. // they are entirely covered by collapsed, non-widget span.
  5991. function lineIsHidden(doc, line) {
  5992. var sps = sawCollapsedSpans && line.markedSpans;
  5993. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5994. sp = sps[i];
  5995. if (!sp.marker.collapsed) continue;
  5996. if (sp.from == null) return true;
  5997. if (sp.marker.widgetNode) continue;
  5998. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5999. return true;
  6000. }
  6001. }
  6002. function lineIsHiddenInner(doc, line, span) {
  6003. if (span.to == null) {
  6004. var end = span.marker.find(1, true);
  6005. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  6006. }
  6007. if (span.marker.inclusiveRight && span.to == line.text.length)
  6008. return true;
  6009. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  6010. sp = line.markedSpans[i];
  6011. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  6012. (sp.to == null || sp.to != span.from) &&
  6013. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  6014. lineIsHiddenInner(doc, line, sp)) return true;
  6015. }
  6016. }
  6017. // LINE WIDGETS
  6018. // Line widgets are block elements displayed above or below a line.
  6019. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  6020. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  6021. this[opt] = options[opt];
  6022. this.doc = doc;
  6023. this.node = node;
  6024. };
  6025. eventMixin(LineWidget);
  6026. function adjustScrollWhenAboveVisible(cm, line, diff) {
  6027. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  6028. addToScrollPos(cm, null, diff);
  6029. }
  6030. LineWidget.prototype.clear = function() {
  6031. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  6032. if (no == null || !ws) return;
  6033. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  6034. if (!ws.length) line.widgets = null;
  6035. var height = widgetHeight(this);
  6036. updateLineHeight(line, Math.max(0, line.height - height));
  6037. if (cm) runInOp(cm, function() {
  6038. adjustScrollWhenAboveVisible(cm, line, -height);
  6039. regLineChange(cm, no, "widget");
  6040. });
  6041. };
  6042. LineWidget.prototype.changed = function() {
  6043. var oldH = this.height, cm = this.doc.cm, line = this.line;
  6044. this.height = null;
  6045. var diff = widgetHeight(this) - oldH;
  6046. if (!diff) return;
  6047. updateLineHeight(line, line.height + diff);
  6048. if (cm) runInOp(cm, function() {
  6049. cm.curOp.forceUpdate = true;
  6050. adjustScrollWhenAboveVisible(cm, line, diff);
  6051. });
  6052. };
  6053. function widgetHeight(widget) {
  6054. if (widget.height != null) return widget.height;
  6055. var cm = widget.doc.cm;
  6056. if (!cm) return 0;
  6057. if (!contains(document.body, widget.node)) {
  6058. var parentStyle = "position: relative;";
  6059. if (widget.coverGutter)
  6060. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  6061. if (widget.noHScroll)
  6062. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  6063. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  6064. }
  6065. return widget.height = widget.node.parentNode.offsetHeight;
  6066. }
  6067. function addLineWidget(doc, handle, node, options) {
  6068. var widget = new LineWidget(doc, node, options);
  6069. var cm = doc.cm;
  6070. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  6071. changeLine(doc, handle, "widget", function(line) {
  6072. var widgets = line.widgets || (line.widgets = []);
  6073. if (widget.insertAt == null) widgets.push(widget);
  6074. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  6075. widget.line = line;
  6076. if (cm && !lineIsHidden(doc, line)) {
  6077. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  6078. updateLineHeight(line, line.height + widgetHeight(widget));
  6079. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  6080. cm.curOp.forceUpdate = true;
  6081. }
  6082. return true;
  6083. });
  6084. return widget;
  6085. }
  6086. // LINE DATA STRUCTURE
  6087. // Line objects. These hold state related to a line, including
  6088. // highlighting info (the styles array).
  6089. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  6090. this.text = text;
  6091. attachMarkedSpans(this, markedSpans);
  6092. this.height = estimateHeight ? estimateHeight(this) : 1;
  6093. };
  6094. eventMixin(Line);
  6095. Line.prototype.lineNo = function() { return lineNo(this); };
  6096. // Change the content (text, markers) of a line. Automatically
  6097. // invalidates cached information and tries to re-estimate the
  6098. // line's height.
  6099. function updateLine(line, text, markedSpans, estimateHeight) {
  6100. line.text = text;
  6101. if (line.stateAfter) line.stateAfter = null;
  6102. if (line.styles) line.styles = null;
  6103. if (line.order != null) line.order = null;
  6104. detachMarkedSpans(line);
  6105. attachMarkedSpans(line, markedSpans);
  6106. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  6107. if (estHeight != line.height) updateLineHeight(line, estHeight);
  6108. }
  6109. // Detach a line from the document tree and its markers.
  6110. function cleanUpLine(line) {
  6111. line.parent = null;
  6112. detachMarkedSpans(line);
  6113. }
  6114. function extractLineClasses(type, output) {
  6115. if (type) for (;;) {
  6116. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  6117. if (!lineClass) break;
  6118. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  6119. var prop = lineClass[1] ? "bgClass" : "textClass";
  6120. if (output[prop] == null)
  6121. output[prop] = lineClass[2];
  6122. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  6123. output[prop] += " " + lineClass[2];
  6124. }
  6125. return type;
  6126. }
  6127. function callBlankLine(mode, state) {
  6128. if (mode.blankLine) return mode.blankLine(state);
  6129. if (!mode.innerMode) return;
  6130. var inner = CodeMirror.innerMode(mode, state);
  6131. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  6132. }
  6133. function readToken(mode, stream, state, inner) {
  6134. for (var i = 0; i < 10; i++) {
  6135. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  6136. var style = mode.token(stream, state);
  6137. if (stream.pos > stream.start) return style;
  6138. }
  6139. throw new Error("Mode " + mode.name + " failed to advance stream.");
  6140. }
  6141. // Utility for getTokenAt and getLineTokens
  6142. function takeToken(cm, pos, precise, asArray) {
  6143. function getObj(copy) {
  6144. return {start: stream.start, end: stream.pos,
  6145. string: stream.current(),
  6146. type: style || null,
  6147. state: copy ? copyState(doc.mode, state) : state};
  6148. }
  6149. var doc = cm.doc, mode = doc.mode, style;
  6150. pos = clipPos(doc, pos);
  6151. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  6152. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  6153. if (asArray) tokens = [];
  6154. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  6155. stream.start = stream.pos;
  6156. style = readToken(mode, stream, state);
  6157. if (asArray) tokens.push(getObj(true));
  6158. }
  6159. return asArray ? tokens : getObj();
  6160. }
  6161. // Run the given mode's parser over a line, calling f for each token.
  6162. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  6163. var flattenSpans = mode.flattenSpans;
  6164. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  6165. var curStart = 0, curStyle = null;
  6166. var stream = new StringStream(text, cm.options.tabSize), style;
  6167. var inner = cm.options.addModeClass && [null];
  6168. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  6169. while (!stream.eol()) {
  6170. if (stream.pos > cm.options.maxHighlightLength) {
  6171. flattenSpans = false;
  6172. if (forceToEnd) processLine(cm, text, state, stream.pos);
  6173. stream.pos = text.length;
  6174. style = null;
  6175. } else {
  6176. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  6177. }
  6178. if (inner) {
  6179. var mName = inner[0].name;
  6180. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  6181. }
  6182. if (!flattenSpans || curStyle != style) {
  6183. while (curStart < stream.start) {
  6184. curStart = Math.min(stream.start, curStart + 50000);
  6185. f(curStart, curStyle);
  6186. }
  6187. curStyle = style;
  6188. }
  6189. stream.start = stream.pos;
  6190. }
  6191. while (curStart < stream.pos) {
  6192. // Webkit seems to refuse to render text nodes longer than 57444 characters
  6193. var pos = Math.min(stream.pos, curStart + 50000);
  6194. f(pos, curStyle);
  6195. curStart = pos;
  6196. }
  6197. }
  6198. // Compute a style array (an array starting with a mode generation
  6199. // -- for invalidation -- followed by pairs of end positions and
  6200. // style strings), which is used to highlight the tokens on the
  6201. // line.
  6202. function highlightLine(cm, line, state, forceToEnd) {
  6203. // A styles array always starts with a number identifying the
  6204. // mode/overlays that it is based on (for easy invalidation).
  6205. var st = [cm.state.modeGen], lineClasses = {};
  6206. // Compute the base array of styles
  6207. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  6208. st.push(end, style);
  6209. }, lineClasses, forceToEnd);
  6210. // Run overlays, adjust style array.
  6211. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6212. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6213. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  6214. var start = i;
  6215. // Ensure there's a token end at the current position, and that i points at it
  6216. while (at < end) {
  6217. var i_end = st[i];
  6218. if (i_end > end)
  6219. st.splice(i, 1, end, st[i+1], i_end);
  6220. i += 2;
  6221. at = Math.min(end, i_end);
  6222. }
  6223. if (!style) return;
  6224. if (overlay.opaque) {
  6225. st.splice(start, i - start, end, "cm-overlay " + style);
  6226. i = start + 2;
  6227. } else {
  6228. for (; start < i; start += 2) {
  6229. var cur = st[start+1];
  6230. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6231. }
  6232. }
  6233. }, lineClasses);
  6234. }
  6235. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  6236. }
  6237. function getLineStyles(cm, line, updateFrontier) {
  6238. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6239. var state = getStateBefore(cm, lineNo(line));
  6240. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  6241. line.stateAfter = state;
  6242. line.styles = result.styles;
  6243. if (result.classes) line.styleClasses = result.classes;
  6244. else if (line.styleClasses) line.styleClasses = null;
  6245. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6246. }
  6247. return line.styles;
  6248. }
  6249. // Lightweight form of highlight -- proceed over this line and
  6250. // update state, but don't save a style array. Used for lines that
  6251. // aren't currently visible.
  6252. function processLine(cm, text, state, startAt) {
  6253. var mode = cm.doc.mode;
  6254. var stream = new StringStream(text, cm.options.tabSize);
  6255. stream.start = stream.pos = startAt || 0;
  6256. if (text == "") callBlankLine(mode, state);
  6257. while (!stream.eol()) {
  6258. readToken(mode, stream, state);
  6259. stream.start = stream.pos;
  6260. }
  6261. }
  6262. // Convert a style as returned by a mode (either null, or a string
  6263. // containing one or more styles) to a CSS style. This is cached,
  6264. // and also looks for line-wide styles.
  6265. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6266. function interpretTokenStyle(style, options) {
  6267. if (!style || /^\s*$/.test(style)) return null;
  6268. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6269. return cache[style] ||
  6270. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6271. }
  6272. // Render the DOM representation of the text of a line. Also builds
  6273. // up a 'line map', which points at the DOM nodes that represent
  6274. // specific stretches of text, and is used by the measuring code.
  6275. // The returned object contains the DOM node, this map, and
  6276. // information about line-wide styles that were set by the mode.
  6277. function buildLineContent(cm, lineView) {
  6278. // The padding-right forces the element to have a 'border', which
  6279. // is needed on Webkit to be able to get line-level bounding
  6280. // rectangles for it (in measureChar).
  6281. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6282. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  6283. col: 0, pos: 0, cm: cm,
  6284. trailingSpace: false,
  6285. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  6286. lineView.measure = {};
  6287. // Iterate over the logical lines that make up this visual line.
  6288. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6289. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6290. builder.pos = 0;
  6291. builder.addToken = buildToken;
  6292. // Optionally wire in some hacks into the token-rendering
  6293. // algorithm, to deal with browser quirks.
  6294. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6295. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6296. builder.map = [];
  6297. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6298. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6299. if (line.styleClasses) {
  6300. if (line.styleClasses.bgClass)
  6301. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6302. if (line.styleClasses.textClass)
  6303. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6304. }
  6305. // Ensure at least a single node is present, for measuring.
  6306. if (builder.map.length == 0)
  6307. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6308. // Store the map and a cache object for the current logical line
  6309. if (i == 0) {
  6310. lineView.measure.map = builder.map;
  6311. lineView.measure.cache = {};
  6312. } else {
  6313. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6314. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6315. }
  6316. }
  6317. // See issue #2901
  6318. if (webkit) {
  6319. var last = builder.content.lastChild
  6320. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  6321. builder.content.className = "cm-tab-wrap-hack";
  6322. }
  6323. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6324. if (builder.pre.className)
  6325. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6326. return builder;
  6327. }
  6328. function defaultSpecialCharPlaceholder(ch) {
  6329. var token = elt("span", "\u2022", "cm-invalidchar");
  6330. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6331. token.setAttribute("aria-label", token.title);
  6332. return token;
  6333. }
  6334. // Build up the DOM representation for a single token, and add it to
  6335. // the line map. Takes care to render special characters separately.
  6336. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6337. if (!text) return;
  6338. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  6339. var special = builder.cm.state.specialChars, mustWrap = false;
  6340. if (!special.test(text)) {
  6341. builder.col += text.length;
  6342. var content = document.createTextNode(displayText);
  6343. builder.map.push(builder.pos, builder.pos + text.length, content);
  6344. if (ie && ie_version < 9) mustWrap = true;
  6345. builder.pos += text.length;
  6346. } else {
  6347. var content = document.createDocumentFragment(), pos = 0;
  6348. while (true) {
  6349. special.lastIndex = pos;
  6350. var m = special.exec(text);
  6351. var skipped = m ? m.index - pos : text.length - pos;
  6352. if (skipped) {
  6353. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  6354. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6355. else content.appendChild(txt);
  6356. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6357. builder.col += skipped;
  6358. builder.pos += skipped;
  6359. }
  6360. if (!m) break;
  6361. pos += skipped + 1;
  6362. if (m[0] == "\t") {
  6363. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6364. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6365. txt.setAttribute("role", "presentation");
  6366. txt.setAttribute("cm-text", "\t");
  6367. builder.col += tabWidth;
  6368. } else if (m[0] == "\r" || m[0] == "\n") {
  6369. var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  6370. txt.setAttribute("cm-text", m[0]);
  6371. builder.col += 1;
  6372. } else {
  6373. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6374. txt.setAttribute("cm-text", m[0]);
  6375. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6376. else content.appendChild(txt);
  6377. builder.col += 1;
  6378. }
  6379. builder.map.push(builder.pos, builder.pos + 1, txt);
  6380. builder.pos++;
  6381. }
  6382. }
  6383. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  6384. if (style || startStyle || endStyle || mustWrap || css) {
  6385. var fullStyle = style || "";
  6386. if (startStyle) fullStyle += startStyle;
  6387. if (endStyle) fullStyle += endStyle;
  6388. var token = elt("span", [content], fullStyle, css);
  6389. if (title) token.title = title;
  6390. return builder.content.appendChild(token);
  6391. }
  6392. builder.content.appendChild(content);
  6393. }
  6394. function splitSpaces(text, trailingBefore) {
  6395. if (text.length > 1 && !/ /.test(text)) return text
  6396. var spaceBefore = trailingBefore, result = ""
  6397. for (var i = 0; i < text.length; i++) {
  6398. var ch = text.charAt(i)
  6399. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  6400. ch = "\u00a0"
  6401. result += ch
  6402. spaceBefore = ch == " "
  6403. }
  6404. return result
  6405. }
  6406. // Work around nonsense dimensions being reported for stretches of
  6407. // right-to-left text.
  6408. function buildTokenBadBidi(inner, order) {
  6409. return function(builder, text, style, startStyle, endStyle, title, css) {
  6410. style = style ? style + " cm-force-border" : "cm-force-border";
  6411. var start = builder.pos, end = start + text.length;
  6412. for (;;) {
  6413. // Find the part that overlaps with the start of this text
  6414. for (var i = 0; i < order.length; i++) {
  6415. var part = order[i];
  6416. if (part.to > start && part.from <= start) break;
  6417. }
  6418. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  6419. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  6420. startStyle = null;
  6421. text = text.slice(part.to - start);
  6422. start = part.to;
  6423. }
  6424. };
  6425. }
  6426. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6427. var widget = !ignoreWidget && marker.widgetNode;
  6428. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6429. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6430. if (!widget)
  6431. widget = builder.content.appendChild(document.createElement("span"));
  6432. widget.setAttribute("cm-marker", marker.id);
  6433. }
  6434. if (widget) {
  6435. builder.cm.display.input.setUneditable(widget);
  6436. builder.content.appendChild(widget);
  6437. }
  6438. builder.pos += size;
  6439. builder.trailingSpace = false
  6440. }
  6441. // Outputs a number of spans to make up a line, taking highlighting
  6442. // and marked text into account.
  6443. function insertLineContent(line, builder, styles) {
  6444. var spans = line.markedSpans, allText = line.text, at = 0;
  6445. if (!spans) {
  6446. for (var i = 1; i < styles.length; i+=2)
  6447. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  6448. return;
  6449. }
  6450. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6451. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6452. for (;;) {
  6453. if (nextChange == pos) { // Update current marker set
  6454. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6455. collapsed = null; nextChange = Infinity;
  6456. var foundBookmarks = [], endStyles
  6457. for (var j = 0; j < spans.length; ++j) {
  6458. var sp = spans[j], m = sp.marker;
  6459. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  6460. foundBookmarks.push(m);
  6461. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  6462. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  6463. nextChange = sp.to;
  6464. spanEndStyle = "";
  6465. }
  6466. if (m.className) spanStyle += " " + m.className;
  6467. if (m.css) css = (css ? css + ";" : "") + m.css;
  6468. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6469. if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  6470. if (m.title && !title) title = m.title;
  6471. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6472. collapsed = sp;
  6473. } else if (sp.from > pos && nextChange > sp.from) {
  6474. nextChange = sp.from;
  6475. }
  6476. }
  6477. if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
  6478. if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  6479. if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
  6480. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6481. if (collapsed && (collapsed.from || 0) == pos) {
  6482. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6483. collapsed.marker, collapsed.from == null);
  6484. if (collapsed.to == null) return;
  6485. if (collapsed.to == pos) collapsed = false;
  6486. }
  6487. }
  6488. if (pos >= len) break;
  6489. var upto = Math.min(len, nextChange);
  6490. while (true) {
  6491. if (text) {
  6492. var end = pos + text.length;
  6493. if (!collapsed) {
  6494. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6495. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6496. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6497. }
  6498. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  6499. pos = end;
  6500. spanStartStyle = "";
  6501. }
  6502. text = allText.slice(at, at = styles[i++]);
  6503. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6504. }
  6505. }
  6506. }
  6507. // DOCUMENT DATA STRUCTURE
  6508. // By default, updates that start and end at the beginning of a line
  6509. // are treated specially, in order to make the association of line
  6510. // widgets and marker elements with the text behave more intuitive.
  6511. function isWholeLineUpdate(doc, change) {
  6512. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6513. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6514. }
  6515. // Perform a change on the document data structure.
  6516. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6517. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  6518. function update(line, text, spans) {
  6519. updateLine(line, text, spans, estimateHeight);
  6520. signalLater(line, "change", line, change);
  6521. }
  6522. function linesFor(start, end) {
  6523. for (var i = start, result = []; i < end; ++i)
  6524. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6525. return result;
  6526. }
  6527. var from = change.from, to = change.to, text = change.text;
  6528. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6529. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6530. // Adjust the line structure
  6531. if (change.full) {
  6532. doc.insert(0, linesFor(0, text.length));
  6533. doc.remove(text.length, doc.size - text.length);
  6534. } else if (isWholeLineUpdate(doc, change)) {
  6535. // This is a whole-line replace. Treated specially to make
  6536. // sure line objects move the way they are supposed to.
  6537. var added = linesFor(0, text.length - 1);
  6538. update(lastLine, lastLine.text, lastSpans);
  6539. if (nlines) doc.remove(from.line, nlines);
  6540. if (added.length) doc.insert(from.line, added);
  6541. } else if (firstLine == lastLine) {
  6542. if (text.length == 1) {
  6543. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6544. } else {
  6545. var added = linesFor(1, text.length - 1);
  6546. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6547. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6548. doc.insert(from.line + 1, added);
  6549. }
  6550. } else if (text.length == 1) {
  6551. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6552. doc.remove(from.line + 1, nlines);
  6553. } else {
  6554. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6555. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6556. var added = linesFor(1, text.length - 1);
  6557. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6558. doc.insert(from.line + 1, added);
  6559. }
  6560. signalLater(doc, "change", doc, change);
  6561. }
  6562. // The document is represented as a BTree consisting of leaves, with
  6563. // chunk of lines in them, and branches, with up to ten leaves or
  6564. // other branch nodes below them. The top node is always a branch
  6565. // node, and is the document object itself (meaning it has
  6566. // additional methods and properties).
  6567. //
  6568. // All nodes have parent links. The tree is used both to go from
  6569. // line numbers to line objects, and to go from objects to numbers.
  6570. // It also indexes by height, and is used to convert between height
  6571. // and line object, and to find the total height of the document.
  6572. //
  6573. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6574. function LeafChunk(lines) {
  6575. this.lines = lines;
  6576. this.parent = null;
  6577. for (var i = 0, height = 0; i < lines.length; ++i) {
  6578. lines[i].parent = this;
  6579. height += lines[i].height;
  6580. }
  6581. this.height = height;
  6582. }
  6583. LeafChunk.prototype = {
  6584. chunkSize: function() { return this.lines.length; },
  6585. // Remove the n lines at offset 'at'.
  6586. removeInner: function(at, n) {
  6587. for (var i = at, e = at + n; i < e; ++i) {
  6588. var line = this.lines[i];
  6589. this.height -= line.height;
  6590. cleanUpLine(line);
  6591. signalLater(line, "delete");
  6592. }
  6593. this.lines.splice(at, n);
  6594. },
  6595. // Helper used to collapse a small branch into a single leaf.
  6596. collapse: function(lines) {
  6597. lines.push.apply(lines, this.lines);
  6598. },
  6599. // Insert the given array of lines at offset 'at', count them as
  6600. // having the given height.
  6601. insertInner: function(at, lines, height) {
  6602. this.height += height;
  6603. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6604. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6605. },
  6606. // Used to iterate over a part of the tree.
  6607. iterN: function(at, n, op) {
  6608. for (var e = at + n; at < e; ++at)
  6609. if (op(this.lines[at])) return true;
  6610. }
  6611. };
  6612. function BranchChunk(children) {
  6613. this.children = children;
  6614. var size = 0, height = 0;
  6615. for (var i = 0; i < children.length; ++i) {
  6616. var ch = children[i];
  6617. size += ch.chunkSize(); height += ch.height;
  6618. ch.parent = this;
  6619. }
  6620. this.size = size;
  6621. this.height = height;
  6622. this.parent = null;
  6623. }
  6624. BranchChunk.prototype = {
  6625. chunkSize: function() { return this.size; },
  6626. removeInner: function(at, n) {
  6627. this.size -= n;
  6628. for (var i = 0; i < this.children.length; ++i) {
  6629. var child = this.children[i], sz = child.chunkSize();
  6630. if (at < sz) {
  6631. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6632. child.removeInner(at, rm);
  6633. this.height -= oldHeight - child.height;
  6634. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6635. if ((n -= rm) == 0) break;
  6636. at = 0;
  6637. } else at -= sz;
  6638. }
  6639. // If the result is smaller than 25 lines, ensure that it is a
  6640. // single leaf node.
  6641. if (this.size - n < 25 &&
  6642. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6643. var lines = [];
  6644. this.collapse(lines);
  6645. this.children = [new LeafChunk(lines)];
  6646. this.children[0].parent = this;
  6647. }
  6648. },
  6649. collapse: function(lines) {
  6650. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6651. },
  6652. insertInner: function(at, lines, height) {
  6653. this.size += lines.length;
  6654. this.height += height;
  6655. for (var i = 0; i < this.children.length; ++i) {
  6656. var child = this.children[i], sz = child.chunkSize();
  6657. if (at <= sz) {
  6658. child.insertInner(at, lines, height);
  6659. if (child.lines && child.lines.length > 50) {
  6660. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  6661. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  6662. var remaining = child.lines.length % 25 + 25
  6663. for (var pos = remaining; pos < child.lines.length;) {
  6664. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  6665. child.height -= leaf.height;
  6666. this.children.splice(++i, 0, leaf);
  6667. leaf.parent = this;
  6668. }
  6669. child.lines = child.lines.slice(0, remaining);
  6670. this.maybeSpill();
  6671. }
  6672. break;
  6673. }
  6674. at -= sz;
  6675. }
  6676. },
  6677. // When a node has grown, check whether it should be split.
  6678. maybeSpill: function() {
  6679. if (this.children.length <= 10) return;
  6680. var me = this;
  6681. do {
  6682. var spilled = me.children.splice(me.children.length - 5, 5);
  6683. var sibling = new BranchChunk(spilled);
  6684. if (!me.parent) { // Become the parent node
  6685. var copy = new BranchChunk(me.children);
  6686. copy.parent = me;
  6687. me.children = [copy, sibling];
  6688. me = copy;
  6689. } else {
  6690. me.size -= sibling.size;
  6691. me.height -= sibling.height;
  6692. var myIndex = indexOf(me.parent.children, me);
  6693. me.parent.children.splice(myIndex + 1, 0, sibling);
  6694. }
  6695. sibling.parent = me.parent;
  6696. } while (me.children.length > 10);
  6697. me.parent.maybeSpill();
  6698. },
  6699. iterN: function(at, n, op) {
  6700. for (var i = 0; i < this.children.length; ++i) {
  6701. var child = this.children[i], sz = child.chunkSize();
  6702. if (at < sz) {
  6703. var used = Math.min(n, sz - at);
  6704. if (child.iterN(at, used, op)) return true;
  6705. if ((n -= used) == 0) break;
  6706. at = 0;
  6707. } else at -= sz;
  6708. }
  6709. }
  6710. };
  6711. var nextDocId = 0;
  6712. var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
  6713. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
  6714. if (firstLine == null) firstLine = 0;
  6715. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6716. this.first = firstLine;
  6717. this.scrollTop = this.scrollLeft = 0;
  6718. this.cantEdit = false;
  6719. this.cleanGeneration = 1;
  6720. this.frontier = firstLine;
  6721. var start = Pos(firstLine, 0);
  6722. this.sel = simpleSelection(start);
  6723. this.history = new History(null);
  6724. this.id = ++nextDocId;
  6725. this.modeOption = mode;
  6726. this.lineSep = lineSep;
  6727. this.extend = false;
  6728. if (typeof text == "string") text = this.splitLines(text);
  6729. updateDoc(this, {from: start, to: start, text: text});
  6730. setSelection(this, simpleSelection(start), sel_dontScroll);
  6731. };
  6732. Doc.prototype = createObj(BranchChunk.prototype, {
  6733. constructor: Doc,
  6734. // Iterate over the document. Supports two forms -- with only one
  6735. // argument, it calls that for each line in the document. With
  6736. // three, it iterates over the range given by the first two (with
  6737. // the second being non-inclusive).
  6738. iter: function(from, to, op) {
  6739. if (op) this.iterN(from - this.first, to - from, op);
  6740. else this.iterN(this.first, this.first + this.size, from);
  6741. },
  6742. // Non-public interface for adding and removing lines.
  6743. insert: function(at, lines) {
  6744. var height = 0;
  6745. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6746. this.insertInner(at - this.first, lines, height);
  6747. },
  6748. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6749. // From here, the methods are part of the public interface. Most
  6750. // are also available from CodeMirror (editor) instances.
  6751. getValue: function(lineSep) {
  6752. var lines = getLines(this, this.first, this.first + this.size);
  6753. if (lineSep === false) return lines;
  6754. return lines.join(lineSep || this.lineSeparator());
  6755. },
  6756. setValue: docMethodOp(function(code) {
  6757. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6758. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6759. text: this.splitLines(code), origin: "setValue", full: true}, true);
  6760. setSelection(this, simpleSelection(top));
  6761. }),
  6762. replaceRange: function(code, from, to, origin) {
  6763. from = clipPos(this, from);
  6764. to = to ? clipPos(this, to) : from;
  6765. replaceRange(this, code, from, to, origin);
  6766. },
  6767. getRange: function(from, to, lineSep) {
  6768. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6769. if (lineSep === false) return lines;
  6770. return lines.join(lineSep || this.lineSeparator());
  6771. },
  6772. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6773. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6774. getLineNumber: function(line) {return lineNo(line);},
  6775. getLineHandleVisualStart: function(line) {
  6776. if (typeof line == "number") line = getLine(this, line);
  6777. return visualLine(line);
  6778. },
  6779. lineCount: function() {return this.size;},
  6780. firstLine: function() {return this.first;},
  6781. lastLine: function() {return this.first + this.size - 1;},
  6782. clipPos: function(pos) {return clipPos(this, pos);},
  6783. getCursor: function(start) {
  6784. var range = this.sel.primary(), pos;
  6785. if (start == null || start == "head") pos = range.head;
  6786. else if (start == "anchor") pos = range.anchor;
  6787. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6788. else pos = range.from();
  6789. return pos;
  6790. },
  6791. listSelections: function() { return this.sel.ranges; },
  6792. somethingSelected: function() {return this.sel.somethingSelected();},
  6793. setCursor: docMethodOp(function(line, ch, options) {
  6794. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6795. }),
  6796. setSelection: docMethodOp(function(anchor, head, options) {
  6797. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6798. }),
  6799. extendSelection: docMethodOp(function(head, other, options) {
  6800. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6801. }),
  6802. extendSelections: docMethodOp(function(heads, options) {
  6803. extendSelections(this, clipPosArray(this, heads), options);
  6804. }),
  6805. extendSelectionsBy: docMethodOp(function(f, options) {
  6806. var heads = map(this.sel.ranges, f);
  6807. extendSelections(this, clipPosArray(this, heads), options);
  6808. }),
  6809. setSelections: docMethodOp(function(ranges, primary, options) {
  6810. if (!ranges.length) return;
  6811. for (var i = 0, out = []; i < ranges.length; i++)
  6812. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6813. clipPos(this, ranges[i].head));
  6814. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6815. setSelection(this, normalizeSelection(out, primary), options);
  6816. }),
  6817. addSelection: docMethodOp(function(anchor, head, options) {
  6818. var ranges = this.sel.ranges.slice(0);
  6819. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6820. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6821. }),
  6822. getSelection: function(lineSep) {
  6823. var ranges = this.sel.ranges, lines;
  6824. for (var i = 0; i < ranges.length; i++) {
  6825. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6826. lines = lines ? lines.concat(sel) : sel;
  6827. }
  6828. if (lineSep === false) return lines;
  6829. else return lines.join(lineSep || this.lineSeparator());
  6830. },
  6831. getSelections: function(lineSep) {
  6832. var parts = [], ranges = this.sel.ranges;
  6833. for (var i = 0; i < ranges.length; i++) {
  6834. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6835. if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
  6836. parts[i] = sel;
  6837. }
  6838. return parts;
  6839. },
  6840. replaceSelection: function(code, collapse, origin) {
  6841. var dup = [];
  6842. for (var i = 0; i < this.sel.ranges.length; i++)
  6843. dup[i] = code;
  6844. this.replaceSelections(dup, collapse, origin || "+input");
  6845. },
  6846. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6847. var changes = [], sel = this.sel;
  6848. for (var i = 0; i < sel.ranges.length; i++) {
  6849. var range = sel.ranges[i];
  6850. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  6851. }
  6852. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6853. for (var i = changes.length - 1; i >= 0; i--)
  6854. makeChange(this, changes[i]);
  6855. if (newSel) setSelectionReplaceHistory(this, newSel);
  6856. else if (this.cm) ensureCursorVisible(this.cm);
  6857. }),
  6858. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6859. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6860. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6861. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6862. setExtending: function(val) {this.extend = val;},
  6863. getExtending: function() {return this.extend;},
  6864. historySize: function() {
  6865. var hist = this.history, done = 0, undone = 0;
  6866. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6867. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6868. return {undo: done, redo: undone};
  6869. },
  6870. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6871. markClean: function() {
  6872. this.cleanGeneration = this.changeGeneration(true);
  6873. },
  6874. changeGeneration: function(forceSplit) {
  6875. if (forceSplit)
  6876. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6877. return this.history.generation;
  6878. },
  6879. isClean: function (gen) {
  6880. return this.history.generation == (gen || this.cleanGeneration);
  6881. },
  6882. getHistory: function() {
  6883. return {done: copyHistoryArray(this.history.done),
  6884. undone: copyHistoryArray(this.history.undone)};
  6885. },
  6886. setHistory: function(histData) {
  6887. var hist = this.history = new History(this.history.maxGeneration);
  6888. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6889. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6890. },
  6891. addLineClass: docMethodOp(function(handle, where, cls) {
  6892. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6893. var prop = where == "text" ? "textClass"
  6894. : where == "background" ? "bgClass"
  6895. : where == "gutter" ? "gutterClass" : "wrapClass";
  6896. if (!line[prop]) line[prop] = cls;
  6897. else if (classTest(cls).test(line[prop])) return false;
  6898. else line[prop] += " " + cls;
  6899. return true;
  6900. });
  6901. }),
  6902. removeLineClass: docMethodOp(function(handle, where, cls) {
  6903. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6904. var prop = where == "text" ? "textClass"
  6905. : where == "background" ? "bgClass"
  6906. : where == "gutter" ? "gutterClass" : "wrapClass";
  6907. var cur = line[prop];
  6908. if (!cur) return false;
  6909. else if (cls == null) line[prop] = null;
  6910. else {
  6911. var found = cur.match(classTest(cls));
  6912. if (!found) return false;
  6913. var end = found.index + found[0].length;
  6914. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6915. }
  6916. return true;
  6917. });
  6918. }),
  6919. addLineWidget: docMethodOp(function(handle, node, options) {
  6920. return addLineWidget(this, handle, node, options);
  6921. }),
  6922. removeLineWidget: function(widget) { widget.clear(); },
  6923. markText: function(from, to, options) {
  6924. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
  6925. },
  6926. setBookmark: function(pos, options) {
  6927. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6928. insertLeft: options && options.insertLeft,
  6929. clearWhenEmpty: false, shared: options && options.shared,
  6930. handleMouseEvents: options && options.handleMouseEvents};
  6931. pos = clipPos(this, pos);
  6932. return markText(this, pos, pos, realOpts, "bookmark");
  6933. },
  6934. findMarksAt: function(pos) {
  6935. pos = clipPos(this, pos);
  6936. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6937. if (spans) for (var i = 0; i < spans.length; ++i) {
  6938. var span = spans[i];
  6939. if ((span.from == null || span.from <= pos.ch) &&
  6940. (span.to == null || span.to >= pos.ch))
  6941. markers.push(span.marker.parent || span.marker);
  6942. }
  6943. return markers;
  6944. },
  6945. findMarks: function(from, to, filter) {
  6946. from = clipPos(this, from); to = clipPos(this, to);
  6947. var found = [], lineNo = from.line;
  6948. this.iter(from.line, to.line + 1, function(line) {
  6949. var spans = line.markedSpans;
  6950. if (spans) for (var i = 0; i < spans.length; i++) {
  6951. var span = spans[i];
  6952. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  6953. span.from == null && lineNo != from.line ||
  6954. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  6955. (!filter || filter(span.marker)))
  6956. found.push(span.marker.parent || span.marker);
  6957. }
  6958. ++lineNo;
  6959. });
  6960. return found;
  6961. },
  6962. getAllMarks: function() {
  6963. var markers = [];
  6964. this.iter(function(line) {
  6965. var sps = line.markedSpans;
  6966. if (sps) for (var i = 0; i < sps.length; ++i)
  6967. if (sps[i].from != null) markers.push(sps[i].marker);
  6968. });
  6969. return markers;
  6970. },
  6971. posFromIndex: function(off) {
  6972. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  6973. this.iter(function(line) {
  6974. var sz = line.text.length + sepSize;
  6975. if (sz > off) { ch = off; return true; }
  6976. off -= sz;
  6977. ++lineNo;
  6978. });
  6979. return clipPos(this, Pos(lineNo, ch));
  6980. },
  6981. indexFromPos: function (coords) {
  6982. coords = clipPos(this, coords);
  6983. var index = coords.ch;
  6984. if (coords.line < this.first || coords.ch < 0) return 0;
  6985. var sepSize = this.lineSeparator().length;
  6986. this.iter(this.first, coords.line, function (line) {
  6987. index += line.text.length + sepSize;
  6988. });
  6989. return index;
  6990. },
  6991. copy: function(copyHistory) {
  6992. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  6993. this.modeOption, this.first, this.lineSep);
  6994. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6995. doc.sel = this.sel;
  6996. doc.extend = false;
  6997. if (copyHistory) {
  6998. doc.history.undoDepth = this.history.undoDepth;
  6999. doc.setHistory(this.getHistory());
  7000. }
  7001. return doc;
  7002. },
  7003. linkedDoc: function(options) {
  7004. if (!options) options = {};
  7005. var from = this.first, to = this.first + this.size;
  7006. if (options.from != null && options.from > from) from = options.from;
  7007. if (options.to != null && options.to < to) to = options.to;
  7008. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
  7009. if (options.sharedHist) copy.history = this.history;
  7010. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  7011. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  7012. copySharedMarkers(copy, findSharedMarkers(this));
  7013. return copy;
  7014. },
  7015. unlinkDoc: function(other) {
  7016. if (other instanceof CodeMirror) other = other.doc;
  7017. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  7018. var link = this.linked[i];
  7019. if (link.doc != other) continue;
  7020. this.linked.splice(i, 1);
  7021. other.unlinkDoc(this);
  7022. detachSharedMarkers(findSharedMarkers(this));
  7023. break;
  7024. }
  7025. // If the histories were shared, split them again
  7026. if (other.history == this.history) {
  7027. var splitIds = [other.id];
  7028. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  7029. other.history = new History(null);
  7030. other.history.done = copyHistoryArray(this.history.done, splitIds);
  7031. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  7032. }
  7033. },
  7034. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  7035. getMode: function() {return this.mode;},
  7036. getEditor: function() {return this.cm;},
  7037. splitLines: function(str) {
  7038. if (this.lineSep) return str.split(this.lineSep);
  7039. return splitLinesAuto(str);
  7040. },
  7041. lineSeparator: function() { return this.lineSep || "\n"; }
  7042. });
  7043. // Public alias.
  7044. Doc.prototype.eachLine = Doc.prototype.iter;
  7045. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  7046. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  7047. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  7048. CodeMirror.prototype[prop] = (function(method) {
  7049. return function() {return method.apply(this.doc, arguments);};
  7050. })(Doc.prototype[prop]);
  7051. eventMixin(Doc);
  7052. // Call f for all linked documents.
  7053. function linkedDocs(doc, f, sharedHistOnly) {
  7054. function propagate(doc, skip, sharedHist) {
  7055. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  7056. var rel = doc.linked[i];
  7057. if (rel.doc == skip) continue;
  7058. var shared = sharedHist && rel.sharedHist;
  7059. if (sharedHistOnly && !shared) continue;
  7060. f(rel.doc, shared);
  7061. propagate(rel.doc, doc, shared);
  7062. }
  7063. }
  7064. propagate(doc, null, true);
  7065. }
  7066. // Attach a document to an editor.
  7067. function attachDoc(cm, doc) {
  7068. if (doc.cm) throw new Error("This document is already in use.");
  7069. cm.doc = doc;
  7070. doc.cm = cm;
  7071. estimateLineHeights(cm);
  7072. loadMode(cm);
  7073. if (!cm.options.lineWrapping) findMaxLine(cm);
  7074. cm.options.mode = doc.modeOption;
  7075. regChange(cm);
  7076. }
  7077. // LINE UTILITIES
  7078. // Find the line object corresponding to the given line number.
  7079. function getLine(doc, n) {
  7080. n -= doc.first;
  7081. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  7082. for (var chunk = doc; !chunk.lines;) {
  7083. for (var i = 0;; ++i) {
  7084. var child = chunk.children[i], sz = child.chunkSize();
  7085. if (n < sz) { chunk = child; break; }
  7086. n -= sz;
  7087. }
  7088. }
  7089. return chunk.lines[n];
  7090. }
  7091. // Get the part of a document between two positions, as an array of
  7092. // strings.
  7093. function getBetween(doc, start, end) {
  7094. var out = [], n = start.line;
  7095. doc.iter(start.line, end.line + 1, function(line) {
  7096. var text = line.text;
  7097. if (n == end.line) text = text.slice(0, end.ch);
  7098. if (n == start.line) text = text.slice(start.ch);
  7099. out.push(text);
  7100. ++n;
  7101. });
  7102. return out;
  7103. }
  7104. // Get the lines between from and to, as array of strings.
  7105. function getLines(doc, from, to) {
  7106. var out = [];
  7107. doc.iter(from, to, function(line) { out.push(line.text); });
  7108. return out;
  7109. }
  7110. // Update the height of a line, propagating the height change
  7111. // upwards to parent nodes.
  7112. function updateLineHeight(line, height) {
  7113. var diff = height - line.height;
  7114. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  7115. }
  7116. // Given a line object, find its line number by walking up through
  7117. // its parent links.
  7118. function lineNo(line) {
  7119. if (line.parent == null) return null;
  7120. var cur = line.parent, no = indexOf(cur.lines, line);
  7121. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  7122. for (var i = 0;; ++i) {
  7123. if (chunk.children[i] == cur) break;
  7124. no += chunk.children[i].chunkSize();
  7125. }
  7126. }
  7127. return no + cur.first;
  7128. }
  7129. // Find the line at the given vertical position, using the height
  7130. // information in the document tree.
  7131. function lineAtHeight(chunk, h) {
  7132. var n = chunk.first;
  7133. outer: do {
  7134. for (var i = 0; i < chunk.children.length; ++i) {
  7135. var child = chunk.children[i], ch = child.height;
  7136. if (h < ch) { chunk = child; continue outer; }
  7137. h -= ch;
  7138. n += child.chunkSize();
  7139. }
  7140. return n;
  7141. } while (!chunk.lines);
  7142. for (var i = 0; i < chunk.lines.length; ++i) {
  7143. var line = chunk.lines[i], lh = line.height;
  7144. if (h < lh) break;
  7145. h -= lh;
  7146. }
  7147. return n + i;
  7148. }
  7149. // Find the height above the given line.
  7150. function heightAtLine(lineObj) {
  7151. lineObj = visualLine(lineObj);
  7152. var h = 0, chunk = lineObj.parent;
  7153. for (var i = 0; i < chunk.lines.length; ++i) {
  7154. var line = chunk.lines[i];
  7155. if (line == lineObj) break;
  7156. else h += line.height;
  7157. }
  7158. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  7159. for (var i = 0; i < p.children.length; ++i) {
  7160. var cur = p.children[i];
  7161. if (cur == chunk) break;
  7162. else h += cur.height;
  7163. }
  7164. }
  7165. return h;
  7166. }
  7167. // Get the bidi ordering for the given line (and cache it). Returns
  7168. // false for lines that are fully left-to-right, and an array of
  7169. // BidiSpan objects otherwise.
  7170. function getOrder(line) {
  7171. var order = line.order;
  7172. if (order == null) order = line.order = bidiOrdering(line.text);
  7173. return order;
  7174. }
  7175. // HISTORY
  7176. function History(startGen) {
  7177. // Arrays of change events and selections. Doing something adds an
  7178. // event to done and clears undo. Undoing moves events from done
  7179. // to undone, redoing moves them in the other direction.
  7180. this.done = []; this.undone = [];
  7181. this.undoDepth = Infinity;
  7182. // Used to track when changes can be merged into a single undo
  7183. // event
  7184. this.lastModTime = this.lastSelTime = 0;
  7185. this.lastOp = this.lastSelOp = null;
  7186. this.lastOrigin = this.lastSelOrigin = null;
  7187. // Used by the isClean() method
  7188. this.generation = this.maxGeneration = startGen || 1;
  7189. }
  7190. // Create a history change event from an updateDoc-style change
  7191. // object.
  7192. function historyChangeFromChange(doc, change) {
  7193. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  7194. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  7195. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  7196. return histChange;
  7197. }
  7198. // Pop all selection events off the end of a history array. Stop at
  7199. // a change event.
  7200. function clearSelectionEvents(array) {
  7201. while (array.length) {
  7202. var last = lst(array);
  7203. if (last.ranges) array.pop();
  7204. else break;
  7205. }
  7206. }
  7207. // Find the top change event in the history. Pop off selection
  7208. // events that are in the way.
  7209. function lastChangeEvent(hist, force) {
  7210. if (force) {
  7211. clearSelectionEvents(hist.done);
  7212. return lst(hist.done);
  7213. } else if (hist.done.length && !lst(hist.done).ranges) {
  7214. return lst(hist.done);
  7215. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  7216. hist.done.pop();
  7217. return lst(hist.done);
  7218. }
  7219. }
  7220. // Register a change in the history. Merges changes that are within
  7221. // a single operation, ore are close together with an origin that
  7222. // allows merging (starting with "+") into a single event.
  7223. function addChangeToHistory(doc, change, selAfter, opId) {
  7224. var hist = doc.history;
  7225. hist.undone.length = 0;
  7226. var time = +new Date, cur;
  7227. if ((hist.lastOp == opId ||
  7228. hist.lastOrigin == change.origin && change.origin &&
  7229. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  7230. change.origin.charAt(0) == "*")) &&
  7231. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  7232. // Merge this change into the last event
  7233. var last = lst(cur.changes);
  7234. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  7235. // Optimized case for simple insertion -- don't want to add
  7236. // new changesets for every character typed
  7237. last.to = changeEnd(change);
  7238. } else {
  7239. // Add new sub-event
  7240. cur.changes.push(historyChangeFromChange(doc, change));
  7241. }
  7242. } else {
  7243. // Can not be merged, start a new event.
  7244. var before = lst(hist.done);
  7245. if (!before || !before.ranges)
  7246. pushSelectionToHistory(doc.sel, hist.done);
  7247. cur = {changes: [historyChangeFromChange(doc, change)],
  7248. generation: hist.generation};
  7249. hist.done.push(cur);
  7250. while (hist.done.length > hist.undoDepth) {
  7251. hist.done.shift();
  7252. if (!hist.done[0].ranges) hist.done.shift();
  7253. }
  7254. }
  7255. hist.done.push(selAfter);
  7256. hist.generation = ++hist.maxGeneration;
  7257. hist.lastModTime = hist.lastSelTime = time;
  7258. hist.lastOp = hist.lastSelOp = opId;
  7259. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7260. if (!last) signal(doc, "historyAdded");
  7261. }
  7262. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7263. var ch = origin.charAt(0);
  7264. return ch == "*" ||
  7265. ch == "+" &&
  7266. prev.ranges.length == sel.ranges.length &&
  7267. prev.somethingSelected() == sel.somethingSelected() &&
  7268. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7269. }
  7270. // Called whenever the selection changes, sets the new selection as
  7271. // the pending selection in the history, and pushes the old pending
  7272. // selection into the 'done' array when it was significantly
  7273. // different (in number of selected ranges, emptiness, or time).
  7274. function addSelectionToHistory(doc, sel, opId, options) {
  7275. var hist = doc.history, origin = options && options.origin;
  7276. // A new event is started when the previous origin does not match
  7277. // the current, or the origins don't allow matching. Origins
  7278. // starting with * are always merged, those starting with + are
  7279. // merged when similar and close together in time.
  7280. if (opId == hist.lastSelOp ||
  7281. (origin && hist.lastSelOrigin == origin &&
  7282. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7283. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7284. hist.done[hist.done.length - 1] = sel;
  7285. else
  7286. pushSelectionToHistory(sel, hist.done);
  7287. hist.lastSelTime = +new Date;
  7288. hist.lastSelOrigin = origin;
  7289. hist.lastSelOp = opId;
  7290. if (options && options.clearRedo !== false)
  7291. clearSelectionEvents(hist.undone);
  7292. }
  7293. function pushSelectionToHistory(sel, dest) {
  7294. var top = lst(dest);
  7295. if (!(top && top.ranges && top.equals(sel)))
  7296. dest.push(sel);
  7297. }
  7298. // Used to store marked span information in the history.
  7299. function attachLocalSpans(doc, change, from, to) {
  7300. var existing = change["spans_" + doc.id], n = 0;
  7301. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  7302. if (line.markedSpans)
  7303. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7304. ++n;
  7305. });
  7306. }
  7307. // When un/re-doing restores text containing marked spans, those
  7308. // that have been explicitly cleared should not be restored.
  7309. function removeClearedSpans(spans) {
  7310. if (!spans) return null;
  7311. for (var i = 0, out; i < spans.length; ++i) {
  7312. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7313. else if (out) out.push(spans[i]);
  7314. }
  7315. return !out ? spans : out.length ? out : null;
  7316. }
  7317. // Retrieve and filter the old marked spans stored in a change event.
  7318. function getOldSpans(doc, change) {
  7319. var found = change["spans_" + doc.id];
  7320. if (!found) return null;
  7321. for (var i = 0, nw = []; i < change.text.length; ++i)
  7322. nw.push(removeClearedSpans(found[i]));
  7323. return nw;
  7324. }
  7325. // Used both to provide a JSON-safe object in .getHistory, and, when
  7326. // detaching a document, to split the history in two
  7327. function copyHistoryArray(events, newGroup, instantiateSel) {
  7328. for (var i = 0, copy = []; i < events.length; ++i) {
  7329. var event = events[i];
  7330. if (event.ranges) {
  7331. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7332. continue;
  7333. }
  7334. var changes = event.changes, newChanges = [];
  7335. copy.push({changes: newChanges});
  7336. for (var j = 0; j < changes.length; ++j) {
  7337. var change = changes[j], m;
  7338. newChanges.push({from: change.from, to: change.to, text: change.text});
  7339. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7340. if (indexOf(newGroup, Number(m[1])) > -1) {
  7341. lst(newChanges)[prop] = change[prop];
  7342. delete change[prop];
  7343. }
  7344. }
  7345. }
  7346. }
  7347. return copy;
  7348. }
  7349. // Rebasing/resetting history to deal with externally-sourced changes
  7350. function rebaseHistSelSingle(pos, from, to, diff) {
  7351. if (to < pos.line) {
  7352. pos.line += diff;
  7353. } else if (from < pos.line) {
  7354. pos.line = from;
  7355. pos.ch = 0;
  7356. }
  7357. }
  7358. // Tries to rebase an array of history events given a change in the
  7359. // document. If the change touches the same lines as the event, the
  7360. // event, and everything 'behind' it, is discarded. If the change is
  7361. // before the event, the event's positions are updated. Uses a
  7362. // copy-on-write scheme for the positions, to avoid having to
  7363. // reallocate them all on every rebase, but also avoid problems with
  7364. // shared position objects being unsafely updated.
  7365. function rebaseHistArray(array, from, to, diff) {
  7366. for (var i = 0; i < array.length; ++i) {
  7367. var sub = array[i], ok = true;
  7368. if (sub.ranges) {
  7369. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7370. for (var j = 0; j < sub.ranges.length; j++) {
  7371. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7372. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7373. }
  7374. continue;
  7375. }
  7376. for (var j = 0; j < sub.changes.length; ++j) {
  7377. var cur = sub.changes[j];
  7378. if (to < cur.from.line) {
  7379. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7380. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7381. } else if (from <= cur.to.line) {
  7382. ok = false;
  7383. break;
  7384. }
  7385. }
  7386. if (!ok) {
  7387. array.splice(0, i + 1);
  7388. i = 0;
  7389. }
  7390. }
  7391. }
  7392. function rebaseHist(hist, change) {
  7393. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7394. rebaseHistArray(hist.done, from, to, diff);
  7395. rebaseHistArray(hist.undone, from, to, diff);
  7396. }
  7397. // EVENT UTILITIES
  7398. // Due to the fact that we still support jurassic IE versions, some
  7399. // compatibility wrappers are needed.
  7400. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  7401. if (e.preventDefault) e.preventDefault();
  7402. else e.returnValue = false;
  7403. };
  7404. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  7405. if (e.stopPropagation) e.stopPropagation();
  7406. else e.cancelBubble = true;
  7407. };
  7408. function e_defaultPrevented(e) {
  7409. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7410. }
  7411. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  7412. function e_target(e) {return e.target || e.srcElement;}
  7413. function e_button(e) {
  7414. var b = e.which;
  7415. if (b == null) {
  7416. if (e.button & 1) b = 1;
  7417. else if (e.button & 2) b = 3;
  7418. else if (e.button & 4) b = 2;
  7419. }
  7420. if (mac && e.ctrlKey && b == 1) b = 3;
  7421. return b;
  7422. }
  7423. // EVENT HANDLING
  7424. // Lightweight event framework. on/off also work on DOM nodes,
  7425. // registering native DOM handlers.
  7426. var on = CodeMirror.on = function(emitter, type, f) {
  7427. if (emitter.addEventListener)
  7428. emitter.addEventListener(type, f, false);
  7429. else if (emitter.attachEvent)
  7430. emitter.attachEvent("on" + type, f);
  7431. else {
  7432. var map = emitter._handlers || (emitter._handlers = {});
  7433. var arr = map[type] || (map[type] = []);
  7434. arr.push(f);
  7435. }
  7436. };
  7437. var noHandlers = []
  7438. function getHandlers(emitter, type, copy) {
  7439. var arr = emitter._handlers && emitter._handlers[type]
  7440. if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
  7441. else return arr || noHandlers
  7442. }
  7443. var off = CodeMirror.off = function(emitter, type, f) {
  7444. if (emitter.removeEventListener)
  7445. emitter.removeEventListener(type, f, false);
  7446. else if (emitter.detachEvent)
  7447. emitter.detachEvent("on" + type, f);
  7448. else {
  7449. var handlers = getHandlers(emitter, type, false)
  7450. for (var i = 0; i < handlers.length; ++i)
  7451. if (handlers[i] == f) { handlers.splice(i, 1); break; }
  7452. }
  7453. };
  7454. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  7455. var handlers = getHandlers(emitter, type, true)
  7456. if (!handlers.length) return;
  7457. var args = Array.prototype.slice.call(arguments, 2);
  7458. for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
  7459. };
  7460. var orphanDelayedCallbacks = null;
  7461. // Often, we want to signal events at a point where we are in the
  7462. // middle of some work, but don't want the handler to start calling
  7463. // other methods on the editor, which might be in an inconsistent
  7464. // state or simply not expect any other events to happen.
  7465. // signalLater looks whether there are any handlers, and schedules
  7466. // them to be executed when the last operation ends, or, if no
  7467. // operation is active, when a timeout fires.
  7468. function signalLater(emitter, type /*, values...*/) {
  7469. var arr = getHandlers(emitter, type, false)
  7470. if (!arr.length) return;
  7471. var args = Array.prototype.slice.call(arguments, 2), list;
  7472. if (operationGroup) {
  7473. list = operationGroup.delayedCallbacks;
  7474. } else if (orphanDelayedCallbacks) {
  7475. list = orphanDelayedCallbacks;
  7476. } else {
  7477. list = orphanDelayedCallbacks = [];
  7478. setTimeout(fireOrphanDelayed, 0);
  7479. }
  7480. function bnd(f) {return function(){f.apply(null, args);};};
  7481. for (var i = 0; i < arr.length; ++i)
  7482. list.push(bnd(arr[i]));
  7483. }
  7484. function fireOrphanDelayed() {
  7485. var delayed = orphanDelayedCallbacks;
  7486. orphanDelayedCallbacks = null;
  7487. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7488. }
  7489. // The DOM events that CodeMirror handles can be overridden by
  7490. // registering a (non-DOM) handler on the editor for the event name,
  7491. // and preventDefault-ing the event in that handler.
  7492. function signalDOMEvent(cm, e, override) {
  7493. if (typeof e == "string")
  7494. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  7495. signal(cm, override || e.type, cm, e);
  7496. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7497. }
  7498. function signalCursorActivity(cm) {
  7499. var arr = cm._handlers && cm._handlers.cursorActivity;
  7500. if (!arr) return;
  7501. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7502. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7503. set.push(arr[i]);
  7504. }
  7505. function hasHandler(emitter, type) {
  7506. return getHandlers(emitter, type).length > 0
  7507. }
  7508. // Add on and off methods to a constructor's prototype, to make
  7509. // registering events on such objects more convenient.
  7510. function eventMixin(ctor) {
  7511. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7512. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7513. }
  7514. // MISC UTILITIES
  7515. // Number of pixels added to scroller and sizer to hide scrollbar
  7516. var scrollerGap = 30;
  7517. // Returned or thrown by various protocols to signal 'I'm not
  7518. // handling this'.
  7519. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  7520. // Reused option objects for setSelection & friends
  7521. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  7522. function Delayed() {this.id = null;}
  7523. Delayed.prototype.set = function(ms, f) {
  7524. clearTimeout(this.id);
  7525. this.id = setTimeout(f, ms);
  7526. };
  7527. // Counts the column offset in a string, taking tabs into account.
  7528. // Used mostly to find indentation.
  7529. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  7530. if (end == null) {
  7531. end = string.search(/[^\s\u00a0]/);
  7532. if (end == -1) end = string.length;
  7533. }
  7534. for (var i = startIndex || 0, n = startValue || 0;;) {
  7535. var nextTab = string.indexOf("\t", i);
  7536. if (nextTab < 0 || nextTab >= end)
  7537. return n + (end - i);
  7538. n += nextTab - i;
  7539. n += tabSize - (n % tabSize);
  7540. i = nextTab + 1;
  7541. }
  7542. };
  7543. // The inverse of countColumn -- find the offset that corresponds to
  7544. // a particular column.
  7545. var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
  7546. for (var pos = 0, col = 0;;) {
  7547. var nextTab = string.indexOf("\t", pos);
  7548. if (nextTab == -1) nextTab = string.length;
  7549. var skipped = nextTab - pos;
  7550. if (nextTab == string.length || col + skipped >= goal)
  7551. return pos + Math.min(skipped, goal - col);
  7552. col += nextTab - pos;
  7553. col += tabSize - (col % tabSize);
  7554. pos = nextTab + 1;
  7555. if (col >= goal) return pos;
  7556. }
  7557. }
  7558. var spaceStrs = [""];
  7559. function spaceStr(n) {
  7560. while (spaceStrs.length <= n)
  7561. spaceStrs.push(lst(spaceStrs) + " ");
  7562. return spaceStrs[n];
  7563. }
  7564. function lst(arr) { return arr[arr.length-1]; }
  7565. var selectInput = function(node) { node.select(); };
  7566. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7567. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7568. else if (ie) // Suppress mysterious IE10 errors
  7569. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  7570. function indexOf(array, elt) {
  7571. for (var i = 0; i < array.length; ++i)
  7572. if (array[i] == elt) return i;
  7573. return -1;
  7574. }
  7575. function map(array, f) {
  7576. var out = [];
  7577. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7578. return out;
  7579. }
  7580. function nothing() {}
  7581. function createObj(base, props) {
  7582. var inst;
  7583. if (Object.create) {
  7584. inst = Object.create(base);
  7585. } else {
  7586. nothing.prototype = base;
  7587. inst = new nothing();
  7588. }
  7589. if (props) copyObj(props, inst);
  7590. return inst;
  7591. };
  7592. function copyObj(obj, target, overwrite) {
  7593. if (!target) target = {};
  7594. for (var prop in obj)
  7595. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7596. target[prop] = obj[prop];
  7597. return target;
  7598. }
  7599. function bind(f) {
  7600. var args = Array.prototype.slice.call(arguments, 1);
  7601. return function(){return f.apply(null, args);};
  7602. }
  7603. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7604. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  7605. return /\w/.test(ch) || ch > "\x80" &&
  7606. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7607. };
  7608. function isWordChar(ch, helper) {
  7609. if (!helper) return isWordCharBasic(ch);
  7610. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7611. return helper.test(ch);
  7612. }
  7613. function isEmpty(obj) {
  7614. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7615. return true;
  7616. }
  7617. // Extending unicode characters. A series of a non-extending char +
  7618. // any number of extending chars is treated as a single unit as far
  7619. // as editing and measuring is concerned. This is not fully correct,
  7620. // since some scripts/fonts/browsers also treat other configurations
  7621. // of code points as a group.
  7622. 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]/;
  7623. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7624. // DOM UTILITIES
  7625. function elt(tag, content, className, style) {
  7626. var e = document.createElement(tag);
  7627. if (className) e.className = className;
  7628. if (style) e.style.cssText = style;
  7629. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7630. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7631. return e;
  7632. }
  7633. var range;
  7634. if (document.createRange) range = function(node, start, end, endNode) {
  7635. var r = document.createRange();
  7636. r.setEnd(endNode || node, end);
  7637. r.setStart(node, start);
  7638. return r;
  7639. };
  7640. else range = function(node, start, end) {
  7641. var r = document.body.createTextRange();
  7642. try { r.moveToElementText(node.parentNode); }
  7643. catch(e) { return r; }
  7644. r.collapse(true);
  7645. r.moveEnd("character", end);
  7646. r.moveStart("character", start);
  7647. return r;
  7648. };
  7649. function removeChildren(e) {
  7650. for (var count = e.childNodes.length; count > 0; --count)
  7651. e.removeChild(e.firstChild);
  7652. return e;
  7653. }
  7654. function removeChildrenAndAdd(parent, e) {
  7655. return removeChildren(parent).appendChild(e);
  7656. }
  7657. var contains = CodeMirror.contains = function(parent, child) {
  7658. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7659. child = child.parentNode;
  7660. if (parent.contains)
  7661. return parent.contains(child);
  7662. do {
  7663. if (child.nodeType == 11) child = child.host;
  7664. if (child == parent) return true;
  7665. } while (child = child.parentNode);
  7666. };
  7667. function activeElt() {
  7668. var activeElement = document.activeElement;
  7669. while (activeElement && activeElement.root && activeElement.root.activeElement)
  7670. activeElement = activeElement.root.activeElement;
  7671. return activeElement;
  7672. }
  7673. // Older versions of IE throws unspecified error when touching
  7674. // document.activeElement in some cases (during loading, in iframe)
  7675. if (ie && ie_version < 11) activeElt = function() {
  7676. try { return document.activeElement; }
  7677. catch(e) { return document.body; }
  7678. };
  7679. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7680. var rmClass = CodeMirror.rmClass = function(node, cls) {
  7681. var current = node.className;
  7682. var match = classTest(cls).exec(current);
  7683. if (match) {
  7684. var after = current.slice(match.index + match[0].length);
  7685. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7686. }
  7687. };
  7688. var addClass = CodeMirror.addClass = function(node, cls) {
  7689. var current = node.className;
  7690. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7691. };
  7692. function joinClasses(a, b) {
  7693. var as = a.split(" ");
  7694. for (var i = 0; i < as.length; i++)
  7695. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7696. return b;
  7697. }
  7698. // WINDOW-WIDE EVENTS
  7699. // These must be handled carefully, because naively registering a
  7700. // handler for each editor will cause the editors to never be
  7701. // garbage collected.
  7702. function forEachCodeMirror(f) {
  7703. if (!document.body.getElementsByClassName) return;
  7704. var byClass = document.body.getElementsByClassName("CodeMirror");
  7705. for (var i = 0; i < byClass.length; i++) {
  7706. var cm = byClass[i].CodeMirror;
  7707. if (cm) f(cm);
  7708. }
  7709. }
  7710. var globalsRegistered = false;
  7711. function ensureGlobalHandlers() {
  7712. if (globalsRegistered) return;
  7713. registerGlobalHandlers();
  7714. globalsRegistered = true;
  7715. }
  7716. function registerGlobalHandlers() {
  7717. // When the window resizes, we need to refresh active editors.
  7718. var resizeTimer;
  7719. on(window, "resize", function() {
  7720. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  7721. resizeTimer = null;
  7722. forEachCodeMirror(onResize);
  7723. }, 100);
  7724. });
  7725. // When the window loses focus, we want to show the editor as blurred
  7726. on(window, "blur", function() {
  7727. forEachCodeMirror(onBlur);
  7728. });
  7729. }
  7730. // FEATURE DETECTION
  7731. // Detect drag-and-drop
  7732. var dragAndDrop = function() {
  7733. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7734. // couldn't get it to work yet.
  7735. if (ie && ie_version < 9) return false;
  7736. var div = elt('div');
  7737. return "draggable" in div || "dragDrop" in div;
  7738. }();
  7739. var zwspSupported;
  7740. function zeroWidthElement(measure) {
  7741. if (zwspSupported == null) {
  7742. var test = elt("span", "\u200b");
  7743. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7744. if (measure.firstChild.offsetHeight != 0)
  7745. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7746. }
  7747. var node = zwspSupported ? elt("span", "\u200b") :
  7748. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7749. node.setAttribute("cm-text", "");
  7750. return node;
  7751. }
  7752. // Feature-detect IE's crummy client rect reporting for bidi text
  7753. var badBidiRects;
  7754. function hasBadBidiRects(measure) {
  7755. if (badBidiRects != null) return badBidiRects;
  7756. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7757. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7758. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7759. removeChildren(measure);
  7760. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7761. return badBidiRects = (r1.right - r0.right < 3);
  7762. }
  7763. // See if "".split is the broken IE version, if so, provide an
  7764. // alternative way to split lines.
  7765. var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7766. var pos = 0, result = [], l = string.length;
  7767. while (pos <= l) {
  7768. var nl = string.indexOf("\n", pos);
  7769. if (nl == -1) nl = string.length;
  7770. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7771. var rt = line.indexOf("\r");
  7772. if (rt != -1) {
  7773. result.push(line.slice(0, rt));
  7774. pos += rt + 1;
  7775. } else {
  7776. result.push(line);
  7777. pos = nl + 1;
  7778. }
  7779. }
  7780. return result;
  7781. } : function(string){return string.split(/\r\n?|\n/);};
  7782. var hasSelection = window.getSelection ? function(te) {
  7783. try { return te.selectionStart != te.selectionEnd; }
  7784. catch(e) { return false; }
  7785. } : function(te) {
  7786. try {var range = te.ownerDocument.selection.createRange();}
  7787. catch(e) {}
  7788. if (!range || range.parentElement() != te) return false;
  7789. return range.compareEndPoints("StartToEnd", range) != 0;
  7790. };
  7791. var hasCopyEvent = (function() {
  7792. var e = elt("div");
  7793. if ("oncopy" in e) return true;
  7794. e.setAttribute("oncopy", "return;");
  7795. return typeof e.oncopy == "function";
  7796. })();
  7797. var badZoomedRects = null;
  7798. function hasBadZoomedRects(measure) {
  7799. if (badZoomedRects != null) return badZoomedRects;
  7800. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7801. var normal = node.getBoundingClientRect();
  7802. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7803. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7804. }
  7805. // KEY NAMES
  7806. var keyNames = CodeMirror.keyNames = {
  7807. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7808. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7809. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7810. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  7811. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  7812. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7813. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7814. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7815. };
  7816. (function() {
  7817. // Number keys
  7818. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7819. // Alphabetic keys
  7820. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7821. // Function keys
  7822. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7823. })();
  7824. // BIDI HELPERS
  7825. function iterateBidiSections(order, from, to, f) {
  7826. if (!order) return f(from, to, "ltr");
  7827. var found = false;
  7828. for (var i = 0; i < order.length; ++i) {
  7829. var part = order[i];
  7830. if (part.from < to && part.to > from || from == to && part.to == from) {
  7831. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7832. found = true;
  7833. }
  7834. }
  7835. if (!found) f(from, to, "ltr");
  7836. }
  7837. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7838. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7839. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7840. function lineRight(line) {
  7841. var order = getOrder(line);
  7842. if (!order) return line.text.length;
  7843. return bidiRight(lst(order));
  7844. }
  7845. function lineStart(cm, lineN) {
  7846. var line = getLine(cm.doc, lineN);
  7847. var visual = visualLine(line);
  7848. if (visual != line) lineN = lineNo(visual);
  7849. var order = getOrder(visual);
  7850. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7851. return Pos(lineN, ch);
  7852. }
  7853. function lineEnd(cm, lineN) {
  7854. var merged, line = getLine(cm.doc, lineN);
  7855. while (merged = collapsedSpanAtEnd(line)) {
  7856. line = merged.find(1, true).line;
  7857. lineN = null;
  7858. }
  7859. var order = getOrder(line);
  7860. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7861. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7862. }
  7863. function lineStartSmart(cm, pos) {
  7864. var start = lineStart(cm, pos.line);
  7865. var line = getLine(cm.doc, start.line);
  7866. var order = getOrder(line);
  7867. if (!order || order[0].level == 0) {
  7868. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7869. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7870. return Pos(start.line, inWS ? 0 : firstNonWS);
  7871. }
  7872. return start;
  7873. }
  7874. function compareBidiLevel(order, a, b) {
  7875. var linedir = order[0].level;
  7876. if (a == linedir) return true;
  7877. if (b == linedir) return false;
  7878. return a < b;
  7879. }
  7880. var bidiOther;
  7881. function getBidiPartAt(order, pos) {
  7882. bidiOther = null;
  7883. for (var i = 0, found; i < order.length; ++i) {
  7884. var cur = order[i];
  7885. if (cur.from < pos && cur.to > pos) return i;
  7886. if ((cur.from == pos || cur.to == pos)) {
  7887. if (found == null) {
  7888. found = i;
  7889. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7890. if (cur.from != cur.to) bidiOther = found;
  7891. return i;
  7892. } else {
  7893. if (cur.from != cur.to) bidiOther = i;
  7894. return found;
  7895. }
  7896. }
  7897. }
  7898. return found;
  7899. }
  7900. function moveInLine(line, pos, dir, byUnit) {
  7901. if (!byUnit) return pos + dir;
  7902. do pos += dir;
  7903. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7904. return pos;
  7905. }
  7906. // This is needed in order to move 'visually' through bi-directional
  7907. // text -- i.e., pressing left should make the cursor go left, even
  7908. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7909. // LTR text touch each other. This often requires the cursor offset
  7910. // to move more than one unit, in order to visually move one unit.
  7911. function moveVisually(line, start, dir, byUnit) {
  7912. var bidi = getOrder(line);
  7913. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7914. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7915. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7916. for (;;) {
  7917. if (target > part.from && target < part.to) return target;
  7918. if (target == part.from || target == part.to) {
  7919. if (getBidiPartAt(bidi, target) == pos) return target;
  7920. part = bidi[pos += dir];
  7921. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7922. } else {
  7923. part = bidi[pos += dir];
  7924. if (!part) return null;
  7925. if ((dir > 0) == part.level % 2)
  7926. target = moveInLine(line, part.to, -1, byUnit);
  7927. else
  7928. target = moveInLine(line, part.from, 1, byUnit);
  7929. }
  7930. }
  7931. }
  7932. function moveLogically(line, start, dir, byUnit) {
  7933. var target = start + dir;
  7934. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7935. return target < 0 || target > line.text.length ? null : target;
  7936. }
  7937. // Bidirectional ordering algorithm
  7938. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7939. // that this (partially) implements.
  7940. // One-char codes used for character types:
  7941. // L (L): Left-to-Right
  7942. // R (R): Right-to-Left
  7943. // r (AL): Right-to-Left Arabic
  7944. // 1 (EN): European Number
  7945. // + (ES): European Number Separator
  7946. // % (ET): European Number Terminator
  7947. // n (AN): Arabic Number
  7948. // , (CS): Common Number Separator
  7949. // m (NSM): Non-Spacing Mark
  7950. // b (BN): Boundary Neutral
  7951. // s (B): Paragraph Separator
  7952. // t (S): Segment Separator
  7953. // w (WS): Whitespace
  7954. // N (ON): Other Neutrals
  7955. // Returns null if characters are ordered as they appear
  7956. // (left-to-right), or an array of sections ({from, to, level}
  7957. // objects) in the order in which they occur visually.
  7958. var bidiOrdering = (function() {
  7959. // Character types for codepoints 0 to 0xff
  7960. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7961. // Character types for codepoints 0x600 to 0x6ff
  7962. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7963. function charType(code) {
  7964. if (code <= 0xf7) return lowTypes.charAt(code);
  7965. else if (0x590 <= code && code <= 0x5f4) return "R";
  7966. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7967. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7968. else if (0x2000 <= code && code <= 0x200b) return "w";
  7969. else if (code == 0x200c) return "b";
  7970. else return "L";
  7971. }
  7972. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7973. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7974. // Browsers seem to always treat the boundaries of block elements as being L.
  7975. var outerType = "L";
  7976. function BidiSpan(level, from, to) {
  7977. this.level = level;
  7978. this.from = from; this.to = to;
  7979. }
  7980. return function(str) {
  7981. if (!bidiRE.test(str)) return false;
  7982. var len = str.length, types = [];
  7983. for (var i = 0, type; i < len; ++i)
  7984. types.push(type = charType(str.charCodeAt(i)));
  7985. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7986. // change the type of the NSM to the type of the previous
  7987. // character. If the NSM is at the start of the level run, it will
  7988. // get the type of sor.
  7989. for (var i = 0, prev = outerType; i < len; ++i) {
  7990. var type = types[i];
  7991. if (type == "m") types[i] = prev;
  7992. else prev = type;
  7993. }
  7994. // W2. Search backwards from each instance of a European number
  7995. // until the first strong type (R, L, AL, or sor) is found. If an
  7996. // AL is found, change the type of the European number to Arabic
  7997. // number.
  7998. // W3. Change all ALs to R.
  7999. for (var i = 0, cur = outerType; i < len; ++i) {
  8000. var type = types[i];
  8001. if (type == "1" && cur == "r") types[i] = "n";
  8002. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  8003. }
  8004. // W4. A single European separator between two European numbers
  8005. // changes to a European number. A single common separator between
  8006. // two numbers of the same type changes to that type.
  8007. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  8008. var type = types[i];
  8009. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  8010. else if (type == "," && prev == types[i+1] &&
  8011. (prev == "1" || prev == "n")) types[i] = prev;
  8012. prev = type;
  8013. }
  8014. // W5. A sequence of European terminators adjacent to European
  8015. // numbers changes to all European numbers.
  8016. // W6. Otherwise, separators and terminators change to Other
  8017. // Neutral.
  8018. for (var i = 0; i < len; ++i) {
  8019. var type = types[i];
  8020. if (type == ",") types[i] = "N";
  8021. else if (type == "%") {
  8022. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  8023. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  8024. for (var j = i; j < end; ++j) types[j] = replace;
  8025. i = end - 1;
  8026. }
  8027. }
  8028. // W7. Search backwards from each instance of a European number
  8029. // until the first strong type (R, L, or sor) is found. If an L is
  8030. // found, then change the type of the European number to L.
  8031. for (var i = 0, cur = outerType; i < len; ++i) {
  8032. var type = types[i];
  8033. if (cur == "L" && type == "1") types[i] = "L";
  8034. else if (isStrong.test(type)) cur = type;
  8035. }
  8036. // N1. A sequence of neutrals takes the direction of the
  8037. // surrounding strong text if the text on both sides has the same
  8038. // direction. European and Arabic numbers act as if they were R in
  8039. // terms of their influence on neutrals. Start-of-level-run (sor)
  8040. // and end-of-level-run (eor) are used at level run boundaries.
  8041. // N2. Any remaining neutrals take the embedding direction.
  8042. for (var i = 0; i < len; ++i) {
  8043. if (isNeutral.test(types[i])) {
  8044. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  8045. var before = (i ? types[i-1] : outerType) == "L";
  8046. var after = (end < len ? types[end] : outerType) == "L";
  8047. var replace = before || after ? "L" : "R";
  8048. for (var j = i; j < end; ++j) types[j] = replace;
  8049. i = end - 1;
  8050. }
  8051. }
  8052. // Here we depart from the documented algorithm, in order to avoid
  8053. // building up an actual levels array. Since there are only three
  8054. // levels (0, 1, 2) in an implementation that doesn't take
  8055. // explicit embedding into account, we can build up the order on
  8056. // the fly, without following the level-based algorithm.
  8057. var order = [], m;
  8058. for (var i = 0; i < len;) {
  8059. if (countsAsLeft.test(types[i])) {
  8060. var start = i;
  8061. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  8062. order.push(new BidiSpan(0, start, i));
  8063. } else {
  8064. var pos = i, at = order.length;
  8065. for (++i; i < len && types[i] != "L"; ++i) {}
  8066. for (var j = pos; j < i;) {
  8067. if (countsAsNum.test(types[j])) {
  8068. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  8069. var nstart = j;
  8070. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  8071. order.splice(at, 0, new BidiSpan(2, nstart, j));
  8072. pos = j;
  8073. } else ++j;
  8074. }
  8075. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  8076. }
  8077. }
  8078. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  8079. order[0].from = m[0].length;
  8080. order.unshift(new BidiSpan(0, 0, m[0].length));
  8081. }
  8082. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  8083. lst(order).to -= m[0].length;
  8084. order.push(new BidiSpan(0, len - m[0].length, len));
  8085. }
  8086. if (order[0].level == 2)
  8087. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  8088. if (order[0].level != lst(order).level)
  8089. order.push(new BidiSpan(order[0].level, len, len));
  8090. return order;
  8091. };
  8092. })();
  8093. // THE END
  8094. CodeMirror.version = "5.17.0";
  8095. return CodeMirror;
  8096. });