codemirror.js 287 KB

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