codemirror.js 306 KB

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