codemirror.js 313 KB

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