codemirror.js 339 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782
  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. var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
  22. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
  23. var ie = ie_upto10 || ie_11up;
  24. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  25. var webkit = /WebKit\//.test(navigator.userAgent);
  26. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  27. var chrome = /Chrome\//.test(navigator.userAgent);
  28. var presto = /Opera\//.test(navigator.userAgent);
  29. var safari = /Apple Computer/.test(navigator.vendor);
  30. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  31. var phantom = /PhantomJS/.test(navigator.userAgent);
  32. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  33. // This is woefully incomplete. Suggestions for alternative methods welcome.
  34. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
  35. var mac = ios || /Mac/.test(navigator.platform);
  36. var windows = /win/i.test(navigator.platform);
  37. var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
  38. if (presto_version) presto_version = Number(presto_version[1]);
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  42. var captureRightClick = gecko || (ie && ie_version >= 9);
  43. // Optimize some code when these features are not used.
  44. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  45. // EDITOR CONSTRUCTOR
  46. // A CodeMirror instance represents an editor. This is the object
  47. // that user code is usually dealing with.
  48. function CodeMirror(place, options) {
  49. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  50. this.options = options = options ? copyObj(options) : {};
  51. // Determine effective options based on given values and defaults.
  52. copyObj(defaults, options, false);
  53. setGuttersForLineNumbers(options);
  54. var doc = options.value;
  55. if (typeof doc == "string") doc = new Doc(doc, options.mode);
  56. this.doc = doc;
  57. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  58. var display = this.display = new Display(place, doc, input);
  59. display.wrapper.CodeMirror = this;
  60. updateGutters(this);
  61. themeChanged(this);
  62. if (options.lineWrapping)
  63. this.display.wrapper.className += " CodeMirror-wrap";
  64. if (options.autofocus && !mobile) display.input.focus();
  65. initScrollbars(this);
  66. this.state = {
  67. keyMaps: [], // stores maps added by addKeyMap
  68. overlays: [], // highlighting overlays, as added by addOverlay
  69. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  70. overwrite: false,
  71. delayingBlurEvent: false,
  72. focused: false,
  73. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  74. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  75. draggingText: false,
  76. highlight: new Delayed(), // stores highlight worker timeout
  77. keySeq: null, // Unfinished key sequence
  78. specialChars: null
  79. };
  80. var cm = this;
  81. // Override magic textarea content restore that IE sometimes does
  82. // on our hidden textarea on reload
  83. if (ie && ie_version < 11) setTimeout(function () { cm.display.input.reset(true); }, 20);
  84. registerEventHandlers(this);
  85. ensureGlobalHandlers();
  86. startOperation(this);
  87. this.curOp.forceUpdate = true;
  88. attachDoc(this, doc);
  89. if ((options.autofocus && !mobile) || cm.hasFocus())
  90. setTimeout(bind(onFocus, this), 20);
  91. else
  92. onBlur(this);
  93. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  94. optionHandlers[opt](this, options[opt], Init);
  95. maybeUpdateLineNumberWidth(this);
  96. if (options.finishInit) options.finishInit(this);
  97. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  98. endOperation(this);
  99. // Suppress optimizelegibility in Webkit, since it breaks text
  100. // measuring on line wrapping boundaries.
  101. if (webkit && options.lineWrapping &&
  102. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  103. display.lineDiv.style.textRendering = "auto";
  104. }
  105. // DISPLAY CONSTRUCTOR
  106. // The display handles the DOM integration, both for input reading
  107. // and content drawing. It holds references to DOM nodes and
  108. // display-related state.
  109. function Display(place, doc, input) {
  110. var d = this;
  111. this.input = input;
  112. // Covers bottom-right square when both scrollbars are present.
  113. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  114. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  115. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  116. // and h scrollbar is present.
  117. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  118. d.gutterFiller.setAttribute("cm-not-content", "true");
  119. // Will contain the actual code, positioned to cover the viewport.
  120. d.lineDiv = elt("div", null, "CodeMirror-code");
  121. // Elements are added to these to represent selection and cursors.
  122. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  123. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  124. // A visibility: hidden element used to find the size of things.
  125. d.measure = elt("div", null, "CodeMirror-measure");
  126. // When lines outside of the viewport are measured, they are drawn in this.
  127. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  128. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  129. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  130. null, "position: relative; outline: none");
  131. // Moved around its parent to cover visible view.
  132. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  133. // Set to the height of the document, allowing scrolling.
  134. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  135. d.sizerWidth = null;
  136. // Behavior of elts with overflow: auto and padding is
  137. // inconsistent across browsers. This is used to ensure the
  138. // scrollable area is big enough.
  139. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  140. // Will contain the gutters, if any.
  141. d.gutters = elt("div", null, "CodeMirror-gutters");
  142. d.lineGutter = null;
  143. // Actual scrollable element.
  144. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  145. d.scroller.setAttribute("tabIndex", "-1");
  146. // The element in which the editor lives.
  147. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  148. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  149. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  150. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  151. if (place) {
  152. if (place.appendChild) place.appendChild(d.wrapper);
  153. else place(d.wrapper);
  154. }
  155. // Current rendered range (may be bigger than the view window).
  156. d.viewFrom = d.viewTo = doc.first;
  157. d.reportedViewFrom = d.reportedViewTo = doc.first;
  158. // Information about the rendered lines.
  159. d.view = [];
  160. d.renderedView = null;
  161. // Holds info about a single rendered line when it was rendered
  162. // for measurement, while not in view.
  163. d.externalMeasured = null;
  164. // Empty space (in pixels) above the view
  165. d.viewOffset = 0;
  166. d.lastWrapHeight = d.lastWrapWidth = 0;
  167. d.updateLineNumbers = null;
  168. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  169. d.scrollbarsClipped = false;
  170. // Used to only resize the line number gutter when necessary (when
  171. // the amount of lines crosses a boundary that makes its width change)
  172. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  173. // Set to true when a non-horizontal-scrolling line widget is
  174. // added. As an optimization, line widget aligning is skipped when
  175. // this is false.
  176. d.alignWidgets = false;
  177. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  178. // Tracks the maximum line length so that the horizontal scrollbar
  179. // can be kept static when scrolling.
  180. d.maxLine = null;
  181. d.maxLineLength = 0;
  182. d.maxLineChanged = false;
  183. // Used for measuring wheel scrolling granularity
  184. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  185. // True when shift is held down.
  186. d.shift = false;
  187. // Used to track whether anything happened since the context menu
  188. // was opened.
  189. d.selForContextMenu = null;
  190. d.activeTouch = null;
  191. input.init(d);
  192. }
  193. // STATE UPDATES
  194. // Used to get the editor into a consistent state again when options change.
  195. function loadMode(cm) {
  196. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  197. resetModeState(cm);
  198. }
  199. function resetModeState(cm) {
  200. cm.doc.iter(function (line) {
  201. if (line.stateAfter) line.stateAfter = null;
  202. if (line.styles) line.styles = null;
  203. });
  204. cm.doc.frontier = cm.doc.first;
  205. startWorker(cm, 100);
  206. cm.state.modeGen++;
  207. if (cm.curOp) regChange(cm);
  208. }
  209. function wrappingChanged(cm) {
  210. if (cm.options.lineWrapping) {
  211. addClass(cm.display.wrapper, "CodeMirror-wrap");
  212. cm.display.sizer.style.minWidth = "";
  213. cm.display.sizerWidth = null;
  214. } else {
  215. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  216. findMaxLine(cm);
  217. }
  218. estimateLineHeights(cm);
  219. regChange(cm);
  220. clearCaches(cm);
  221. setTimeout(function () { updateScrollbars(cm); }, 100);
  222. }
  223. // Returns a function that estimates the height of a line, to use as
  224. // first approximation until the line becomes visible (and is thus
  225. // properly measurable).
  226. function estimateHeight(cm) {
  227. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  228. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  229. return function (line) {
  230. if (lineIsHidden(cm.doc, line)) return 0;
  231. var widgetsHeight = 0;
  232. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  233. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  234. }
  235. if (wrapping)
  236. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  237. else
  238. return widgetsHeight + th;
  239. };
  240. }
  241. function estimateLineHeights(cm) {
  242. var doc = cm.doc, est = estimateHeight(cm);
  243. doc.iter(function (line) {
  244. var estHeight = est(line);
  245. if (estHeight != line.height) updateLineHeight(line, estHeight);
  246. });
  247. }
  248. function themeChanged(cm) {
  249. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  250. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  251. clearCaches(cm);
  252. }
  253. function guttersChanged(cm) {
  254. updateGutters(cm);
  255. regChange(cm);
  256. setTimeout(function () { alignHorizontally(cm); }, 20);
  257. }
  258. // Rebuild the gutter elements, ensure the margin to the left of the
  259. // code matches their width.
  260. function updateGutters(cm) {
  261. var gutters = cm.display.gutters, specs = cm.options.gutters;
  262. removeChildren(gutters);
  263. for (var i = 0; i < specs.length; ++i) {
  264. var gutterClass = specs[i];
  265. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  266. if (gutterClass == "CodeMirror-linenumbers") {
  267. cm.display.lineGutter = gElt;
  268. gElt.style.width = (cm.display.lineNumWidth || 21) + "px";
  269. }
  270. }
  271. gutters.style.display = i ? "" : "none";
  272. updateGutterSpace(cm);
  273. }
  274. function updateGutterSpace(cm) {
  275. var width = cm.display.gutters.offsetWidth;
  276. cm.display.sizer.style.marginLeft = width + "px";
  277. }
  278. // Compute the character length of a line, taking into account
  279. // collapsed ranges (see markText) that might hide parts, and join
  280. // other lines onto it.
  281. function lineLength(line) {
  282. if (line.height == 0) return 0;
  283. var len = line.text.length, merged, cur = line;
  284. while (merged = collapsedSpanAtStart(cur)) {
  285. var found = merged.find(0, true);
  286. cur = found.from.line;
  287. len += found.from.ch - found.to.ch;
  288. }
  289. cur = line;
  290. while (merged = collapsedSpanAtEnd(cur)) {
  291. var found = merged.find(0, true);
  292. len -= cur.text.length - found.from.ch;
  293. cur = found.to.line;
  294. len += cur.text.length - found.to.ch;
  295. }
  296. return len;
  297. }
  298. // Find the longest line in the document.
  299. function findMaxLine(cm) {
  300. var d = cm.display, doc = cm.doc;
  301. d.maxLine = getLine(doc, doc.first);
  302. d.maxLineLength = lineLength(d.maxLine);
  303. d.maxLineChanged = true;
  304. doc.iter(function (line) {
  305. var len = lineLength(line);
  306. if (len > d.maxLineLength) {
  307. d.maxLineLength = len;
  308. d.maxLine = line;
  309. }
  310. });
  311. }
  312. // Make sure the gutters options contains the element
  313. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  314. function setGuttersForLineNumbers(options) {
  315. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  316. if (found == -1 && options.lineNumbers) {
  317. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  318. } else if (found > -1 && !options.lineNumbers) {
  319. options.gutters = options.gutters.slice(0);
  320. options.gutters.splice(found, 1);
  321. }
  322. }
  323. // SCROLLBARS
  324. // Prepare DOM reads needed to update the scrollbars. Done in one
  325. // shot to minimize update/measure roundtrips.
  326. function measureForScrollbars(cm) {
  327. var d = cm.display, gutterW = d.gutters.offsetWidth;
  328. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  329. return {
  330. clientHeight: d.scroller.clientHeight,
  331. viewHeight: d.wrapper.clientHeight,
  332. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  333. viewWidth: d.wrapper.clientWidth,
  334. barLeft: cm.options.fixedGutter ? gutterW : 0,
  335. docHeight: docH,
  336. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  337. nativeBarWidth: d.nativeBarWidth,
  338. gutterWidth: gutterW
  339. };
  340. }
  341. function NativeScrollbars(place, scroll, cm) {
  342. this.cm = cm;
  343. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  344. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  345. place(vert); place(horiz);
  346. on(vert, "scroll", function () {
  347. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  348. });
  349. on(horiz, "scroll", function () {
  350. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  351. });
  352. this.checkedOverlay = false;
  353. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  354. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  355. }
  356. NativeScrollbars.prototype = copyObj({
  357. update: function (measure) {
  358. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  359. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  360. var sWidth = measure.nativeBarWidth;
  361. if (needsV) {
  362. this.vert.style.display = "block";
  363. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  364. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  365. // A bug in IE8 can cause this value to be negative, so guard it.
  366. this.vert.firstChild.style.height =
  367. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  368. } else {
  369. this.vert.style.display = "";
  370. this.vert.firstChild.style.height = "0";
  371. }
  372. if (needsH) {
  373. this.horiz.style.display = "block";
  374. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  375. this.horiz.style.left = measure.barLeft + "px";
  376. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  377. this.horiz.firstChild.style.width =
  378. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  379. } else {
  380. this.horiz.style.display = "";
  381. this.horiz.firstChild.style.width = "0";
  382. }
  383. if (!this.checkedOverlay && measure.clientHeight > 0) {
  384. if (sWidth == 0) this.overlayHack();
  385. this.checkedOverlay = true;
  386. }
  387. return { right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0 };
  388. },
  389. setScrollLeft: function (pos) {
  390. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  391. },
  392. setScrollTop: function (pos) {
  393. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  394. },
  395. overlayHack: function () {
  396. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  397. this.horiz.style.minHeight = this.vert.style.minWidth = w;
  398. var self = this;
  399. var barMouseDown = function (e) {
  400. if (e_target(e) != self.vert && e_target(e) != self.horiz)
  401. operation(self.cm, onMouseDown)(e);
  402. };
  403. on(this.vert, "mousedown", barMouseDown);
  404. on(this.horiz, "mousedown", barMouseDown);
  405. },
  406. clear: function () {
  407. var parent = this.horiz.parentNode;
  408. parent.removeChild(this.horiz);
  409. parent.removeChild(this.vert);
  410. }
  411. }, NativeScrollbars.prototype);
  412. function NullScrollbars() { }
  413. NullScrollbars.prototype = copyObj({
  414. update: function () { return { bottom: 0, right: 0 }; },
  415. setScrollLeft: function () { },
  416. setScrollTop: function () { },
  417. clear: function () { }
  418. }, NullScrollbars.prototype);
  419. CodeMirror.scrollbarModel = { "native": NativeScrollbars, "null": NullScrollbars };
  420. function initScrollbars(cm) {
  421. if (cm.display.scrollbars) {
  422. cm.display.scrollbars.clear();
  423. if (cm.display.scrollbars.addClass)
  424. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  425. }
  426. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function (node) {
  427. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  428. // Prevent clicks in the scrollbars from killing focus
  429. on(node, "mousedown", function () {
  430. if (cm.state.focused) setTimeout(function () { cm.display.input.focus(); }, 0);
  431. });
  432. node.setAttribute("cm-not-content", "true");
  433. }, function (pos, axis) {
  434. if (axis == "horizontal") setScrollLeft(cm, pos);
  435. else setScrollTop(cm, pos);
  436. }, cm);
  437. if (cm.display.scrollbars.addClass)
  438. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  439. }
  440. function updateScrollbars(cm, measure) {
  441. if (!measure) measure = measureForScrollbars(cm);
  442. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  443. updateScrollbarsInner(cm, measure);
  444. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  445. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  446. updateHeightsInViewport(cm);
  447. updateScrollbarsInner(cm, measureForScrollbars(cm));
  448. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  449. }
  450. }
  451. // Re-synchronize the fake scrollbars with the actual size of the
  452. // content.
  453. function updateScrollbarsInner(cm, measure) {
  454. var d = cm.display;
  455. var sizes = d.scrollbars.update(measure);
  456. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  457. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  458. if (sizes.right && sizes.bottom) {
  459. d.scrollbarFiller.style.display = "block";
  460. d.scrollbarFiller.style.height = sizes.bottom + "px";
  461. d.scrollbarFiller.style.width = sizes.right + "px";
  462. } else d.scrollbarFiller.style.display = "";
  463. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  464. d.gutterFiller.style.display = "block";
  465. d.gutterFiller.style.height = sizes.bottom + "px";
  466. d.gutterFiller.style.width = measure.gutterWidth + "px";
  467. } else d.gutterFiller.style.display = "";
  468. }
  469. // Compute the lines that are visible in a given viewport (defaults
  470. // the the current scroll position). viewport may contain top,
  471. // height, and ensure (see op.scrollToPos) properties.
  472. function visibleLines(display, doc, viewport) {
  473. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  474. top = Math.floor(top - paddingTop(display));
  475. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  476. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  477. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  478. // forces those lines into the viewport (if possible).
  479. if (viewport && viewport.ensure) {
  480. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  481. if (ensureFrom < from) {
  482. from = ensureFrom;
  483. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  484. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  485. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  486. to = ensureTo;
  487. }
  488. }
  489. return { from: from, to: Math.max(to, from + 1) };
  490. }
  491. // LINE NUMBERS
  492. // Re-align line numbers and gutter marks to compensate for
  493. // horizontal scrolling.
  494. function alignHorizontally(cm) {
  495. var display = cm.display, view = display.view;
  496. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  497. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  498. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  499. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  500. if (cm.options.fixedGutter && view[i].gutter)
  501. view[i].gutter.style.left = left;
  502. var align = view[i].alignable;
  503. if (align) for (var j = 0; j < align.length; j++)
  504. align[j].style.left = left;
  505. }
  506. if (cm.options.fixedGutter)
  507. display.gutters.style.left = (comp + gutterW) + "px";
  508. }
  509. // Used to ensure that the line number gutter is still the right
  510. // size for the current document size. Returns true when an update
  511. // is needed.
  512. function maybeUpdateLineNumberWidth(cm) {
  513. if (!cm.options.lineNumbers) return false;
  514. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  515. if (last.length != display.lineNumChars) {
  516. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  517. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  518. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  519. display.lineGutter.style.width = "";
  520. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  521. display.lineNumWidth = display.lineNumInnerWidth + padding;
  522. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  523. display.lineGutter.style.width = display.lineNumWidth + "px";
  524. updateGutterSpace(cm);
  525. return true;
  526. }
  527. return false;
  528. }
  529. function lineNumberFor(options, i) {
  530. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  531. }
  532. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  533. // but using getBoundingClientRect to get a sub-pixel-accurate
  534. // result.
  535. function compensateForHScroll(display) {
  536. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  537. }
  538. // DISPLAY DRAWING
  539. function DisplayUpdate(cm, viewport, force) {
  540. var display = cm.display;
  541. this.viewport = viewport;
  542. // Store some values that we'll need later (but don't want to force a relayout for)
  543. this.visible = visibleLines(display, cm.doc, viewport);
  544. this.editorIsHidden = !display.wrapper.offsetWidth;
  545. this.wrapperHeight = display.wrapper.clientHeight;
  546. this.wrapperWidth = display.wrapper.clientWidth;
  547. this.oldDisplayWidth = displayWidth(cm);
  548. this.force = force;
  549. this.dims = getDimensions(cm);
  550. this.events = [];
  551. }
  552. DisplayUpdate.prototype.signal = function (emitter, type) {
  553. if (hasHandler(emitter, type))
  554. this.events.push(arguments);
  555. };
  556. DisplayUpdate.prototype.finish = function () {
  557. for (var i = 0; i < this.events.length; i++)
  558. signal.apply(null, this.events[i]);
  559. };
  560. function maybeClipScrollbars(cm) {
  561. var display = cm.display;
  562. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  563. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  564. display.heightForcer.style.height = scrollGap(cm) + "px";
  565. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  566. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  567. display.scrollbarsClipped = true;
  568. }
  569. }
  570. // Does the actual updating of the line display. Bails out
  571. // (returning false) when there is nothing to be done and forced is
  572. // false.
  573. function updateDisplayIfNeeded(cm, update) {
  574. var display = cm.display, doc = cm.doc;
  575. // if (update.editorIsHidden) {
  576. // resetView(cm);
  577. // return false;
  578. // }
  579. // Bail out if the visible area is already rendered and nothing changed.
  580. if (!update.force &&
  581. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  582. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  583. display.renderedView == display.view && countDirtyView(cm) == 0)
  584. return false;
  585. if (maybeUpdateLineNumberWidth(cm)) {
  586. resetView(cm);
  587. update.dims = getDimensions(cm);
  588. }
  589. // Compute a suitable new viewport (from & to)
  590. var end = doc.first + doc.size;
  591. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  592. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  593. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  594. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  595. if (sawCollapsedSpans) {
  596. from = visualLineNo(cm.doc, from);
  597. to = visualLineEndNo(cm.doc, to);
  598. }
  599. var different = from != display.viewFrom || to != display.viewTo ||
  600. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  601. adjustView(cm, from, to);
  602. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  603. // Position the mover div to align with the current scroll position
  604. cm.display.mover.style.top = display.viewOffset + "px";
  605. var toUpdate = countDirtyView(cm);
  606. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  607. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  608. return false;
  609. // For big changes, we hide the enclosing element during the
  610. // update, since that speeds up the operations on most browsers.
  611. var focused = activeElt();
  612. if (toUpdate > 4) display.lineDiv.style.display = "none";
  613. patchDisplay(cm, display.updateLineNumbers, update.dims);
  614. if (toUpdate > 4) display.lineDiv.style.display = "";
  615. display.renderedView = display.view;
  616. // There might have been a widget with a focused element that got
  617. // hidden or updated, if so re-focus it.
  618. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  619. // Prevent selection and cursors from interfering with the scroll
  620. // width and height.
  621. removeChildren(display.cursorDiv);
  622. removeChildren(display.selectionDiv);
  623. display.gutters.style.height = 0;
  624. if (different) {
  625. display.lastWrapHeight = update.wrapperHeight;
  626. display.lastWrapWidth = update.wrapperWidth;
  627. startWorker(cm, 400);
  628. }
  629. display.updateLineNumbers = null;
  630. return true;
  631. }
  632. function postUpdateDisplay(cm, update) {
  633. var viewport = update.viewport;
  634. for (var first = true; ; first = false) {
  635. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  636. // Clip forced viewport to actual scrollable area.
  637. if (viewport && viewport.top != null)
  638. viewport = { top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) };
  639. // Updated line heights might result in the drawn area not
  640. // actually covering the viewport. Keep looping until it does.
  641. update.visible = visibleLines(cm.display, cm.doc, viewport);
  642. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  643. break;
  644. }
  645. if (!updateDisplayIfNeeded(cm, update)) break;
  646. updateHeightsInViewport(cm);
  647. var barMeasure = measureForScrollbars(cm);
  648. updateSelection(cm);
  649. setDocumentHeight(cm, barMeasure);
  650. updateScrollbars(cm, barMeasure);
  651. }
  652. update.signal(cm, "update", cm);
  653. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  654. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  655. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  656. }
  657. }
  658. function updateDisplaySimple(cm, viewport) {
  659. var update = new DisplayUpdate(cm, viewport);
  660. if (updateDisplayIfNeeded(cm, update)) {
  661. updateHeightsInViewport(cm);
  662. postUpdateDisplay(cm, update);
  663. var barMeasure = measureForScrollbars(cm);
  664. updateSelection(cm);
  665. setDocumentHeight(cm, barMeasure);
  666. updateScrollbars(cm, barMeasure);
  667. update.finish();
  668. }
  669. }
  670. function setDocumentHeight(cm, measure) {
  671. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  672. var total = measure.docHeight + cm.display.barHeight;
  673. cm.display.heightForcer.style.top = total + "px";
  674. cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
  675. }
  676. // Read the actual heights of the rendered lines, and update their
  677. // stored heights to match.
  678. function updateHeightsInViewport(cm) {
  679. var display = cm.display;
  680. var prevBottom = display.lineDiv.offsetTop;
  681. for (var i = 0; i < display.view.length; i++) {
  682. var cur = display.view[i], height;
  683. if (cur.hidden) continue;
  684. if (ie && ie_version < 8) {
  685. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  686. height = bot - prevBottom;
  687. prevBottom = bot;
  688. } else {
  689. var box = cur.node.getBoundingClientRect();
  690. height = box.bottom - box.top;
  691. }
  692. var diff = cur.line.height - height;
  693. if (height < 2) height = textHeight(display);
  694. if (diff > .001 || diff < -.001) {
  695. updateLineHeight(cur.line, height);
  696. updateWidgetHeight(cur.line);
  697. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  698. updateWidgetHeight(cur.rest[j]);
  699. }
  700. }
  701. }
  702. // Read and store the height of line widgets associated with the
  703. // given line.
  704. function updateWidgetHeight(line) {
  705. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  706. line.widgets[i].height = line.widgets[i].node.offsetHeight;
  707. }
  708. // Do a bulk-read of the DOM positions and sizes needed to draw the
  709. // view, so that we don't interleave reading and writing to the DOM.
  710. function getDimensions(cm) {
  711. var d = cm.display, left = {}, width = {};
  712. var gutterLeft = d.gutters.clientLeft;
  713. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  714. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  715. width[cm.options.gutters[i]] = n.clientWidth;
  716. }
  717. return {
  718. fixedPos: compensateForHScroll(d),
  719. gutterTotalWidth: Math.max(d.gutters.offsetWidth, 21),
  720. gutterLeft: left,
  721. gutterWidth: width,
  722. wrapperWidth: d.wrapper.clientWidth
  723. };
  724. }
  725. // Sync the actual display DOM structure with display.view, removing
  726. // nodes for lines that are no longer in view, and creating the ones
  727. // that are not there yet, and updating the ones that are out of
  728. // date.
  729. function patchDisplay(cm, updateNumbersFrom, dims) {
  730. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  731. var container = display.lineDiv, cur = container.firstChild;
  732. function rm(node) {
  733. var next = node.nextSibling;
  734. // Works around a throw-scroll bug in OS X Webkit
  735. if (webkit && mac && cm.display.currentWheelTarget == node)
  736. node.style.display = "none";
  737. else
  738. node.parentNode.removeChild(node);
  739. return next;
  740. }
  741. var view = display.view, lineN = display.viewFrom;
  742. // Loop over the elements in the view, syncing cur (the DOM nodes
  743. // in display.lineDiv) with the view as we go.
  744. for (var i = 0; i < view.length; i++) {
  745. var lineView = view[i];
  746. if (lineView.hidden) {
  747. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  748. var node = buildLineElement(cm, lineView, lineN, dims);
  749. container.insertBefore(node, cur);
  750. } else { // Already drawn
  751. while (cur != lineView.node) cur = rm(cur);
  752. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  753. updateNumbersFrom <= lineN && lineView.lineNumber;
  754. if (lineView.changes) {
  755. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  756. updateLineForChanges(cm, lineView, lineN, dims);
  757. }
  758. if (updateNumber) {
  759. removeChildren(lineView.lineNumber);
  760. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  761. }
  762. cur = lineView.node.nextSibling;
  763. }
  764. lineN += lineView.size;
  765. }
  766. while (cur) cur = rm(cur);
  767. }
  768. // When an aspect of a line changes, a string is added to
  769. // lineView.changes. This updates the relevant part of the line's
  770. // DOM structure.
  771. function updateLineForChanges(cm, lineView, lineN, dims) {
  772. for (var j = 0; j < lineView.changes.length; j++) {
  773. var type = lineView.changes[j];
  774. if (type == "text") updateLineText(cm, lineView);
  775. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  776. else if (type == "class") updateLineClasses(lineView);
  777. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  778. }
  779. lineView.changes = null;
  780. }
  781. // Lines with gutter elements, widgets or a background class need to
  782. // be wrapped, and have the extra elements added to the wrapper div
  783. function ensureLineWrapped(lineView) {
  784. if (lineView.node == lineView.text) {
  785. lineView.node = elt("div", null, null, "position: relative");
  786. if (lineView.text.parentNode)
  787. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  788. lineView.node.appendChild(lineView.text);
  789. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  790. }
  791. return lineView.node;
  792. }
  793. function updateLineBackground(lineView) {
  794. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  795. if (cls) cls += " CodeMirror-linebackground";
  796. if (lineView.background) {
  797. if (cls) lineView.background.className = cls;
  798. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  799. } else if (cls) {
  800. var wrap = ensureLineWrapped(lineView);
  801. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  802. }
  803. }
  804. // Wrapper around buildLineContent which will reuse the structure
  805. // in display.externalMeasured when possible.
  806. function getLineContent(cm, lineView) {
  807. var ext = cm.display.externalMeasured;
  808. if (ext && ext.line == lineView.line) {
  809. cm.display.externalMeasured = null;
  810. lineView.measure = ext.measure;
  811. return ext.built;
  812. }
  813. return buildLineContent(cm, lineView);
  814. }
  815. // Redraw the line's text. Interacts with the background and text
  816. // classes because the mode may output tokens that influence these
  817. // classes.
  818. function updateLineText(cm, lineView) {
  819. var cls = lineView.text.className;
  820. var built = getLineContent(cm, lineView);
  821. if (lineView.text == lineView.node) lineView.node = built.pre;
  822. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  823. lineView.text = built.pre;
  824. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  825. lineView.bgClass = built.bgClass;
  826. lineView.textClass = built.textClass;
  827. updateLineClasses(lineView);
  828. } else if (cls) {
  829. lineView.text.className = cls;
  830. }
  831. }
  832. function updateLineClasses(lineView) {
  833. updateLineBackground(lineView);
  834. if (lineView.line.wrapClass)
  835. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  836. else if (lineView.node != lineView.text)
  837. lineView.node.className = "";
  838. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  839. lineView.text.className = textClass || "";
  840. }
  841. function updateLineGutter(cm, lineView, lineN, dims) {
  842. if (lineView.gutter) {
  843. lineView.node.removeChild(lineView.gutter);
  844. lineView.gutter = null;
  845. }
  846. var markers = lineView.line.gutterMarkers;
  847. if (cm.options.lineNumbers || markers) {
  848. var wrap = ensureLineWrapped(lineView);
  849. var _width = Math.max(dims.gutterTotalWidth, 21)
  850. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  851. (-_width) +//cm.options.fixedGutter ? dims.fixedPos :
  852. "px; width: " + _width + "px");
  853. cm.display.input.setUneditable(gutterWrap);
  854. wrap.insertBefore(gutterWrap, lineView.text);
  855. if (lineView.line.gutterClass)
  856. gutterWrap.className += " " + lineView.line.gutterClass;
  857. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  858. lineView.lineNumber = gutterWrap.appendChild(
  859. elt("div", lineNumberFor(cm.options, lineN),
  860. "CodeMirror-linenumber CodeMirror-gutter-elt",
  861. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  862. + cm.display.lineNumInnerWidth + "px"));
  863. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  864. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  865. if (found)
  866. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  867. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  868. }
  869. }
  870. }
  871. function updateLineWidgets(cm, lineView, dims) {
  872. if (lineView.alignable) lineView.alignable = null;
  873. for (var node = lineView.node.firstChild, next; node; node = next) {
  874. var next = node.nextSibling;
  875. if (node.className == "CodeMirror-linewidget")
  876. lineView.node.removeChild(node);
  877. }
  878. insertLineWidgets(cm, lineView, dims);
  879. }
  880. // Build a line's DOM representation from scratch
  881. function buildLineElement(cm, lineView, lineN, dims) {
  882. var built = getLineContent(cm, lineView);
  883. lineView.text = lineView.node = built.pre;
  884. if (built.bgClass) lineView.bgClass = built.bgClass;
  885. if (built.textClass) lineView.textClass = built.textClass;
  886. updateLineClasses(lineView);
  887. updateLineGutter(cm, lineView, lineN, dims);
  888. insertLineWidgets(cm, lineView, dims);
  889. return lineView.node;
  890. }
  891. // A lineView may contain multiple logical lines (when merged by
  892. // collapsed spans). The widgets for all of them need to be drawn.
  893. function insertLineWidgets(cm, lineView, dims) {
  894. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  895. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  896. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  897. }
  898. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  899. if (!line.widgets) return;
  900. var wrap = ensureLineWrapped(lineView);
  901. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  902. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  903. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  904. positionLineWidget(widget, node, lineView, dims);
  905. cm.display.input.setUneditable(node);
  906. if (allowAbove && widget.above)
  907. wrap.insertBefore(node, lineView.gutter || lineView.text);
  908. else
  909. wrap.appendChild(node);
  910. signalLater(widget, "redraw");
  911. }
  912. }
  913. function positionLineWidget(widget, node, lineView, dims) {
  914. if (widget.noHScroll) {
  915. (lineView.alignable || (lineView.alignable = [])).push(node);
  916. var width = dims.wrapperWidth;
  917. node.style.left = dims.fixedPos + "px";
  918. if (!widget.coverGutter) {
  919. width -= dims.gutterTotalWidth;
  920. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  921. }
  922. node.style.width = width + "px";
  923. }
  924. if (widget.coverGutter) {
  925. node.style.zIndex = 5;
  926. node.style.position = "relative";
  927. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  928. }
  929. }
  930. // POSITION OBJECT
  931. // A Pos instance represents a position within the text.
  932. var Pos = CodeMirror.Pos = function (line, ch) {
  933. if (!(this instanceof Pos)) return new Pos(line, ch);
  934. this.line = line; this.ch = ch;
  935. };
  936. // Compare two positions, return 0 if they are the same, a negative
  937. // number when a is less, and a positive number otherwise.
  938. var cmp = CodeMirror.cmpPos = function (a, b) { return a.line - b.line || a.ch - b.ch; };
  939. function copyPos(x) { return Pos(x.line, x.ch); }
  940. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  941. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  942. // INPUT HANDLING
  943. function ensureFocus(cm) {
  944. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  945. }
  946. function isReadOnly(cm) {
  947. return cm.options.readOnly || cm.doc.cantEdit;
  948. }
  949. // This will be set to an array of strings when copying, so that,
  950. // when pasting, we know what kind of selections the copied text
  951. // was made out of.
  952. var lastCopied = null;
  953. function applyTextInput(cm, inserted, deleted, sel, origin) {
  954. var doc = cm.doc;
  955. cm.display.shift = false;
  956. if (!sel) sel = doc.sel;
  957. var textLines = splitLines(inserted), multiPaste = null;
  958. // When pasing N lines into N selections, insert one line per selection
  959. if (cm.state.pasteIncoming && sel.ranges.length > 1) {
  960. if (lastCopied && lastCopied.join("\n") == inserted)
  961. multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);
  962. else if (textLines.length == sel.ranges.length)
  963. multiPaste = map(textLines, function (l) { return [l]; });
  964. }
  965. // Normal behavior is to insert the new text into every selection
  966. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  967. var range = sel.ranges[i];
  968. var from = range.from(), to = range.to();
  969. if (range.empty()) {
  970. if (deleted && deleted > 0) // Handle deletion
  971. from = Pos(from.line, from.ch - deleted);
  972. else if (cm.state.overwrite && !cm.state.pasteIncoming) // Handle overwrite
  973. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  974. }
  975. var updateInput = cm.curOp.updateInput;
  976. var changeEvent = {
  977. from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  978. origin: origin || (cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input")
  979. };
  980. makeChange(cm.doc, changeEvent);
  981. signalLater(cm, "inputRead", cm, changeEvent);
  982. }
  983. if (inserted && !cm.state.pasteIncoming)
  984. triggerElectric(cm, inserted);
  985. ensureCursorVisible(cm);
  986. cm.curOp.updateInput = updateInput;
  987. cm.curOp.typing = true;
  988. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  989. }
  990. function triggerElectric(cm, inserted) {
  991. // When an 'electric' character is inserted, immediately trigger a reindent
  992. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  993. var sel = cm.doc.sel;
  994. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  995. var range = sel.ranges[i];
  996. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  997. var mode = cm.getModeAt(range.head);
  998. var indented = false;
  999. if (mode.electricChars) {
  1000. for (var j = 0; j < mode.electricChars.length; j++)
  1001. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  1002. indented = indentLine(cm, range.head.line, "smart");
  1003. break;
  1004. }
  1005. } else if (mode.electricInput) {
  1006. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  1007. indented = indentLine(cm, range.head.line, "smart");
  1008. }
  1009. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  1010. }
  1011. }
  1012. function copyableRanges(cm) {
  1013. var text = [], ranges = [];
  1014. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1015. var line = cm.doc.sel.ranges[i].head.line;
  1016. var lineRange = { anchor: Pos(line, 0), head: Pos(line + 1, 0) };
  1017. ranges.push(lineRange);
  1018. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1019. }
  1020. return { text: text, ranges: ranges };
  1021. }
  1022. function disableBrowserMagic(field) {
  1023. field.setAttribute("autocorrect", "off");
  1024. field.setAttribute("autocapitalize", "off");
  1025. field.setAttribute("spellcheck", "false");
  1026. }
  1027. // TEXTAREA INPUT STYLE
  1028. function TextareaInput(cm) {
  1029. this.cm = cm;
  1030. // See input.poll and input.reset
  1031. this.prevInput = "";
  1032. // Flag that indicates whether we expect input to appear real soon
  1033. // now (after some event like 'keypress' or 'input') and are
  1034. // polling intensively.
  1035. this.pollingFast = false;
  1036. // Self-resetting timeout for the poller
  1037. this.polling = new Delayed();
  1038. // Tracks when input.reset has punted to just putting a short
  1039. // string into the textarea instead of the full selection.
  1040. this.inaccurateSelection = false;
  1041. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1042. this.hasSelection = false;
  1043. this.composing = null;
  1044. };
  1045. function hiddenTextarea() {
  1046. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  1047. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1048. // The textarea is kept positioned near the cursor to prevent the
  1049. // fact that it'll be scrolled into view on input from scrolling
  1050. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1051. // very slow. So make the area wide instead.
  1052. if (webkit) te.style.width = "1000px";
  1053. else te.setAttribute("wrap", "off");
  1054. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1055. if (ios) te.style.border = "1px solid black";
  1056. disableBrowserMagic(te);
  1057. return div;
  1058. }
  1059. TextareaInput.prototype = copyObj({
  1060. init: function (display) {
  1061. var input = this, cm = this.cm;
  1062. // Wraps and hides input textarea
  1063. var div = this.wrapper = hiddenTextarea();
  1064. // The semihidden textarea that is focused when the editor is
  1065. // focused, and receives input.
  1066. var te = this.textarea = div.firstChild;
  1067. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1068. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1069. if (ios) te.style.width = "0px";
  1070. on(te, "input", function () {
  1071. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1072. input.poll();
  1073. });
  1074. on(te, "paste", function () {
  1075. // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
  1076. // Add a char to the end of textarea before paste occur so that
  1077. // selection doesn't span to the end of textarea.
  1078. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
  1079. var start = te.selectionStart, end = te.selectionEnd;
  1080. te.value += "$";
  1081. // The selection end needs to be set before the start, otherwise there
  1082. // can be an intermediate non-empty selection between the two, which
  1083. // can override the middle-click paste buffer on linux and cause the
  1084. // wrong thing to get pasted.
  1085. te.selectionEnd = end;
  1086. te.selectionStart = start;
  1087. cm.state.fakedLastChar = true;
  1088. }
  1089. cm.state.pasteIncoming = true;
  1090. input.fastPoll();
  1091. });
  1092. function prepareCopyCut(e) {
  1093. if (cm.somethingSelected()) {
  1094. lastCopied = cm.getSelections();
  1095. if (input.inaccurateSelection) {
  1096. input.prevInput = "";
  1097. input.inaccurateSelection = false;
  1098. te.value = lastCopied.join("\n");
  1099. selectInput(te);
  1100. }
  1101. } else if (!cm.options.lineWiseCopyCut) {
  1102. return;
  1103. } else {
  1104. var ranges = copyableRanges(cm);
  1105. lastCopied = ranges.text;
  1106. if (e.type == "cut") {
  1107. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1108. } else {
  1109. input.prevInput = "";
  1110. te.value = ranges.text.join("\n");
  1111. selectInput(te);
  1112. }
  1113. }
  1114. if (e.type == "cut") cm.state.cutIncoming = true;
  1115. }
  1116. on(te, "cut", prepareCopyCut);
  1117. on(te, "copy", prepareCopyCut);
  1118. on(display.scroller, "paste", function (e) {
  1119. if (eventInWidget(display, e)) return;
  1120. cm.state.pasteIncoming = true;
  1121. input.focus();
  1122. });
  1123. // Prevent normal selection in the editor (we handle our own)
  1124. on(display.lineSpace, "selectstart", function (e) {
  1125. if (!eventInWidget(display, e)) e_preventDefault(e);
  1126. });
  1127. on(te, "compositionstart", function () {
  1128. var start = cm.getCursor("from");
  1129. input.composing = {
  1130. start: start,
  1131. range: cm.markText(start, cm.getCursor("to"), { className: "CodeMirror-composing" })
  1132. };
  1133. });
  1134. on(te, "compositionend", function () {
  1135. if (input.composing) {
  1136. input.poll();
  1137. input.composing.range.clear();
  1138. input.composing = null;
  1139. }
  1140. });
  1141. },
  1142. prepareSelection: function () {
  1143. // Redraw the selection and/or cursor
  1144. var cm = this.cm, display = cm.display, doc = cm.doc;
  1145. var result = prepareSelection(cm);
  1146. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1147. if (cm.options.moveInputWithCursor) {
  1148. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1149. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1150. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1151. headPos.top + lineOff.top - wrapOff.top));
  1152. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1153. headPos.left + lineOff.left - wrapOff.left));
  1154. }
  1155. return result;
  1156. },
  1157. showSelection: function (drawn) {
  1158. var cm = this.cm, display = cm.display;
  1159. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1160. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1161. if (drawn.teTop != null) {
  1162. this.wrapper.style.top = drawn.teTop + "px";
  1163. this.wrapper.style.left = drawn.teLeft + "px";
  1164. }
  1165. },
  1166. // Reset the input to correspond to the selection (or to be empty,
  1167. // when not typing and nothing is selected)
  1168. reset: function (typing) {
  1169. if (this.contextMenuPending) return;
  1170. var minimal, selected, cm = this.cm, doc = cm.doc;
  1171. if (cm.somethingSelected()) {
  1172. this.prevInput = "";
  1173. var range = doc.sel.primary();
  1174. minimal = hasCopyEvent &&
  1175. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1176. var content = minimal ? "-" : selected || cm.getSelection();
  1177. this.textarea.value = content;
  1178. if (cm.state.focused) selectInput(this.textarea);
  1179. if (ie && ie_version >= 9) this.hasSelection = content;
  1180. } else if (!typing) {
  1181. this.prevInput = this.textarea.value = "";
  1182. if (ie && ie_version >= 9) this.hasSelection = null;
  1183. }
  1184. this.inaccurateSelection = minimal;
  1185. },
  1186. getField: function () { return this.textarea; },
  1187. supportsTouch: function () { return false; },
  1188. focus: function () {
  1189. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1190. try { this.textarea.focus(); }
  1191. catch (e) { } // IE8 will throw if the textarea is display: none or not in DOM
  1192. }
  1193. },
  1194. blur: function () { this.textarea.blur(); },
  1195. resetPosition: function () {
  1196. this.wrapper.style.top = this.wrapper.style.left = 0;
  1197. },
  1198. receivedFocus: function () { this.slowPoll(); },
  1199. // Poll for input changes, using the normal rate of polling. This
  1200. // runs as long as the editor is focused.
  1201. slowPoll: function () {
  1202. var input = this;
  1203. if (input.pollingFast) return;
  1204. input.polling.set(this.cm.options.pollInterval, function () {
  1205. input.poll();
  1206. if (input.cm.state.focused) input.slowPoll();
  1207. });
  1208. },
  1209. // When an event has just come in that is likely to add or change
  1210. // something in the input textarea, we poll faster, to ensure that
  1211. // the change appears on the screen quickly.
  1212. fastPoll: function () {
  1213. var missed = false, input = this;
  1214. input.pollingFast = true;
  1215. function p() {
  1216. var changed = input.poll();
  1217. if (!changed && !missed) { missed = true; input.polling.set(60, p); }
  1218. else { input.pollingFast = false; input.slowPoll(); }
  1219. }
  1220. input.polling.set(20, p);
  1221. },
  1222. // Read input from the textarea, and update the document to match.
  1223. // When something is selected, it is present in the textarea, and
  1224. // selected (unless it is huge, in which case a placeholder is
  1225. // used). When nothing is selected, the cursor sits after previously
  1226. // seen text (can be empty), which is stored in prevInput (we must
  1227. // not reset the textarea when typing, because that breaks IME).
  1228. poll: function () {
  1229. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1230. // Since this is called a *lot*, try to bail out as cheaply as
  1231. // possible when it is clear that nothing happened. hasSelection
  1232. // will be the case when there is a lot of text in the textarea,
  1233. // in which case reading its value would be expensive.
  1234. if (!cm.state.focused || (hasSelection(input) && !prevInput) ||
  1235. isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
  1236. return false;
  1237. // See paste handler for more on the fakedLastChar kludge
  1238. if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
  1239. input.value = input.value.substring(0, input.value.length - 1);
  1240. cm.state.fakedLastChar = false;
  1241. }
  1242. var text = input.value;
  1243. // If nothing changed, bail.
  1244. if (text == prevInput && !cm.somethingSelected()) return false;
  1245. // Work around nonsensical selection resetting in IE9/10, and
  1246. // inexplicable appearance of private area unicode characters on
  1247. // some key combos in Mac (#2689).
  1248. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1249. mac && /[\uf700-\uf7ff]/.test(text)) {
  1250. cm.display.input.reset();
  1251. return false;
  1252. }
  1253. if (cm.doc.sel == cm.display.selForContextMenu) {
  1254. var first = text.charCodeAt(0);
  1255. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  1256. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  1257. }
  1258. // Find the part of the input that is actually new
  1259. var same = 0, l = Math.min(prevInput.length, text.length);
  1260. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same))++same;
  1261. var self = this;
  1262. runInOp(cm, function () {
  1263. applyTextInput(cm, text.slice(same), prevInput.length - same,
  1264. null, self.composing ? "*compose" : null);
  1265. // Don't leave long text in the textarea, since it makes further polling slow
  1266. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1267. else self.prevInput = text;
  1268. if (self.composing) {
  1269. self.composing.range.clear();
  1270. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  1271. { className: "CodeMirror-composing" });
  1272. }
  1273. });
  1274. return true;
  1275. },
  1276. ensurePolled: function () {
  1277. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1278. },
  1279. onKeyPress: function () {
  1280. if (ie && ie_version >= 9) this.hasSelection = null;
  1281. this.fastPoll();
  1282. },
  1283. onContextMenu: function (e) {
  1284. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1285. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1286. if (!pos || presto) return; // Opera is difficult.
  1287. // Reset the current text selection only if the click is done outside of the selection
  1288. // and 'resetSelectionOnContextMenu' option is true.
  1289. var reset = cm.options.resetSelectionOnContextMenu;
  1290. if (reset && cm.doc.sel.contains(pos) == -1)
  1291. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1292. var oldCSS = te.style.cssText;
  1293. input.wrapper.style.position = "absolute";
  1294. te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1295. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
  1296. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1297. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1298. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1299. display.input.focus();
  1300. if (webkit) window.scrollTo(null, oldScrollY);
  1301. display.input.reset();
  1302. // Adds "Select all" to context menu in FF
  1303. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1304. input.contextMenuPending = true;
  1305. display.selForContextMenu = cm.doc.sel;
  1306. clearTimeout(display.detectingSelectAll);
  1307. // Select-all will be greyed out if there's nothing to select, so
  1308. // this adds a zero-width space so that we can later check whether
  1309. // it got selected.
  1310. function prepareSelectAllHack() {
  1311. if (te.selectionStart != null) {
  1312. var selected = cm.somethingSelected();
  1313. var extval = "\u200b" + (selected ? te.value : "");
  1314. te.value = "\u21da"; // Used to catch context-menu undo
  1315. te.value = extval;
  1316. input.prevInput = selected ? "" : "\u200b";
  1317. te.selectionStart = 1; te.selectionEnd = extval.length;
  1318. // Re-set this, in case some other handler touched the
  1319. // selection in the meantime.
  1320. display.selForContextMenu = cm.doc.sel;
  1321. }
  1322. }
  1323. function rehide() {
  1324. input.contextMenuPending = false;
  1325. input.wrapper.style.position = "relative";
  1326. te.style.cssText = oldCSS;
  1327. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1328. // Try to detect the user choosing select-all
  1329. if (te.selectionStart != null) {
  1330. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1331. var i = 0, poll = function () {
  1332. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  1333. te.selectionEnd > 0 && input.prevInput == "\u200b")
  1334. operation(cm, commands.selectAll)(cm);
  1335. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1336. else display.input.reset();
  1337. };
  1338. display.detectingSelectAll = setTimeout(poll, 200);
  1339. }
  1340. }
  1341. if (ie && ie_version >= 9) prepareSelectAllHack();
  1342. if (captureRightClick) {
  1343. e_stop(e);
  1344. var mouseup = function () {
  1345. off(window, "mouseup", mouseup);
  1346. setTimeout(rehide, 20);
  1347. };
  1348. on(window, "mouseup", mouseup);
  1349. } else {
  1350. setTimeout(rehide, 50);
  1351. }
  1352. },
  1353. setUneditable: nothing,
  1354. needsContentAttribute: false
  1355. }, TextareaInput.prototype);
  1356. // CONTENTEDITABLE INPUT STYLE
  1357. function ContentEditableInput(cm) {
  1358. this.cm = cm;
  1359. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1360. this.polling = new Delayed();
  1361. this.gracePeriod = false;
  1362. }
  1363. ContentEditableInput.prototype = copyObj({
  1364. init: function (display) {
  1365. var input = this, cm = input.cm;
  1366. var div = input.div = display.lineDiv;
  1367. div.contentEditable = "true";
  1368. disableBrowserMagic(div);
  1369. on(div, "paste", function (e) {
  1370. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1371. if (pasted) {
  1372. e.preventDefault();
  1373. cm.replaceSelection(pasted, null, "paste");
  1374. }
  1375. });
  1376. on(div, "compositionstart", function (e) {
  1377. var data = e.data;
  1378. input.composing = { sel: cm.doc.sel, data: data, startData: data };
  1379. if (!data) return;
  1380. var prim = cm.doc.sel.primary();
  1381. var line = cm.getLine(prim.head.line);
  1382. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1383. if (found > -1 && found <= prim.head.ch)
  1384. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1385. Pos(prim.head.line, found + data.length));
  1386. });
  1387. on(div, "compositionupdate", function (e) {
  1388. input.composing.data = e.data;
  1389. });
  1390. on(div, "compositionend", function (e) {
  1391. var ours = input.composing;
  1392. if (!ours) return;
  1393. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1394. ours.data = e.data;
  1395. // Need a small delay to prevent other code (input event,
  1396. // selection polling) from doing damage when fired right after
  1397. // compositionend.
  1398. setTimeout(function () {
  1399. if (!ours.handled)
  1400. input.applyComposition(ours);
  1401. if (input.composing == ours)
  1402. input.composing = null;
  1403. }, 50);
  1404. });
  1405. on(div, "touchstart", function () {
  1406. input.forceCompositionEnd();
  1407. });
  1408. on(div, "input", function () {
  1409. if (input.composing) return;
  1410. if (!input.pollContent())
  1411. runInOp(input.cm, function () { regChange(cm); });
  1412. });
  1413. function onCopyCut(e) {
  1414. if (cm.somethingSelected()) {
  1415. lastCopied = cm.getSelections();
  1416. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1417. } else if (!cm.options.lineWiseCopyCut) {
  1418. return;
  1419. } else {
  1420. var ranges = copyableRanges(cm);
  1421. lastCopied = ranges.text;
  1422. if (e.type == "cut") {
  1423. cm.operation(function () {
  1424. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1425. cm.replaceSelection("", null, "cut");
  1426. });
  1427. }
  1428. }
  1429. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1430. if (e.clipboardData && !ios) {
  1431. e.preventDefault();
  1432. e.clipboardData.clearData();
  1433. e.clipboardData.setData("text/plain", lastCopied.join("\n"));
  1434. } else {
  1435. // Old-fashioned briefly-focus-a-textarea hack
  1436. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1437. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1438. te.value = lastCopied.join("\n");
  1439. var hadFocus = document.activeElement;
  1440. selectInput(te);
  1441. setTimeout(function () {
  1442. cm.display.lineSpace.removeChild(kludge);
  1443. hadFocus.focus();
  1444. }, 50);
  1445. }
  1446. }
  1447. on(div, "copy", onCopyCut);
  1448. on(div, "cut", onCopyCut);
  1449. },
  1450. prepareSelection: function () {
  1451. var result = prepareSelection(this.cm, false);
  1452. result.focus = this.cm.state.focused;
  1453. return result;
  1454. },
  1455. showSelection: function (info) {
  1456. if (!info || !this.cm.display.view.length) return;
  1457. if (info.focus) this.showPrimarySelection();
  1458. this.showMultipleSelections(info);
  1459. },
  1460. showPrimarySelection: function () {
  1461. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1462. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1463. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1464. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1465. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1466. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1467. return;
  1468. var start = posToDOM(this.cm, prim.from());
  1469. var end = posToDOM(this.cm, prim.to());
  1470. if (!start && !end) return;
  1471. var view = this.cm.display.view;
  1472. var old = sel.rangeCount && sel.getRangeAt(0);
  1473. if (!start) {
  1474. start = { node: view[0].measure.map[2], offset: 0 };
  1475. } else if (!end) { // FIXME dangerously hacky
  1476. var measure = view[view.length - 1].measure;
  1477. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1478. end = { node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3] };
  1479. }
  1480. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1481. catch (e) { } // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1482. if (rng) {
  1483. sel.removeAllRanges();
  1484. sel.addRange(rng);
  1485. if (old && sel.anchorNode == null) sel.addRange(old);
  1486. else if (gecko) this.startGracePeriod();
  1487. }
  1488. this.rememberSelection();
  1489. },
  1490. startGracePeriod: function () {
  1491. var input = this;
  1492. clearTimeout(this.gracePeriod);
  1493. this.gracePeriod = setTimeout(function () {
  1494. input.gracePeriod = false;
  1495. if (input.selectionChanged())
  1496. input.cm.operation(function () { input.cm.curOp.selectionChanged = true; });
  1497. }, 20);
  1498. },
  1499. showMultipleSelections: function (info) {
  1500. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1501. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1502. },
  1503. rememberSelection: function () {
  1504. var sel = window.getSelection();
  1505. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1506. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1507. },
  1508. selectionInEditor: function () {
  1509. var sel = window.getSelection();
  1510. if (!sel.rangeCount) return false;
  1511. var node = sel.getRangeAt(0).commonAncestorContainer;
  1512. return contains(this.div, node);
  1513. },
  1514. focus: function () {
  1515. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1516. },
  1517. blur: function () { this.div.blur(); },
  1518. getField: function () { return this.div; },
  1519. supportsTouch: function () { return true; },
  1520. receivedFocus: function () {
  1521. var input = this;
  1522. if (this.selectionInEditor())
  1523. this.pollSelection();
  1524. else
  1525. runInOp(this.cm, function () { input.cm.curOp.selectionChanged = true; });
  1526. function poll() {
  1527. if (input.cm.state.focused) {
  1528. input.pollSelection();
  1529. input.polling.set(input.cm.options.pollInterval, poll);
  1530. }
  1531. }
  1532. this.polling.set(this.cm.options.pollInterval, poll);
  1533. },
  1534. selectionChanged: function () {
  1535. var sel = window.getSelection();
  1536. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1537. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  1538. },
  1539. pollSelection: function () {
  1540. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  1541. var sel = window.getSelection(), cm = this.cm;
  1542. this.rememberSelection();
  1543. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1544. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1545. if (anchor && head) runInOp(cm, function () {
  1546. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1547. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1548. });
  1549. }
  1550. },
  1551. pollContent: function () {
  1552. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1553. var from = sel.from(), to = sel.to();
  1554. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1555. var fromIndex;
  1556. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1557. var fromLine = lineNo(display.view[0].line);
  1558. var fromNode = display.view[0].node;
  1559. } else {
  1560. var fromLine = lineNo(display.view[fromIndex].line);
  1561. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1562. }
  1563. var toIndex = findViewIndex(cm, to.line);
  1564. if (toIndex == display.view.length - 1) {
  1565. var toLine = display.viewTo - 1;
  1566. var toNode = display.view[toIndex].node;
  1567. } else {
  1568. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1569. var toNode = display.view[toIndex + 1].node.previousSibling;
  1570. }
  1571. var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1572. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1573. while (newText.length > 1 && oldText.length > 1) {
  1574. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1575. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1576. else break;
  1577. }
  1578. var cutFront = 0, cutEnd = 0;
  1579. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1580. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1581. ++cutFront;
  1582. var newBot = lst(newText), oldBot = lst(oldText);
  1583. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1584. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1585. while (cutEnd < maxCutEnd &&
  1586. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1587. ++cutEnd;
  1588. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1589. newText[0] = newText[0].slice(cutFront);
  1590. var chFrom = Pos(fromLine, cutFront);
  1591. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1592. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1593. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1594. return true;
  1595. }
  1596. },
  1597. ensurePolled: function () {
  1598. this.forceCompositionEnd();
  1599. },
  1600. reset: function () {
  1601. this.forceCompositionEnd();
  1602. },
  1603. forceCompositionEnd: function () {
  1604. if (!this.composing || this.composing.handled) return;
  1605. this.applyComposition(this.composing);
  1606. this.composing.handled = true;
  1607. this.div.blur();
  1608. this.div.focus();
  1609. },
  1610. applyComposition: function (composing) {
  1611. if (composing.data && composing.data != composing.startData)
  1612. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1613. },
  1614. setUneditable: function (node) {
  1615. node.setAttribute("contenteditable", "false");
  1616. },
  1617. onKeyPress: function (e) {
  1618. e.preventDefault();
  1619. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1620. },
  1621. onContextMenu: nothing,
  1622. resetPosition: nothing,
  1623. needsContentAttribute: true
  1624. }, ContentEditableInput.prototype);
  1625. function posToDOM(cm, pos) {
  1626. var view = findViewForLine(cm, pos.line);
  1627. if (!view || view.hidden) return null;
  1628. var line = getLine(cm.doc, pos.line);
  1629. var info = mapFromLineView(view, line, pos.line);
  1630. var order = getOrder(line), side = "left";
  1631. if (order) {
  1632. var partPos = getBidiPartAt(order, pos.ch);
  1633. side = partPos % 2 ? "right" : "left";
  1634. }
  1635. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  1636. result.offset = result.collapse == "right" ? result.end : result.start;
  1637. return result;
  1638. }
  1639. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1640. function domToPos(cm, node, offset) {
  1641. var lineNode;
  1642. if (node == cm.display.lineDiv) {
  1643. lineNode = cm.display.lineDiv.childNodes[offset];
  1644. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1645. node = null; offset = 0;
  1646. } else {
  1647. for (lineNode = node; ; lineNode = lineNode.parentNode) {
  1648. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1649. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1650. }
  1651. }
  1652. for (var i = 0; i < cm.display.view.length; i++) {
  1653. var lineView = cm.display.view[i];
  1654. if (lineView.node == lineNode)
  1655. return locateNodeInLineView(lineView, node, offset);
  1656. }
  1657. }
  1658. function locateNodeInLineView(lineView, node, offset) {
  1659. var wrapper = lineView.text.firstChild, bad = false;
  1660. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1661. if (node == wrapper) {
  1662. bad = true;
  1663. node = wrapper.childNodes[offset];
  1664. offset = 0;
  1665. if (!node) {
  1666. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1667. return badPos(Pos(lineNo(line), line.text.length), bad);
  1668. }
  1669. }
  1670. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1671. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1672. textNode = node.firstChild;
  1673. if (offset) offset = textNode.nodeValue.length;
  1674. }
  1675. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1676. var measure = lineView.measure, maps = measure.maps;
  1677. function find(textNode, topNode, offset) {
  1678. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1679. var map = i < 0 ? measure.map : maps[i];
  1680. for (var j = 0; j < map.length; j += 3) {
  1681. var curNode = map[j + 2];
  1682. if (curNode == textNode || curNode == topNode) {
  1683. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1684. var ch = map[j] + offset;
  1685. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1686. return Pos(line, ch);
  1687. }
  1688. }
  1689. }
  1690. }
  1691. var found = find(textNode, topNode, offset);
  1692. if (found) return badPos(found, bad);
  1693. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1694. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1695. found = find(after, after.firstChild, 0);
  1696. if (found)
  1697. return badPos(Pos(found.line, found.ch - dist), bad);
  1698. else
  1699. dist += after.textContent.length;
  1700. }
  1701. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1702. found = find(before, before.firstChild, -1);
  1703. if (found)
  1704. return badPos(Pos(found.line, found.ch + dist), bad);
  1705. else
  1706. dist += after.textContent.length;
  1707. }
  1708. }
  1709. function domTextBetween(cm, from, to, fromLine, toLine) {
  1710. var text = "", closing = false;
  1711. function recognizeMarker(id) { return function (marker) { return marker.id == id; }; }
  1712. function walk(node) {
  1713. if (node.nodeType == 1) {
  1714. var cmText = node.getAttribute("cm-text");
  1715. if (cmText != null) {
  1716. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1717. text += cmText;
  1718. return;
  1719. }
  1720. var markerID = node.getAttribute("cm-marker"), range;
  1721. if (markerID) {
  1722. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1723. if (found.length && (range = found[0].find()))
  1724. text += getBetween(cm.doc, range.from, range.to).join("\n");
  1725. return;
  1726. }
  1727. if (node.getAttribute("contenteditable") == "false") return;
  1728. for (var i = 0; i < node.childNodes.length; i++)
  1729. walk(node.childNodes[i]);
  1730. if (/^(pre|div|p)$/i.test(node.nodeName))
  1731. closing = true;
  1732. } else if (node.nodeType == 3) {
  1733. var val = node.nodeValue;
  1734. if (!val) return;
  1735. if (closing) {
  1736. text += "\n";
  1737. closing = false;
  1738. }
  1739. text += val;
  1740. }
  1741. }
  1742. for (; ;) {
  1743. walk(from);
  1744. if (from == to) break;
  1745. from = from.nextSibling;
  1746. }
  1747. return text;
  1748. }
  1749. CodeMirror.inputStyles = { "textarea": TextareaInput, "contenteditable": ContentEditableInput };
  1750. // SELECTION / CURSOR
  1751. // Selection objects are immutable. A new one is created every time
  1752. // the selection changes. A selection is one or more non-overlapping
  1753. // (and non-touching) ranges, sorted, and an integer that indicates
  1754. // which one is the primary selection (the one that's scrolled into
  1755. // view, that getCursor returns, etc).
  1756. function Selection(ranges, primIndex) {
  1757. this.ranges = ranges;
  1758. this.primIndex = primIndex;
  1759. }
  1760. Selection.prototype = {
  1761. primary: function () { return this.ranges[this.primIndex]; },
  1762. equals: function (other) {
  1763. if (other == this) return true;
  1764. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1765. for (var i = 0; i < this.ranges.length; i++) {
  1766. var here = this.ranges[i], there = other.ranges[i];
  1767. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1768. }
  1769. return true;
  1770. },
  1771. deepCopy: function () {
  1772. for (var out = [], i = 0; i < this.ranges.length; i++)
  1773. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1774. return new Selection(out, this.primIndex);
  1775. },
  1776. somethingSelected: function () {
  1777. for (var i = 0; i < this.ranges.length; i++)
  1778. if (!this.ranges[i].empty()) return true;
  1779. return false;
  1780. },
  1781. contains: function (pos, end) {
  1782. if (!end) end = pos;
  1783. for (var i = 0; i < this.ranges.length; i++) {
  1784. var range = this.ranges[i];
  1785. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1786. return i;
  1787. }
  1788. return -1;
  1789. }
  1790. };
  1791. function Range(anchor, head) {
  1792. this.anchor = anchor; this.head = head;
  1793. }
  1794. Range.prototype = {
  1795. from: function () { return minPos(this.anchor, this.head); },
  1796. to: function () { return maxPos(this.anchor, this.head); },
  1797. empty: function () {
  1798. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1799. }
  1800. };
  1801. // Take an unsorted, potentially overlapping set of ranges, and
  1802. // build a selection out of it. 'Consumes' ranges array (modifying
  1803. // it).
  1804. function normalizeSelection(ranges, primIndex) {
  1805. var prim = ranges[primIndex];
  1806. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  1807. primIndex = indexOf(ranges, prim);
  1808. for (var i = 1; i < ranges.length; i++) {
  1809. var cur = ranges[i], prev = ranges[i - 1];
  1810. if (cmp(prev.to(), cur.from()) >= 0) {
  1811. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1812. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1813. if (i <= primIndex)--primIndex;
  1814. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1815. }
  1816. }
  1817. return new Selection(ranges, primIndex);
  1818. }
  1819. function simpleSelection(anchor, head) {
  1820. return new Selection([new Range(anchor, head || anchor)], 0);
  1821. }
  1822. // Most of the external API clips given positions to make sure they
  1823. // actually exist within the document.
  1824. function clipLine(doc, n) { return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1)); }
  1825. function clipPos(doc, pos) {
  1826. if (pos.line < doc.first) return Pos(doc.first, 0);
  1827. var last = doc.first + doc.size - 1;
  1828. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1829. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1830. }
  1831. function clipToLen(pos, linelen) {
  1832. var ch = pos.ch;
  1833. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1834. else if (ch < 0) return Pos(pos.line, 0);
  1835. else return pos;
  1836. }
  1837. function isLine(doc, l) { return l >= doc.first && l < doc.first + doc.size; }
  1838. function clipPosArray(doc, array) {
  1839. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1840. return out;
  1841. }
  1842. // SELECTION UPDATES
  1843. // The 'scroll' parameter given to many of these indicated whether
  1844. // the new cursor position should be scrolled into view after
  1845. // modifying the selection.
  1846. // If shift is held or the extend flag is set, extends a range to
  1847. // include a given position (and optionally a second position).
  1848. // Otherwise, simply returns the range between the given positions.
  1849. // Used for cursor motion and such.
  1850. function extendRange(doc, range, head, other) {
  1851. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1852. var anchor = range.anchor;
  1853. if (other) {
  1854. var posBefore = cmp(head, anchor) < 0;
  1855. if (posBefore != (cmp(other, anchor) < 0)) {
  1856. anchor = head;
  1857. head = other;
  1858. } else if (posBefore != (cmp(head, other) < 0)) {
  1859. head = other;
  1860. }
  1861. }
  1862. return new Range(anchor, head);
  1863. } else {
  1864. return new Range(other || head, head);
  1865. }
  1866. }
  1867. // Extend the primary selection range, discard the rest.
  1868. function extendSelection(doc, head, other, options) {
  1869. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1870. }
  1871. // Extend all selections (pos is an array of selections with length
  1872. // equal the number of selections)
  1873. function extendSelections(doc, heads, options) {
  1874. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1875. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1876. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1877. setSelection(doc, newSel, options);
  1878. }
  1879. // Updates a single range in the selection.
  1880. function replaceOneSelection(doc, i, range, options) {
  1881. var ranges = doc.sel.ranges.slice(0);
  1882. ranges[i] = range;
  1883. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1884. }
  1885. // Reset the selection to a single range.
  1886. function setSimpleSelection(doc, anchor, head, options) {
  1887. setSelection(doc, simpleSelection(anchor, head), options);
  1888. }
  1889. // Give beforeSelectionChange handlers a change to influence a
  1890. // selection update.
  1891. function filterSelectionChange(doc, sel) {
  1892. var obj = {
  1893. ranges: sel.ranges,
  1894. update: function (ranges) {
  1895. this.ranges = [];
  1896. for (var i = 0; i < ranges.length; i++)
  1897. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1898. clipPos(doc, ranges[i].head));
  1899. }
  1900. };
  1901. signal(doc, "beforeSelectionChange", doc, obj);
  1902. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1903. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1904. else return sel;
  1905. }
  1906. function setSelectionReplaceHistory(doc, sel, options) {
  1907. var done = doc.history.done, last = lst(done);
  1908. if (last && last.ranges) {
  1909. done[done.length - 1] = sel;
  1910. setSelectionNoUndo(doc, sel, options);
  1911. } else {
  1912. setSelection(doc, sel, options);
  1913. }
  1914. }
  1915. // Set a new selection.
  1916. function setSelection(doc, sel, options) {
  1917. setSelectionNoUndo(doc, sel, options);
  1918. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1919. }
  1920. function setSelectionNoUndo(doc, sel, options) {
  1921. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1922. sel = filterSelectionChange(doc, sel);
  1923. var bias = options && options.bias ||
  1924. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1925. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1926. if (!(options && options.scroll === false) && doc.cm)
  1927. ensureCursorVisible(doc.cm);
  1928. }
  1929. function setSelectionInner(doc, sel) {
  1930. if (sel.equals(doc.sel)) return;
  1931. doc.sel = sel;
  1932. if (doc.cm) {
  1933. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1934. signalCursorActivity(doc.cm);
  1935. }
  1936. signalLater(doc, "cursorActivity", doc);
  1937. }
  1938. // Verify that the selection does not partially select any atomic
  1939. // marked ranges.
  1940. function reCheckSelection(doc) {
  1941. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1942. }
  1943. // Return a selection that does not partially select any atomic
  1944. // ranges.
  1945. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1946. var out;
  1947. for (var i = 0; i < sel.ranges.length; i++) {
  1948. var range = sel.ranges[i];
  1949. var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
  1950. var newHead = skipAtomic(doc, range.head, bias, mayClear);
  1951. if (out || newAnchor != range.anchor || newHead != range.head) {
  1952. if (!out) out = sel.ranges.slice(0, i);
  1953. out[i] = new Range(newAnchor, newHead);
  1954. }
  1955. }
  1956. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1957. }
  1958. // Ensure a given position is not inside an atomic range.
  1959. function skipAtomic(doc, pos, bias, mayClear) {
  1960. var flipped = false, curPos = pos;
  1961. var dir = bias || 1;
  1962. doc.cantEdit = false;
  1963. search: for (; ;) {
  1964. var line = getLine(doc, curPos.line);
  1965. if (line.markedSpans) {
  1966. for (var i = 0; i < line.markedSpans.length; ++i) {
  1967. var sp = line.markedSpans[i], m = sp.marker;
  1968. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  1969. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  1970. if (mayClear) {
  1971. signal(m, "beforeCursorEnter");
  1972. if (m.explicitlyCleared) {
  1973. if (!line.markedSpans) break;
  1974. else { --i; continue; }
  1975. }
  1976. }
  1977. if (!m.atomic) continue;
  1978. var newPos = m.find(dir < 0 ? -1 : 1);
  1979. if (cmp(newPos, curPos) == 0) {
  1980. newPos.ch += dir;
  1981. if (newPos.ch < 0) {
  1982. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  1983. else newPos = null;
  1984. } else if (newPos.ch > line.text.length) {
  1985. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  1986. else newPos = null;
  1987. }
  1988. if (!newPos) {
  1989. if (flipped) {
  1990. // Driven in a corner -- no valid cursor position found at all
  1991. // -- try again *with* clearing, if we didn't already
  1992. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  1993. // Otherwise, turn off editing until further notice, and return the start of the doc
  1994. doc.cantEdit = true;
  1995. return Pos(doc.first, 0);
  1996. }
  1997. flipped = true; newPos = pos; dir = -dir;
  1998. }
  1999. }
  2000. curPos = newPos;
  2001. continue search;
  2002. }
  2003. }
  2004. }
  2005. return curPos;
  2006. }
  2007. }
  2008. // SELECTION DRAWING
  2009. function updateSelection(cm) {
  2010. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2011. }
  2012. function prepareSelection(cm, primary) {
  2013. var doc = cm.doc, result = {};
  2014. var curFragment = result.cursors = document.createDocumentFragment();
  2015. var selFragment = result.selection = document.createDocumentFragment();
  2016. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2017. if (primary === false && i == doc.sel.primIndex) continue;
  2018. var range = doc.sel.ranges[i];
  2019. var collapsed = range.empty();
  2020. if (collapsed || cm.options.showCursorWhenSelecting)
  2021. drawSelectionCursor(cm, range, curFragment);
  2022. if (!collapsed)
  2023. drawSelectionRange(cm, range, selFragment);
  2024. }
  2025. return result;
  2026. }
  2027. // Draws a cursor for the given range
  2028. function drawSelectionCursor(cm, range, output) {
  2029. var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2030. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2031. cursor.style.left = pos.left + "px";
  2032. cursor.style.top = pos.top + "px";
  2033. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2034. if (pos.other) {
  2035. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2036. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2037. otherCursor.style.display = "";
  2038. otherCursor.style.left = pos.other.left + "px";
  2039. otherCursor.style.top = pos.other.top + "px";
  2040. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2041. }
  2042. }
  2043. // Draws the given range as a highlighted selection
  2044. function drawSelectionRange(cm, range, output) {
  2045. var display = cm.display, doc = cm.doc;
  2046. var fragment = document.createDocumentFragment();
  2047. var padding = paddingH(cm.display), leftSide = padding.left;
  2048. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2049. function add(left, top, width, bottom) {
  2050. if (top < 0) top = 0;
  2051. top = Math.round(top);
  2052. bottom = Math.round(bottom);
  2053. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  2054. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  2055. "px; height: " + (bottom - top) + "px"));
  2056. }
  2057. function drawForLine(line, fromArg, toArg) {
  2058. var lineObj = getLine(doc, line);
  2059. var lineLen = lineObj.text.length;
  2060. var start, end;
  2061. function coords(ch, bias) {
  2062. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2063. }
  2064. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
  2065. var leftPos = coords(from, "left"), rightPos, left, right;
  2066. if (from == to) {
  2067. rightPos = leftPos;
  2068. left = right = leftPos.left;
  2069. } else {
  2070. rightPos = coords(to - 1, "right");
  2071. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2072. left = leftPos.left;
  2073. right = rightPos.right;
  2074. }
  2075. if (fromArg == null && from == 0) left = leftSide;
  2076. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2077. add(left, leftPos.top, null, leftPos.bottom);
  2078. left = leftSide;
  2079. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2080. }
  2081. if (toArg == null && to == lineLen) right = rightSide;
  2082. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2083. start = leftPos;
  2084. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2085. end = rightPos;
  2086. if (left < leftSide + 1) left = leftSide;
  2087. add(left, rightPos.top, right - left, rightPos.bottom);
  2088. });
  2089. return { start: start, end: end };
  2090. }
  2091. var sFrom = range.from(), sTo = range.to();
  2092. if (sFrom.line == sTo.line) {
  2093. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2094. } else {
  2095. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2096. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2097. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2098. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2099. if (singleVLine) {
  2100. if (leftEnd.top < rightStart.top - 2) {
  2101. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2102. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2103. } else {
  2104. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2105. }
  2106. }
  2107. if (leftEnd.bottom < rightStart.top)
  2108. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2109. }
  2110. output.appendChild(fragment);
  2111. }
  2112. // Cursor-blinking
  2113. function restartBlink(cm) {
  2114. if (!cm.state.focused) return;
  2115. var display = cm.display;
  2116. clearInterval(display.blinker);
  2117. var on = true;
  2118. display.cursorDiv.style.visibility = "";
  2119. if (cm.options.cursorBlinkRate > 0)
  2120. display.blinker = setInterval(function () {
  2121. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2122. }, cm.options.cursorBlinkRate);
  2123. else if (cm.options.cursorBlinkRate < 0)
  2124. display.cursorDiv.style.visibility = "hidden";
  2125. }
  2126. // HIGHLIGHT WORKER
  2127. function startWorker(cm, time) {
  2128. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2129. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2130. }
  2131. function highlightWorker(cm) {
  2132. var doc = cm.doc;
  2133. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2134. if (doc.frontier >= cm.display.viewTo) return;
  2135. var end = +new Date + cm.options.workTime;
  2136. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2137. var changedLines = [];
  2138. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  2139. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2140. var oldStyles = line.styles;
  2141. var highlighted = highlightLine(cm, line, state, true);
  2142. line.styles = highlighted.styles;
  2143. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2144. if (newCls) line.styleClasses = newCls;
  2145. else if (oldCls) line.styleClasses = null;
  2146. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2147. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2148. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2149. if (ischange) changedLines.push(doc.frontier);
  2150. line.stateAfter = copyState(doc.mode, state);
  2151. } else {
  2152. processLine(cm, line.text, state);
  2153. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2154. }
  2155. ++doc.frontier;
  2156. if (+new Date > end) {
  2157. startWorker(cm, cm.options.workDelay);
  2158. return true;
  2159. }
  2160. });
  2161. if (changedLines.length) runInOp(cm, function () {
  2162. for (var i = 0; i < changedLines.length; i++)
  2163. regLineChange(cm, changedLines[i], "text");
  2164. });
  2165. }
  2166. // Finds the line to start with when starting a parse. Tries to
  2167. // find a line with a stateAfter, so that it can start with a
  2168. // valid state. If that fails, it returns the line with the
  2169. // smallest indentation, which tends to need the least context to
  2170. // parse correctly.
  2171. function findStartLine(cm, n, precise) {
  2172. var minindent, minline, doc = cm.doc;
  2173. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2174. for (var search = n; search > lim; --search) {
  2175. if (search <= doc.first) return doc.first;
  2176. var line = getLine(doc, search - 1);
  2177. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2178. var indented = countColumn(line.text, null, cm.options.tabSize);
  2179. if (minline == null || minindent > indented) {
  2180. minline = search - 1;
  2181. minindent = indented;
  2182. }
  2183. }
  2184. return minline;
  2185. }
  2186. function getStateBefore(cm, n, precise) {
  2187. var doc = cm.doc, display = cm.display;
  2188. if (!doc.mode.startState) return true;
  2189. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos - 1).stateAfter;
  2190. if (!state) state = startState(doc.mode);
  2191. else state = copyState(doc.mode, state);
  2192. doc.iter(pos, n, function (line) {
  2193. processLine(cm, line.text, state);
  2194. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2195. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2196. ++pos;
  2197. });
  2198. if (precise) doc.frontier = pos;
  2199. return state;
  2200. }
  2201. // POSITION MEASUREMENT
  2202. function paddingTop(display) { return display.lineSpace.offsetTop; }
  2203. function paddingVert(display) { return display.mover.offsetHeight - display.lineSpace.offsetHeight; }
  2204. function paddingH(display) {
  2205. if (display.cachedPaddingH) return display.cachedPaddingH;
  2206. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2207. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2208. var data = { left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight) };
  2209. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2210. return data;
  2211. }
  2212. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2213. function displayWidth(cm) {
  2214. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2215. }
  2216. function displayHeight(cm) {
  2217. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2218. }
  2219. // Ensure the lineView.wrapping.heights array is populated. This is
  2220. // an array of bottom offsets for the lines that make up a drawn
  2221. // line. When lineWrapping is on, there might be more than one
  2222. // height.
  2223. function ensureLineHeights(cm, lineView, rect) {
  2224. var wrapping = cm.options.lineWrapping;
  2225. var curWidth = wrapping && displayWidth(cm);
  2226. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2227. var heights = lineView.measure.heights = [];
  2228. if (wrapping) {
  2229. lineView.measure.width = curWidth;
  2230. var rects = lineView.text.firstChild.getClientRects();
  2231. for (var i = 0; i < rects.length - 1; i++) {
  2232. var cur = rects[i], next = rects[i + 1];
  2233. if (Math.abs(cur.bottom - next.bottom) > 2)
  2234. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2235. }
  2236. }
  2237. heights.push(rect.bottom - rect.top);
  2238. }
  2239. }
  2240. // Find a line map (mapping character offsets to text nodes) and a
  2241. // measurement cache for the given line number. (A line view might
  2242. // contain multiple lines when collapsed ranges are present.)
  2243. function mapFromLineView(lineView, line, lineN) {
  2244. if (lineView.line == line)
  2245. return { map: lineView.measure.map, cache: lineView.measure.cache };
  2246. for (var i = 0; i < lineView.rest.length; i++)
  2247. if (lineView.rest[i] == line)
  2248. return { map: lineView.measure.maps[i], cache: lineView.measure.caches[i] };
  2249. for (var i = 0; i < lineView.rest.length; i++)
  2250. if (lineNo(lineView.rest[i]) > lineN)
  2251. return { map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true };
  2252. }
  2253. // Render a line into the hidden node display.externalMeasured. Used
  2254. // when measurement is needed for a line that's not in the viewport.
  2255. function updateExternalMeasurement(cm, line) {
  2256. line = visualLine(line);
  2257. var lineN = lineNo(line);
  2258. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2259. view.lineN = lineN;
  2260. var built = view.built = buildLineContent(cm, view);
  2261. view.text = built.pre;
  2262. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2263. return view;
  2264. }
  2265. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2266. // for a given character.
  2267. function measureChar(cm, line, ch, bias) {
  2268. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2269. }
  2270. // Find a line view that corresponds to the given line number.
  2271. function findViewForLine(cm, lineN) {
  2272. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2273. return cm.display.view[findViewIndex(cm, lineN)];
  2274. var ext = cm.display.externalMeasured;
  2275. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2276. return ext;
  2277. }
  2278. // Measurement can be split in two steps, the set-up work that
  2279. // applies to the whole line, and the measurement of the actual
  2280. // character. Functions like coordsChar, that need to do a lot of
  2281. // measurements in a row, can thus ensure that the set-up work is
  2282. // only done once.
  2283. function prepareMeasureForLine(cm, line) {
  2284. var lineN = lineNo(line);
  2285. var view = findViewForLine(cm, lineN);
  2286. if (view && !view.text)
  2287. view = null;
  2288. else if (view && view.changes)
  2289. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2290. if (!view)
  2291. view = updateExternalMeasurement(cm, line);
  2292. var info = mapFromLineView(view, line, lineN);
  2293. return {
  2294. line: line, view: view, rect: null,
  2295. map: info.map, cache: info.cache, before: info.before,
  2296. hasHeights: false
  2297. };
  2298. }
  2299. // Given a prepared measurement object, measures the position of an
  2300. // actual character (or fetches it from the cache).
  2301. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2302. if (prepared.before) ch = -1;
  2303. var key = ch + (bias || ""), found;
  2304. if (prepared.cache.hasOwnProperty(key)) {
  2305. found = prepared.cache[key];
  2306. } else {
  2307. if (!prepared.rect)
  2308. prepared.rect = prepared.view.text.getBoundingClientRect();
  2309. if (!prepared.hasHeights) {
  2310. ensureLineHeights(cm, prepared.view, prepared.rect);
  2311. prepared.hasHeights = true;
  2312. }
  2313. found = measureCharInner(cm, prepared, ch, bias);
  2314. if (!found.bogus) prepared.cache[key] = found;
  2315. }
  2316. return {
  2317. left: found.left, right: found.right,
  2318. top: varHeight ? found.rtop : found.top,
  2319. bottom: varHeight ? found.rbottom : found.bottom
  2320. };
  2321. }
  2322. var nullRect = { left: 0, right: 0, top: 0, bottom: 0 };
  2323. function nodeAndOffsetInLineMap(map, ch, bias) {
  2324. var node, start, end, collapse;
  2325. // First, search the line map for the text node corresponding to,
  2326. // or closest to, the target character.
  2327. for (var i = 0; i < map.length; i += 3) {
  2328. var mStart = map[i], mEnd = map[i + 1];
  2329. if (ch < mStart) {
  2330. start = 0; end = 1;
  2331. collapse = "left";
  2332. } else if (ch < mEnd) {
  2333. start = ch - mStart;
  2334. end = start + 1;
  2335. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2336. end = mEnd - mStart;
  2337. start = end - 1;
  2338. if (ch >= mEnd) collapse = "right";
  2339. }
  2340. if (start != null) {
  2341. node = map[i + 2];
  2342. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2343. collapse = bias;
  2344. if (bias == "left" && start == 0)
  2345. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2346. node = map[(i -= 3) + 2];
  2347. collapse = "left";
  2348. }
  2349. if (bias == "right" && start == mEnd - mStart)
  2350. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2351. node = map[(i += 3) + 2];
  2352. collapse = "right";
  2353. }
  2354. break;
  2355. }
  2356. }
  2357. return { node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd };
  2358. }
  2359. function measureCharInner(cm, prepared, ch, bias) {
  2360. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2361. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2362. var rect;
  2363. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2364. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2365. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start)))--start;
  2366. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end)))++end;
  2367. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2368. rect = node.parentNode.getBoundingClientRect();
  2369. } else if (ie && cm.options.lineWrapping) {
  2370. var rects = range(node, start, end).getClientRects();
  2371. if (rects.length)
  2372. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2373. else
  2374. rect = nullRect;
  2375. } else {
  2376. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  2377. }
  2378. if (rect.left || rect.right || start == 0) break;
  2379. end = start;
  2380. start = start - 1;
  2381. collapse = "right";
  2382. }
  2383. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2384. } else { // If it is a widget, simply get the box for the whole widget.
  2385. if (start > 0) collapse = bias = "right";
  2386. var rects;
  2387. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2388. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2389. else
  2390. rect = node.getBoundingClientRect();
  2391. }
  2392. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2393. var rSpan = node.parentNode.getClientRects()[0];
  2394. if (rSpan)
  2395. rect = { left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom };
  2396. else
  2397. rect = nullRect;
  2398. }
  2399. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2400. var mid = (rtop + rbot) / 2;
  2401. var heights = prepared.view.measure.heights;
  2402. for (var i = 0; i < heights.length - 1; i++)
  2403. if (mid < heights[i]) break;
  2404. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2405. var result = {
  2406. left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2407. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2408. top: top, bottom: bot
  2409. };
  2410. if (!rect.left && !rect.right) result.bogus = true;
  2411. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2412. return result;
  2413. }
  2414. // Work around problem with bounding client rects on ranges being
  2415. // returned incorrectly when zoomed on IE10 and below.
  2416. function maybeUpdateRectForZooming(measure, rect) {
  2417. if (!window.screen || screen.logicalXDPI == null ||
  2418. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2419. return rect;
  2420. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2421. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2422. return {
  2423. left: rect.left * scaleX, right: rect.right * scaleX,
  2424. top: rect.top * scaleY, bottom: rect.bottom * scaleY
  2425. };
  2426. }
  2427. function clearLineMeasurementCacheFor(lineView) {
  2428. if (lineView.measure) {
  2429. lineView.measure.cache = {};
  2430. lineView.measure.heights = null;
  2431. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2432. lineView.measure.caches[i] = {};
  2433. }
  2434. }
  2435. function clearLineMeasurementCache(cm) {
  2436. cm.display.externalMeasure = null;
  2437. removeChildren(cm.display.lineMeasure);
  2438. for (var i = 0; i < cm.display.view.length; i++)
  2439. clearLineMeasurementCacheFor(cm.display.view[i]);
  2440. }
  2441. function clearCaches(cm) {
  2442. clearLineMeasurementCache(cm);
  2443. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2444. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2445. cm.display.lineNumChars = null;
  2446. }
  2447. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2448. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2449. // Converts a {top, bottom, left, right} box from line-local
  2450. // coordinates into another coordinate system. Context may be one of
  2451. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2452. // or "page".
  2453. function intoCoordSystem(cm, lineObj, rect, context) {
  2454. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2455. var size = widgetHeight(lineObj.widgets[i]);
  2456. rect.top += size; rect.bottom += size;
  2457. }
  2458. if (context == "line") return rect;
  2459. if (!context) context = "local";
  2460. var yOff = heightAtLine(lineObj);
  2461. if (context == "local") yOff += paddingTop(cm.display);
  2462. else yOff -= cm.display.viewOffset;
  2463. if (context == "page" || context == "window") {
  2464. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2465. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2466. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2467. rect.left += xOff; rect.right += xOff;
  2468. }
  2469. rect.top += yOff; rect.bottom += yOff;
  2470. return rect;
  2471. }
  2472. // Coverts a box from "div" coords to another coordinate system.
  2473. // Context may be "window", "page", "div", or "local"/null.
  2474. function fromCoordSystem(cm, coords, context) {
  2475. if (context == "div") return coords;
  2476. var left = coords.left, top = coords.top;
  2477. // First move into "page" coordinate system
  2478. if (context == "page") {
  2479. left -= pageScrollX();
  2480. top -= pageScrollY();
  2481. } else if (context == "local" || !context) {
  2482. var localBox = cm.display.sizer.getBoundingClientRect();
  2483. left += localBox.left;
  2484. top += localBox.top;
  2485. }
  2486. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2487. return { left: left - lineSpaceBox.left, top: top - lineSpaceBox.top };
  2488. }
  2489. function charCoords(cm, pos, context, lineObj, bias) {
  2490. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2491. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2492. }
  2493. // Returns a box for a given cursor position, which may have an
  2494. // 'other' property containing the position of the secondary cursor
  2495. // on a bidi boundary.
  2496. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2497. lineObj = lineObj || getLine(cm.doc, pos.line);
  2498. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2499. function get(ch, right) {
  2500. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2501. if (right) m.left = m.right; else m.right = m.left;
  2502. return intoCoordSystem(cm, lineObj, m, context);
  2503. }
  2504. function getBidi(ch, partPos) {
  2505. var part = order[partPos], right = part.level % 2;
  2506. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2507. part = order[--partPos];
  2508. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2509. right = true;
  2510. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2511. part = order[++partPos];
  2512. ch = bidiLeft(part) - part.level % 2;
  2513. right = false;
  2514. }
  2515. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2516. return get(ch, right);
  2517. }
  2518. var order = getOrder(lineObj), ch = pos.ch;
  2519. if (!order) return get(ch);
  2520. var partPos = getBidiPartAt(order, ch);
  2521. var val = getBidi(ch, partPos);
  2522. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2523. return val;
  2524. }
  2525. // Used to cheaply estimate the coordinates for a position. Used for
  2526. // intermediate scroll updates.
  2527. function estimateCoords(cm, pos) {
  2528. var left = 0, pos = clipPos(cm.doc, pos);
  2529. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2530. var lineObj = getLine(cm.doc, pos.line);
  2531. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2532. return { left: left, right: left, top: top, bottom: top + lineObj.height };
  2533. }
  2534. // Positions returned by coordsChar contain some extra information.
  2535. // xRel is the relative x position of the input coordinates compared
  2536. // to the found position (so xRel > 0 means the coordinates are to
  2537. // the right of the character position, for example). When outside
  2538. // is true, that means the coordinates lie outside the line's
  2539. // vertical range.
  2540. function PosWithInfo(line, ch, outside, xRel) {
  2541. var pos = Pos(line, ch);
  2542. pos.xRel = xRel;
  2543. if (outside) pos.outside = true;
  2544. return pos;
  2545. }
  2546. // Compute the character position closest to the given coordinates.
  2547. // Input must be lineSpace-local ("div" coordinate system).
  2548. function coordsChar(cm, x, y) {
  2549. var doc = cm.doc;
  2550. y += cm.display.viewOffset;
  2551. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2552. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2553. if (lineN > last)
  2554. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2555. if (x < 0) x = 0;
  2556. var lineObj = getLine(doc, lineN);
  2557. for (; ;) {
  2558. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2559. var merged = collapsedSpanAtEnd(lineObj);
  2560. var mergedPos = merged && merged.find(0, true);
  2561. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2562. lineN = lineNo(lineObj = mergedPos.to.line);
  2563. else
  2564. return found;
  2565. }
  2566. }
  2567. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2568. var innerOff = y - heightAtLine(lineObj);
  2569. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2570. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2571. function getX(ch) {
  2572. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2573. wrongLine = true;
  2574. if (innerOff > sp.bottom) return sp.left - adjust;
  2575. else if (innerOff < sp.top) return sp.left + adjust;
  2576. else wrongLine = false;
  2577. return sp.left;
  2578. }
  2579. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2580. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2581. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2582. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2583. // Do a binary search between these bounds.
  2584. for (; ;) {
  2585. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2586. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2587. var xDiff = x - (ch == from ? fromX : toX);
  2588. while (isExtendingChar(lineObj.text.charAt(ch)))++ch;
  2589. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  2590. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2591. return pos;
  2592. }
  2593. var step = Math.ceil(dist / 2), middle = from + step;
  2594. if (bidi) {
  2595. middle = from;
  2596. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2597. }
  2598. var middleX = getX(middle);
  2599. if (middleX > x) { to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step; }
  2600. else { from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step; }
  2601. }
  2602. }
  2603. var measureText;
  2604. // Compute the default text height.
  2605. function textHeight(display) {
  2606. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2607. if (measureText == null) {
  2608. measureText = elt("pre");
  2609. // Measure a bunch of lines, for browsers that compute
  2610. // fractional heights.
  2611. for (var i = 0; i < 49; ++i) {
  2612. measureText.appendChild(document.createTextNode("x"));
  2613. measureText.appendChild(elt("br"));
  2614. }
  2615. measureText.appendChild(document.createTextNode("x"));
  2616. }
  2617. removeChildrenAndAdd(display.measure, measureText);
  2618. var height = measureText.offsetHeight / 50;
  2619. if (height > 3) display.cachedTextHeight = height;
  2620. removeChildren(display.measure);
  2621. return height || 1;
  2622. }
  2623. // Compute the default character width.
  2624. function charWidth(display) {
  2625. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2626. var anchor = elt("span", "xxxxxxxxxx");
  2627. var pre = elt("pre", [anchor]);
  2628. removeChildrenAndAdd(display.measure, pre);
  2629. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2630. if (width > 2) display.cachedCharWidth = width;
  2631. return width || 10;
  2632. }
  2633. // OPERATIONS
  2634. // Operations are used to wrap a series of changes to the editor
  2635. // state in such a way that each change won't have to update the
  2636. // cursor and display (which would be awkward, slow, and
  2637. // error-prone). Instead, display updates are batched and then all
  2638. // combined and executed at once.
  2639. var operationGroup = null;
  2640. var nextOpId = 0;
  2641. // Start a new operation.
  2642. function startOperation(cm) {
  2643. cm.curOp = {
  2644. cm: cm,
  2645. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2646. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2647. forceUpdate: false, // Used to force a redraw
  2648. updateInput: null, // Whether to reset the input textarea
  2649. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2650. changeObjs: null, // Accumulated changes, for firing change events
  2651. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2652. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2653. selectionChanged: false, // Whether the selection needs to be redrawn
  2654. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2655. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2656. scrollToPos: null, // Used to scroll to a specific position
  2657. focus: false,
  2658. id: ++nextOpId // Unique ID
  2659. };
  2660. if (operationGroup) {
  2661. operationGroup.ops.push(cm.curOp);
  2662. } else {
  2663. cm.curOp.ownsGroup = operationGroup = {
  2664. ops: [cm.curOp],
  2665. delayedCallbacks: []
  2666. };
  2667. }
  2668. }
  2669. function fireCallbacksForOps(group) {
  2670. // Calls delayed callbacks and cursorActivity handlers until no
  2671. // new ones appear
  2672. var callbacks = group.delayedCallbacks, i = 0;
  2673. do {
  2674. for (; i < callbacks.length; i++)
  2675. callbacks[i]();
  2676. for (var j = 0; j < group.ops.length; j++) {
  2677. var op = group.ops[j];
  2678. if (op.cursorActivityHandlers)
  2679. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2680. op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);
  2681. }
  2682. } while (i < callbacks.length);
  2683. }
  2684. // Finish an operation, updating the display and signalling delayed events
  2685. function endOperation(cm) {
  2686. var op = cm.curOp, group = op.ownsGroup;
  2687. if (!group) return;
  2688. try { fireCallbacksForOps(group); }
  2689. finally {
  2690. operationGroup = null;
  2691. for (var i = 0; i < group.ops.length; i++)
  2692. group.ops[i].cm.curOp = null;
  2693. endOperations(group);
  2694. }
  2695. }
  2696. // The DOM updates done when an operation finishes are batched so
  2697. // that the minimum number of relayouts are required.
  2698. function endOperations(group) {
  2699. var ops = group.ops;
  2700. for (var i = 0; i < ops.length; i++) // Read DOM
  2701. endOperation_R1(ops[i]);
  2702. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2703. endOperation_W1(ops[i]);
  2704. for (var i = 0; i < ops.length; i++) // Read DOM
  2705. endOperation_R2(ops[i]);
  2706. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2707. endOperation_W2(ops[i]);
  2708. for (var i = 0; i < ops.length; i++) // Read DOM
  2709. endOperation_finish(ops[i]);
  2710. }
  2711. function endOperation_R1(op) {
  2712. var cm = op.cm, display = cm.display;
  2713. maybeClipScrollbars(cm);
  2714. if (op.updateMaxLine) findMaxLine(cm);
  2715. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2716. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2717. op.scrollToPos.to.line >= display.viewTo) ||
  2718. display.maxLineChanged && cm.options.lineWrapping;
  2719. op.update = op.mustUpdate &&
  2720. new DisplayUpdate(cm, op.mustUpdate && { top: op.scrollTop, ensure: op.scrollToPos }, op.forceUpdate);
  2721. }
  2722. function endOperation_W1(op) {
  2723. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2724. }
  2725. function endOperation_R2(op) {
  2726. var cm = op.cm, display = cm.display;
  2727. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2728. op.barMeasure = measureForScrollbars(cm);
  2729. // If the max line changed since it was last measured, measure it,
  2730. // and ensure the document's width matches it.
  2731. // updateDisplay_W2 will use these properties to do the actual resizing
  2732. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2733. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2734. cm.display.sizerWidth = op.adjustWidthTo;
  2735. op.barMeasure.scrollWidth =
  2736. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2737. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2738. }
  2739. if (op.updatedDisplay || op.selectionChanged)
  2740. op.preparedSelection = display.input.prepareSelection();
  2741. }
  2742. function endOperation_W2(op) {
  2743. var cm = op.cm;
  2744. if (op.adjustWidthTo != null) {
  2745. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2746. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2747. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2748. cm.display.maxLineChanged = false;
  2749. }
  2750. if (op.preparedSelection)
  2751. cm.display.input.showSelection(op.preparedSelection);
  2752. if (op.updatedDisplay)
  2753. setDocumentHeight(cm, op.barMeasure);
  2754. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2755. updateScrollbars(cm, op.barMeasure);
  2756. if (op.selectionChanged) restartBlink(cm);
  2757. if (cm.state.focused && op.updateInput)
  2758. cm.display.input.reset(op.typing);
  2759. if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
  2760. }
  2761. function endOperation_finish(op) {
  2762. var cm = op.cm, display = cm.display, doc = cm.doc;
  2763. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2764. // Abort mouse wheel delta measurement, when scrolling explicitly
  2765. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2766. display.wheelStartX = display.wheelStartY = null;
  2767. // Propagate the scroll position to the actual DOM scroller
  2768. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2769. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2770. display.scrollbars.setScrollTop(doc.scrollTop);
  2771. display.scroller.scrollTop = doc.scrollTop;
  2772. }
  2773. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2774. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
  2775. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2776. display.scroller.scrollLeft = doc.scrollLeft;
  2777. alignHorizontally(cm);
  2778. }
  2779. // If we need to scroll a specific position into view, do so.
  2780. if (op.scrollToPos) {
  2781. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2782. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2783. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2784. }
  2785. // Fire events for markers that are hidden/unidden by editing or
  2786. // undoing
  2787. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2788. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2789. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2790. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2791. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2792. if (display.wrapper.offsetHeight)
  2793. doc.scrollTop = cm.display.scroller.scrollTop;
  2794. // Fire change events, and delayed event handlers
  2795. if (op.changeObjs)
  2796. signal(cm, "changes", cm, op.changeObjs);
  2797. if (op.update)
  2798. op.update.finish();
  2799. }
  2800. // Run the given function in an operation
  2801. function runInOp(cm, f) {
  2802. if (cm.curOp) return f();
  2803. startOperation(cm);
  2804. try { return f(); }
  2805. finally { endOperation(cm); }
  2806. }
  2807. // Wraps a function in an operation. Returns the wrapped function.
  2808. function operation(cm, f) {
  2809. return function () {
  2810. if (cm.curOp) return f.apply(cm, arguments);
  2811. startOperation(cm);
  2812. try { return f.apply(cm, arguments); }
  2813. finally { endOperation(cm); }
  2814. };
  2815. }
  2816. // Used to add methods to editor and doc instances, wrapping them in
  2817. // operations.
  2818. function methodOp(f) {
  2819. return function () {
  2820. if (this.curOp) return f.apply(this, arguments);
  2821. startOperation(this);
  2822. try { return f.apply(this, arguments); }
  2823. finally { endOperation(this); }
  2824. };
  2825. }
  2826. function docMethodOp(f) {
  2827. return function () {
  2828. var cm = this.cm;
  2829. if (!cm || cm.curOp) return f.apply(this, arguments);
  2830. startOperation(cm);
  2831. try { return f.apply(this, arguments); }
  2832. finally { endOperation(cm); }
  2833. };
  2834. }
  2835. // VIEW TRACKING
  2836. // These objects are used to represent the visible (currently drawn)
  2837. // part of the document. A LineView may correspond to multiple
  2838. // logical lines, if those are connected by collapsed ranges.
  2839. function LineView(doc, line, lineN) {
  2840. // The starting line
  2841. this.line = line;
  2842. // Continuing lines, if any
  2843. this.rest = visualLineContinued(line);
  2844. // Number of logical lines in this visual line
  2845. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2846. this.node = this.text = null;
  2847. this.hidden = lineIsHidden(doc, line);
  2848. }
  2849. // Create a range of LineView objects for the given lines.
  2850. function buildViewArray(cm, from, to) {
  2851. var array = [], nextPos;
  2852. for (var pos = from; pos < to; pos = nextPos) {
  2853. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2854. nextPos = pos + view.size;
  2855. array.push(view);
  2856. }
  2857. return array;
  2858. }
  2859. // Updates the display.view data structure for a given change to the
  2860. // document. From and to are in pre-change coordinates. Lendiff is
  2861. // the amount of lines added or subtracted by the change. This is
  2862. // used for changes that span multiple lines, or change the way
  2863. // lines are divided into visual lines. regLineChange (below)
  2864. // registers single-line changes.
  2865. function regChange(cm, from, to, lendiff) {
  2866. if (from == null) from = cm.doc.first;
  2867. if (to == null) to = cm.doc.first + cm.doc.size;
  2868. if (!lendiff) lendiff = 0;
  2869. var display = cm.display;
  2870. if (lendiff && to < display.viewTo &&
  2871. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2872. display.updateLineNumbers = from;
  2873. cm.curOp.viewChanged = true;
  2874. if (from >= display.viewTo) { // Change after
  2875. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2876. resetView(cm);
  2877. } else if (to <= display.viewFrom) { // Change before
  2878. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2879. resetView(cm);
  2880. } else {
  2881. display.viewFrom += lendiff;
  2882. display.viewTo += lendiff;
  2883. }
  2884. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2885. resetView(cm);
  2886. } else if (from <= display.viewFrom) { // Top overlap
  2887. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2888. if (cut) {
  2889. display.view = display.view.slice(cut.index);
  2890. display.viewFrom = cut.lineN;
  2891. display.viewTo += lendiff;
  2892. } else {
  2893. resetView(cm);
  2894. }
  2895. } else if (to >= display.viewTo) { // Bottom overlap
  2896. var cut = viewCuttingPoint(cm, from, from, -1);
  2897. if (cut) {
  2898. display.view = display.view.slice(0, cut.index);
  2899. display.viewTo = cut.lineN;
  2900. } else {
  2901. resetView(cm);
  2902. }
  2903. } else { // Gap in the middle
  2904. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2905. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2906. if (cutTop && cutBot) {
  2907. display.view = display.view.slice(0, cutTop.index)
  2908. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2909. .concat(display.view.slice(cutBot.index));
  2910. display.viewTo += lendiff;
  2911. } else {
  2912. resetView(cm);
  2913. }
  2914. }
  2915. var ext = display.externalMeasured;
  2916. if (ext) {
  2917. if (to < ext.lineN)
  2918. ext.lineN += lendiff;
  2919. else if (from < ext.lineN + ext.size)
  2920. display.externalMeasured = null;
  2921. }
  2922. }
  2923. // Register a change to a single line. Type must be one of "text",
  2924. // "gutter", "class", "widget"
  2925. function regLineChange(cm, line, type) {
  2926. cm.curOp.viewChanged = true;
  2927. var display = cm.display, ext = cm.display.externalMeasured;
  2928. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2929. display.externalMeasured = null;
  2930. if (line < display.viewFrom || line >= display.viewTo) return;
  2931. var lineView = display.view[findViewIndex(cm, line)];
  2932. if (lineView.node == null) return;
  2933. var arr = lineView.changes || (lineView.changes = []);
  2934. if (indexOf(arr, type) == -1) arr.push(type);
  2935. }
  2936. // Clear the view.
  2937. function resetView(cm) {
  2938. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2939. cm.display.view = [];
  2940. cm.display.viewOffset = 0;
  2941. }
  2942. // Find the view element corresponding to a given line. Return null
  2943. // when the line isn't visible.
  2944. function findViewIndex(cm, n) {
  2945. if (n >= cm.display.viewTo) return null;
  2946. n -= cm.display.viewFrom;
  2947. if (n < 0) return null;
  2948. var view = cm.display.view;
  2949. for (var i = 0; i < view.length; i++) {
  2950. n -= view[i].size;
  2951. if (n < 0) return i;
  2952. }
  2953. }
  2954. function viewCuttingPoint(cm, oldN, newN, dir) {
  2955. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2956. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2957. return { index: index, lineN: newN };
  2958. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2959. n += view[i].size;
  2960. if (n != oldN) {
  2961. if (dir > 0) {
  2962. if (index == view.length - 1) return null;
  2963. diff = (n + view[index].size) - oldN;
  2964. index++;
  2965. } else {
  2966. diff = n - oldN;
  2967. }
  2968. oldN += diff; newN += diff;
  2969. }
  2970. while (visualLineNo(cm.doc, newN) != newN) {
  2971. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  2972. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2973. index += dir;
  2974. }
  2975. return { index: index, lineN: newN };
  2976. }
  2977. // Force the view to cover a given range, adding empty view element
  2978. // or clipping off existing ones as needed.
  2979. function adjustView(cm, from, to) {
  2980. var display = cm.display, view = display.view;
  2981. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2982. display.view = buildViewArray(cm, from, to);
  2983. display.viewFrom = from;
  2984. } else {
  2985. if (display.viewFrom > from)
  2986. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  2987. else if (display.viewFrom < from)
  2988. display.view = display.view.slice(findViewIndex(cm, from));
  2989. display.viewFrom = from;
  2990. if (display.viewTo < to)
  2991. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  2992. else if (display.viewTo > to)
  2993. display.view = display.view.slice(0, findViewIndex(cm, to));
  2994. }
  2995. display.viewTo = to;
  2996. }
  2997. // Count the number of lines in the view whose DOM representation is
  2998. // out of date (or nonexistent).
  2999. function countDirtyView(cm) {
  3000. var view = cm.display.view, dirty = 0;
  3001. for (var i = 0; i < view.length; i++) {
  3002. var lineView = view[i];
  3003. if (!lineView.hidden && (!lineView.node || lineView.changes))++dirty;
  3004. }
  3005. return dirty;
  3006. }
  3007. // EVENT HANDLERS
  3008. // Attach the necessary event handlers when initializing the editor
  3009. function registerEventHandlers(cm) {
  3010. var d = cm.display;
  3011. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  3012. // Older IE's will not fire a second mousedown for a double click
  3013. if (ie && ie_version < 11)
  3014. on(d.scroller, "dblclick", operation(cm, function (e) {
  3015. if (signalDOMEvent(cm, e)) return;
  3016. var pos = posFromMouse(cm, e);
  3017. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  3018. e_preventDefault(e);
  3019. var word = cm.findWordAt(pos);
  3020. extendSelection(cm.doc, word.anchor, word.head);
  3021. }));
  3022. else
  3023. on(d.scroller, "dblclick", function (e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  3024. // Some browsers fire contextmenu *after* opening the menu, at
  3025. // which point we can't mess with it anymore. Context menu is
  3026. // handled in onMouseDown for these browsers.
  3027. if (!captureRightClick) on(d.scroller, "contextmenu", function (e) { onContextMenu(cm, e); });
  3028. // Used to suppress mouse event handling when a touch happens
  3029. var touchFinished, prevTouch = { end: 0 };
  3030. function finishTouch() {
  3031. if (d.activeTouch) {
  3032. touchFinished = setTimeout(function () { d.activeTouch = null; }, 1000);
  3033. prevTouch = d.activeTouch;
  3034. prevTouch.end = +new Date;
  3035. }
  3036. };
  3037. function isMouseLikeTouchEvent(e) {
  3038. if (e.touches.length != 1) return false;
  3039. var touch = e.touches[0];
  3040. return touch.radiusX <= 1 && touch.radiusY <= 1;
  3041. }
  3042. function farAway(touch, other) {
  3043. if (other.left == null) return true;
  3044. var dx = other.left - touch.left, dy = other.top - touch.top;
  3045. return dx * dx + dy * dy > 20 * 20;
  3046. }
  3047. on(d.scroller, "touchstart", function (e) {
  3048. if (!isMouseLikeTouchEvent(e)) {
  3049. clearTimeout(touchFinished);
  3050. var now = +new Date;
  3051. d.activeTouch = {
  3052. start: now, moved: false,
  3053. prev: now - prevTouch.end <= 300 ? prevTouch : null
  3054. };
  3055. if (e.touches.length == 1) {
  3056. d.activeTouch.left = e.touches[0].pageX;
  3057. d.activeTouch.top = e.touches[0].pageY;
  3058. }
  3059. }
  3060. });
  3061. on(d.scroller, "touchmove", function () {
  3062. if (d.activeTouch) d.activeTouch.moved = true;
  3063. });
  3064. on(d.scroller, "touchend", function (e) {
  3065. var touch = d.activeTouch;
  3066. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3067. !touch.moved && new Date - touch.start < 300) {
  3068. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3069. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3070. range = new Range(pos, pos);
  3071. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3072. range = cm.findWordAt(pos);
  3073. else // Triple tap
  3074. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3075. cm.setSelection(range.anchor, range.head);
  3076. cm.focus();
  3077. e_preventDefault(e);
  3078. }
  3079. finishTouch();
  3080. });
  3081. on(d.scroller, "touchcancel", finishTouch);
  3082. // Sync scrolling between fake scrollbars and real scrollable
  3083. // area, ensure viewport is updated when scrolling.
  3084. on(d.scroller, "scroll", function () {
  3085. if (d.scroller.clientHeight) {
  3086. setScrollTop(cm, d.scroller.scrollTop);
  3087. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3088. signal(cm, "scroll", cm);
  3089. }
  3090. });
  3091. // Listen to wheel events in order to try and update the viewport on time.
  3092. on(d.scroller, "mousewheel", function (e) { onScrollWheel(cm, e); });
  3093. on(d.scroller, "DOMMouseScroll", function (e) { onScrollWheel(cm, e); });
  3094. // Prevent wrapper from ever scrolling
  3095. on(d.wrapper, "scroll", function () { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3096. d.dragFunctions = {
  3097. simple: function (e) { if (!signalDOMEvent(cm, e)) e_stop(e); },
  3098. start: function (e) { onDragStart(cm, e); },
  3099. drop: operation(cm, onDrop)
  3100. };
  3101. var inp = d.input.getField();
  3102. on(inp, "keyup", function (e) { onKeyUp.call(cm, e); });
  3103. on(inp, "keydown", operation(cm, onKeyDown));
  3104. on(inp, "keypress", operation(cm, onKeyPress));
  3105. on(inp, "focus", bind(onFocus, cm));
  3106. on(inp, "blur", bind(onBlur, cm));
  3107. }
  3108. function dragDropChanged(cm, value, old) {
  3109. var wasOn = old && old != CodeMirror.Init;
  3110. if (!value != !wasOn) {
  3111. var funcs = cm.display.dragFunctions;
  3112. var toggle = value ? on : off;
  3113. toggle(cm.display.scroller, "dragstart", funcs.start);
  3114. toggle(cm.display.scroller, "dragenter", funcs.simple);
  3115. toggle(cm.display.scroller, "dragover", funcs.simple);
  3116. toggle(cm.display.scroller, "drop", funcs.drop);
  3117. }
  3118. }
  3119. // Called when the window resizes
  3120. function onResize(cm) {
  3121. var d = cm.display;
  3122. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3123. return;
  3124. // Might be a text scaling operation, clear size caches.
  3125. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3126. d.scrollbarsClipped = false;
  3127. cm.setSize();
  3128. }
  3129. // MOUSE EVENTS
  3130. // Return true when the given mouse event happened in a widget
  3131. function eventInWidget(display, e) {
  3132. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3133. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3134. (n.parentNode == display.sizer && n != display.mover))
  3135. return true;
  3136. }
  3137. }
  3138. // Given a mouse event, find the corresponding position. If liberal
  3139. // is false, it checks whether a gutter or scrollbar was clicked,
  3140. // and returns null if it was. forRect is used by rectangular
  3141. // selections, and tries to estimate a character position even for
  3142. // coordinates beyond the right of the text.
  3143. function posFromMouse(cm, e, liberal, forRect) {
  3144. var display = cm.display;
  3145. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3146. var x, y, space = display.lineSpace.getBoundingClientRect();
  3147. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3148. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3149. catch (e) { return null; }
  3150. var coords = coordsChar(cm, x, y), line;
  3151. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3152. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3153. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3154. }
  3155. return coords;
  3156. }
  3157. // A mouse down can be a single click, double click, triple click,
  3158. // start of selection drag, start of text drag, new cursor
  3159. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3160. // middle-click-paste. Or it might be a click on something we should
  3161. // not interfere with, such as a scrollbar or widget.
  3162. function onMouseDown(e) {
  3163. var cm = this, display = cm.display;
  3164. if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
  3165. display.shift = e.shiftKey;
  3166. if (eventInWidget(display, e)) {
  3167. if (!webkit) {
  3168. // Briefly turn off draggability, to allow widgets to do
  3169. // normal dragging things.
  3170. display.scroller.draggable = false;
  3171. setTimeout(function () { display.scroller.draggable = true; }, 100);
  3172. }
  3173. return;
  3174. }
  3175. if (clickInGutter(cm, e)) return;
  3176. var start = posFromMouse(cm, e);
  3177. window.focus();
  3178. switch (e_button(e)) {
  3179. case 1:
  3180. if (start)
  3181. leftButtonDown(cm, e, start);
  3182. else if (e_target(e) == display.scroller)
  3183. e_preventDefault(e);
  3184. break;
  3185. case 2:
  3186. if (webkit) cm.state.lastMiddleDown = +new Date;
  3187. if (start) extendSelection(cm.doc, start);
  3188. setTimeout(function () { display.input.focus(); }, 20);
  3189. e_preventDefault(e);
  3190. break;
  3191. case 3:
  3192. if (captureRightClick) onContextMenu(cm, e);
  3193. else delayBlurEvent(cm);
  3194. break;
  3195. }
  3196. }
  3197. var lastClick, lastDoubleClick;
  3198. function leftButtonDown(cm, e, start) {
  3199. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3200. else cm.curOp.focus = activeElt();
  3201. var now = +new Date, type;
  3202. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3203. type = "triple";
  3204. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3205. type = "double";
  3206. lastDoubleClick = { time: now, pos: start };
  3207. } else {
  3208. type = "single";
  3209. lastClick = { time: now, pos: start };
  3210. }
  3211. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3212. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
  3213. type == "single" && (contained = sel.contains(start)) > -1 &&
  3214. !sel.ranges[contained].empty())
  3215. leftButtonStartDrag(cm, e, start, modifier);
  3216. else
  3217. leftButtonSelect(cm, e, start, type, modifier);
  3218. }
  3219. // Start a text drag. When it ends, see if any dragging actually
  3220. // happen, and treat as a click if it didn't.
  3221. function leftButtonStartDrag(cm, e, start, modifier) {
  3222. var display = cm.display, startTime = +new Date;
  3223. var dragEnd = operation(cm, function (e2) {
  3224. if (webkit) display.scroller.draggable = false;
  3225. cm.state.draggingText = false;
  3226. off(document, "mouseup", dragEnd);
  3227. off(display.scroller, "drop", dragEnd);
  3228. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3229. e_preventDefault(e2);
  3230. if (!modifier && +new Date - 200 < startTime)
  3231. extendSelection(cm.doc, start);
  3232. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  3233. if (webkit || ie && ie_version == 9)
  3234. setTimeout(function () { document.body.focus(); display.input.focus(); }, 20);
  3235. else
  3236. display.input.focus();
  3237. }
  3238. });
  3239. // Let the drag handler handle this.
  3240. if (webkit) display.scroller.draggable = true;
  3241. cm.state.draggingText = dragEnd;
  3242. // IE's approach to draggable
  3243. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3244. on(document, "mouseup", dragEnd);
  3245. on(display.scroller, "drop", dragEnd);
  3246. }
  3247. // Normal selection, as opposed to text dragging.
  3248. function leftButtonSelect(cm, e, start, type, addNew) {
  3249. var display = cm.display, doc = cm.doc;
  3250. e_preventDefault(e);
  3251. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3252. if (addNew && !e.shiftKey) {
  3253. ourIndex = doc.sel.contains(start);
  3254. if (ourIndex > -1)
  3255. ourRange = ranges[ourIndex];
  3256. else
  3257. ourRange = new Range(start, start);
  3258. } else {
  3259. ourRange = doc.sel.primary();
  3260. ourIndex = doc.sel.primIndex;
  3261. }
  3262. if (e.altKey) {
  3263. type = "rect";
  3264. if (!addNew) ourRange = new Range(start, start);
  3265. start = posFromMouse(cm, e, true, true);
  3266. ourIndex = -1;
  3267. } else if (type == "double") {
  3268. var word = cm.findWordAt(start);
  3269. if (cm.display.shift || doc.extend)
  3270. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3271. else
  3272. ourRange = word;
  3273. } else if (type == "triple") {
  3274. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3275. if (cm.display.shift || doc.extend)
  3276. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3277. else
  3278. ourRange = line;
  3279. } else {
  3280. ourRange = extendRange(doc, ourRange, start);
  3281. }
  3282. if (!addNew) {
  3283. ourIndex = 0;
  3284. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3285. startSel = doc.sel;
  3286. } else if (ourIndex == -1) {
  3287. ourIndex = ranges.length;
  3288. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3289. { scroll: false, origin: "*mouse" });
  3290. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  3291. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
  3292. startSel = doc.sel;
  3293. } else {
  3294. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3295. }
  3296. var lastPos = start;
  3297. function extendTo(pos) {
  3298. if (cmp(lastPos, pos) == 0) return;
  3299. lastPos = pos;
  3300. if (type == "rect") {
  3301. var ranges = [], tabSize = cm.options.tabSize;
  3302. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3303. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3304. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3305. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3306. line <= end; line++) {
  3307. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3308. if (left == right)
  3309. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3310. else if (text.length > leftPos)
  3311. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3312. }
  3313. if (!ranges.length) ranges.push(new Range(start, start));
  3314. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3315. { origin: "*mouse", scroll: false });
  3316. cm.scrollIntoView(pos);
  3317. } else {
  3318. var oldRange = ourRange;
  3319. var anchor = oldRange.anchor, head = pos;
  3320. if (type != "single") {
  3321. if (type == "double")
  3322. var range = cm.findWordAt(pos);
  3323. else
  3324. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3325. if (cmp(range.anchor, anchor) > 0) {
  3326. head = range.head;
  3327. anchor = minPos(oldRange.from(), range.anchor);
  3328. } else {
  3329. head = range.anchor;
  3330. anchor = maxPos(oldRange.to(), range.head);
  3331. }
  3332. }
  3333. var ranges = startSel.ranges.slice(0);
  3334. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3335. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3336. }
  3337. }
  3338. var editorSize = display.wrapper.getBoundingClientRect();
  3339. // Used to ensure timeout re-tries don't fire when another extend
  3340. // happened in the meantime (clearTimeout isn't reliable -- at
  3341. // least on Chrome, the timeouts still happen even when cleared,
  3342. // if the clear happens after their scheduled firing time).
  3343. var counter = 0;
  3344. function extend(e) {
  3345. var curCount = ++counter;
  3346. var cur = posFromMouse(cm, e, true, type == "rect");
  3347. if (!cur) return;
  3348. if (cmp(cur, lastPos) != 0) {
  3349. cm.curOp.focus = activeElt();
  3350. extendTo(cur);
  3351. var visible = visibleLines(display, doc);
  3352. if (cur.line >= visible.to || cur.line < visible.from)
  3353. setTimeout(operation(cm, function () { if (counter == curCount) extend(e); }), 150);
  3354. } else {
  3355. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3356. if (outside) setTimeout(operation(cm, function () {
  3357. if (counter != curCount) return;
  3358. display.scroller.scrollTop += outside;
  3359. extend(e);
  3360. }), 50);
  3361. }
  3362. }
  3363. function done(e) {
  3364. counter = Infinity;
  3365. e_preventDefault(e);
  3366. display.input.focus();
  3367. off(document, "mousemove", move);
  3368. off(document, "mouseup", up);
  3369. doc.history.lastSelOrigin = null;
  3370. }
  3371. var move = operation(cm, function (e) {
  3372. if (!e_button(e)) done(e);
  3373. else extend(e);
  3374. });
  3375. var up = operation(cm, done);
  3376. on(document, "mousemove", move);
  3377. on(document, "mouseup", up);
  3378. }
  3379. // Determines whether an event happened in the gutter, and fires the
  3380. // handlers for the corresponding event.
  3381. function gutterEvent(cm, e, type, prevent, signalfn) {
  3382. try { var mX = e.clientX, mY = e.clientY; }
  3383. catch (e) { return false; }
  3384. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3385. if (prevent) e_preventDefault(e);
  3386. var display = cm.display;
  3387. var lineBox = display.lineDiv.getBoundingClientRect();
  3388. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3389. mY -= lineBox.top - display.viewOffset;
  3390. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3391. var g = display.gutters.childNodes[i];
  3392. if (g && g.getBoundingClientRect().right >= mX) {
  3393. var line = lineAtHeight(cm.doc, mY);
  3394. var gutter = cm.options.gutters[i];
  3395. signalfn(cm, type, cm, line, gutter, e);
  3396. return e_defaultPrevented(e);
  3397. }
  3398. }
  3399. }
  3400. function clickInGutter(cm, e) {
  3401. return gutterEvent(cm, e, "gutterClick", true, signalLater);
  3402. }
  3403. // Kludge to work around strange IE behavior where it'll sometimes
  3404. // re-fire a series of drag-related events right after the drop (#1551)
  3405. var lastDrop = 0;
  3406. function onDrop(e) {
  3407. var cm = this;
  3408. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3409. return;
  3410. e_preventDefault(e);
  3411. if (ie) lastDrop = +new Date;
  3412. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3413. if (!pos || isReadOnly(cm)) return;
  3414. // Might be a file drop, in which case we simply extract the text
  3415. // and insert it.
  3416. if (files && files.length && window.FileReader && window.File) {
  3417. var n = files.length, text = Array(n), read = 0;
  3418. var loadFile = function (file, i) {
  3419. var reader = new FileReader;
  3420. reader.onload = operation(cm, function () {
  3421. text[i] = reader.result;
  3422. if (++read == n) {
  3423. pos = clipPos(cm.doc, pos);
  3424. var change = { from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste" };
  3425. makeChange(cm.doc, change);
  3426. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3427. }
  3428. });
  3429. reader.readAsText(file);
  3430. };
  3431. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3432. } else { // Normal drop
  3433. // Don't do a replace if the drop happened inside of the selected text.
  3434. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3435. cm.state.draggingText(e);
  3436. // Ensure the editor is re-focused
  3437. setTimeout(function () { cm.display.input.focus(); }, 20);
  3438. return;
  3439. }
  3440. try {
  3441. var text = e.dataTransfer.getData("Text");
  3442. if (text) {
  3443. if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
  3444. var selected = cm.listSelections();
  3445. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3446. if (selected) for (var i = 0; i < selected.length; ++i)
  3447. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3448. cm.replaceSelection(text, "around", "paste");
  3449. cm.display.input.focus();
  3450. }
  3451. }
  3452. catch (e) { }
  3453. }
  3454. }
  3455. function onDragStart(cm, e) {
  3456. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3457. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3458. e.dataTransfer.setData("Text", cm.getSelection());
  3459. // Use dummy image instead of default browsers image.
  3460. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3461. if (e.dataTransfer.setDragImage && !safari) {
  3462. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3463. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3464. if (presto) {
  3465. img.width = img.height = 1;
  3466. cm.display.wrapper.appendChild(img);
  3467. // Force a relayout, or Opera won't use our image for some obscure reason
  3468. img._top = img.offsetTop;
  3469. }
  3470. e.dataTransfer.setDragImage(img, 0, 0);
  3471. if (presto) img.parentNode.removeChild(img);
  3472. }
  3473. }
  3474. // SCROLL EVENTS
  3475. // Sync the scrollable area and scrollbars, ensure the viewport
  3476. // covers the visible area.
  3477. function setScrollTop(cm, val) {
  3478. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3479. cm.doc.scrollTop = val;
  3480. if (!gecko) updateDisplaySimple(cm, { top: val });
  3481. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3482. cm.display.scrollbars.setScrollTop(val);
  3483. if (gecko) updateDisplaySimple(cm);
  3484. startWorker(cm, 100);
  3485. }
  3486. // Sync scroller and scrollbar, ensure the gutter elements are
  3487. // aligned.
  3488. function setScrollLeft(cm, val, isScroller) {
  3489. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3490. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3491. cm.doc.scrollLeft = val;
  3492. alignHorizontally(cm);
  3493. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3494. cm.display.scrollbars.setScrollLeft(val);
  3495. }
  3496. // Since the delta values reported on mouse wheel events are
  3497. // unstandardized between browsers and even browser versions, and
  3498. // generally horribly unpredictable, this code starts by measuring
  3499. // the scroll effect that the first few mouse wheel events have,
  3500. // and, from that, detects the way it can convert deltas to pixel
  3501. // offsets afterwards.
  3502. //
  3503. // The reason we want to know the amount a wheel event will scroll
  3504. // is that it gives us a chance to update the display before the
  3505. // actual scrolling happens, reducing flickering.
  3506. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3507. // Fill in a browser-detected starting value on browsers where we
  3508. // know one. These don't have to be accurate -- the result of them
  3509. // being wrong would just be a slight flicker on the first wheel
  3510. // scroll (if it is large enough).
  3511. if (ie) wheelPixelsPerUnit = -.53;
  3512. else if (gecko) wheelPixelsPerUnit = 15;
  3513. else if (chrome) wheelPixelsPerUnit = -.7;
  3514. else if (safari) wheelPixelsPerUnit = -1 / 3;
  3515. var wheelEventDelta = function (e) {
  3516. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3517. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3518. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3519. else if (dy == null) dy = e.wheelDelta;
  3520. return { x: dx, y: dy };
  3521. };
  3522. CodeMirror.wheelEventPixels = function (e) {
  3523. var delta = wheelEventDelta(e);
  3524. delta.x *= wheelPixelsPerUnit;
  3525. delta.y *= wheelPixelsPerUnit;
  3526. return delta;
  3527. };
  3528. function onScrollWheel(cm, e) {
  3529. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3530. var display = cm.display, scroll = display.scroller;
  3531. // Quit if there's nothing to scroll here
  3532. if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
  3533. dy && scroll.scrollHeight > scroll.clientHeight)) return;
  3534. // Webkit browsers on OS X abort momentum scrolls when the target
  3535. // of the scroll event is removed from the scrollable element.
  3536. // This hack (see related code in patchDisplay) makes sure the
  3537. // element is kept around.
  3538. if (dy && mac && webkit) {
  3539. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3540. for (var i = 0; i < view.length; i++) {
  3541. if (view[i].node == cur) {
  3542. cm.display.currentWheelTarget = cur;
  3543. break outer;
  3544. }
  3545. }
  3546. }
  3547. }
  3548. // On some browsers, horizontal scrolling will cause redraws to
  3549. // happen before the gutter has been realigned, causing it to
  3550. // wriggle around in a most unseemly way. When we have an
  3551. // estimated pixels/delta value, we just handle horizontal
  3552. // scrolling entirely here. It'll be slightly off from native, but
  3553. // better than glitching out.
  3554. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3555. if (dy)
  3556. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3557. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3558. e_preventDefault(e);
  3559. display.wheelStartX = null; // Abort measurement, if in progress
  3560. return;
  3561. }
  3562. // 'Project' the visible viewport to cover the area that is being
  3563. // scrolled into view (if we know enough to estimate it).
  3564. if (dy && wheelPixelsPerUnit != null) {
  3565. var pixels = dy * wheelPixelsPerUnit;
  3566. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3567. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3568. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3569. updateDisplaySimple(cm, { top: top, bottom: bot });
  3570. }
  3571. if (wheelSamples < 20) {
  3572. if (display.wheelStartX == null) {
  3573. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3574. display.wheelDX = dx; display.wheelDY = dy;
  3575. setTimeout(function () {
  3576. if (display.wheelStartX == null) return;
  3577. var movedX = scroll.scrollLeft - display.wheelStartX;
  3578. var movedY = scroll.scrollTop - display.wheelStartY;
  3579. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3580. (movedX && display.wheelDX && movedX / display.wheelDX);
  3581. display.wheelStartX = display.wheelStartY = null;
  3582. if (!sample) return;
  3583. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3584. ++wheelSamples;
  3585. }, 200);
  3586. } else {
  3587. display.wheelDX += dx; display.wheelDY += dy;
  3588. }
  3589. }
  3590. }
  3591. // KEY EVENTS
  3592. // Run a handler that was bound to a key.
  3593. function doHandleBinding(cm, bound, dropShift) {
  3594. if (typeof bound == "string") {
  3595. bound = commands[bound];
  3596. if (!bound) return false;
  3597. }
  3598. // Ensure previous input has been read, so that the handler sees a
  3599. // consistent view of the document
  3600. cm.display.input.ensurePolled();
  3601. var prevShift = cm.display.shift, done = false;
  3602. try {
  3603. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  3604. if (dropShift) cm.display.shift = false;
  3605. done = bound(cm) != Pass;
  3606. } finally {
  3607. cm.display.shift = prevShift;
  3608. cm.state.suppressEdits = false;
  3609. }
  3610. return done;
  3611. }
  3612. function lookupKeyForEditor(cm, name, handle) {
  3613. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3614. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3615. if (result) return result;
  3616. }
  3617. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3618. || lookupKey(name, cm.options.keyMap, handle, cm);
  3619. }
  3620. var stopSeq = new Delayed;
  3621. function dispatchKey(cm, name, e, handle) {
  3622. var seq = cm.state.keySeq;
  3623. if (seq) {
  3624. if (isModifierKey(name)) return "handled";
  3625. stopSeq.set(50, function () {
  3626. if (cm.state.keySeq == seq) {
  3627. cm.state.keySeq = null;
  3628. cm.display.input.reset();
  3629. }
  3630. });
  3631. name = seq + " " + name;
  3632. }
  3633. var result = lookupKeyForEditor(cm, name, handle);
  3634. if (result == "multi")
  3635. cm.state.keySeq = name;
  3636. if (result == "handled")
  3637. signalLater(cm, "keyHandled", cm, name, e);
  3638. if (result == "handled" || result == "multi") {
  3639. e_preventDefault(e);
  3640. restartBlink(cm);
  3641. }
  3642. if (seq && !result && /\'$/.test(name)) {
  3643. e_preventDefault(e);
  3644. return true;
  3645. }
  3646. return !!result;
  3647. }
  3648. // Handle a key from the keydown event.
  3649. function handleKeyBinding(cm, e) {
  3650. var name = keyName(e, true);
  3651. if (!name) return false;
  3652. if (e.shiftKey && !cm.state.keySeq) {
  3653. // First try to resolve full name (including 'Shift-'). Failing
  3654. // that, see if there is a cursor-motion command (starting with
  3655. // 'go') bound to the keyname without 'Shift-'.
  3656. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  3657. || dispatchKey(cm, name, e, function (b) {
  3658. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3659. return doHandleBinding(cm, b);
  3660. });
  3661. } else {
  3662. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); });
  3663. }
  3664. }
  3665. // Handle a key from the keypress event
  3666. function handleCharBinding(cm, e, ch) {
  3667. return dispatchKey(cm, "'" + ch + "'", e,
  3668. function (b) { return doHandleBinding(cm, b, true); });
  3669. }
  3670. var lastStoppedKey = null;
  3671. function onKeyDown(e) {
  3672. var cm = this;
  3673. cm.curOp.focus = activeElt();
  3674. if (signalDOMEvent(cm, e)) return;
  3675. // IE does strange things with escape.
  3676. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3677. var code = e.keyCode;
  3678. cm.display.shift = code == 16 || e.shiftKey;
  3679. var handled = handleKeyBinding(cm, e);
  3680. if (presto) {
  3681. lastStoppedKey = handled ? code : null;
  3682. // Opera has no cut event... we try to at least catch the key combo
  3683. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3684. cm.replaceSelection("", null, "cut");
  3685. }
  3686. // Turn mouse into crosshair when Alt is held on Mac.
  3687. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3688. showCrossHair(cm);
  3689. }
  3690. function showCrossHair(cm) {
  3691. var lineDiv = cm.display.lineDiv;
  3692. addClass(lineDiv, "CodeMirror-crosshair");
  3693. function up(e) {
  3694. if (e.keyCode == 18 || !e.altKey) {
  3695. rmClass(lineDiv, "CodeMirror-crosshair");
  3696. off(document, "keyup", up);
  3697. off(document, "mouseover", up);
  3698. }
  3699. }
  3700. on(document, "keyup", up);
  3701. on(document, "mouseover", up);
  3702. }
  3703. function onKeyUp(e) {
  3704. if (e.keyCode == 16) this.doc.sel.shift = false;
  3705. signalDOMEvent(this, e);
  3706. }
  3707. function onKeyPress(e) {
  3708. var cm = this;
  3709. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3710. var keyCode = e.keyCode, charCode = e.charCode;
  3711. if (presto && keyCode == lastStoppedKey) { lastStoppedKey = null; e_preventDefault(e); return; }
  3712. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3713. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3714. if (handleCharBinding(cm, e, ch)) return;
  3715. cm.display.input.onKeyPress(e);
  3716. }
  3717. // FOCUS/BLUR EVENTS
  3718. function delayBlurEvent(cm) {
  3719. cm.state.delayingBlurEvent = true;
  3720. setTimeout(function () {
  3721. if (cm.state.delayingBlurEvent) {
  3722. cm.state.delayingBlurEvent = false;
  3723. onBlur(cm);
  3724. }
  3725. }, 100);
  3726. }
  3727. function onFocus(cm) {
  3728. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  3729. if (cm.options.readOnly == "nocursor") return;
  3730. if (!cm.state.focused) {
  3731. signal(cm, "focus", cm);
  3732. cm.state.focused = true;
  3733. addClass(cm.display.wrapper, "CodeMirror-focused");
  3734. // This test prevents this from firing when a context
  3735. // menu is closed (since the input reset would kill the
  3736. // select-all detection hack)
  3737. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3738. cm.display.input.reset();
  3739. if (webkit) setTimeout(function () { cm.display.input.reset(true); }, 20); // Issue #1730
  3740. }
  3741. cm.display.input.receivedFocus();
  3742. }
  3743. restartBlink(cm);
  3744. }
  3745. function onBlur(cm) {
  3746. if (cm.state.delayingBlurEvent) return;
  3747. if (cm.state.focused) {
  3748. signal(cm, "blur", cm);
  3749. cm.state.focused = false;
  3750. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3751. }
  3752. clearInterval(cm.display.blinker);
  3753. setTimeout(function () { if (!cm.state.focused) cm.display.shift = false; }, 150);
  3754. }
  3755. // CONTEXT MENU HANDLING
  3756. // To make the context menu work, we need to briefly unhide the
  3757. // textarea (making it as unobtrusive as possible) to let the
  3758. // right-click take effect on it.
  3759. function onContextMenu(cm, e) {
  3760. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3761. cm.display.input.onContextMenu(e);
  3762. }
  3763. function contextMenuInGutter(cm, e) {
  3764. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3765. return gutterEvent(cm, e, "gutterContextMenu", false, signal);
  3766. }
  3767. // UPDATING
  3768. // Compute the position of the end of a change (its 'to' property
  3769. // refers to the pre-change end).
  3770. var changeEnd = CodeMirror.changeEnd = function (change) {
  3771. if (!change.text) return change.to;
  3772. return Pos(change.from.line + change.text.length - 1,
  3773. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3774. };
  3775. // Adjust a position to refer to the post-change position of the
  3776. // same text, or the end of the change if the change covers it.
  3777. function adjustForChange(pos, change) {
  3778. if (cmp(pos, change.from) < 0) return pos;
  3779. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3780. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3781. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3782. return Pos(line, ch);
  3783. }
  3784. function computeSelAfterChange(doc, change) {
  3785. var out = [];
  3786. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3787. var range = doc.sel.ranges[i];
  3788. out.push(new Range(adjustForChange(range.anchor, change),
  3789. adjustForChange(range.head, change)));
  3790. }
  3791. return normalizeSelection(out, doc.sel.primIndex);
  3792. }
  3793. function offsetPos(pos, old, nw) {
  3794. if (pos.line == old.line)
  3795. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3796. else
  3797. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3798. }
  3799. // Used by replaceSelections to allow moving the selection to the
  3800. // start or around the replaced test. Hint may be "start" or "around".
  3801. function computeReplacedSel(doc, changes, hint) {
  3802. var out = [];
  3803. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3804. for (var i = 0; i < changes.length; i++) {
  3805. var change = changes[i];
  3806. var from = offsetPos(change.from, oldPrev, newPrev);
  3807. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3808. oldPrev = change.to;
  3809. newPrev = to;
  3810. if (hint == "around") {
  3811. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3812. out[i] = new Range(inv ? to : from, inv ? from : to);
  3813. } else {
  3814. out[i] = new Range(from, from);
  3815. }
  3816. }
  3817. return new Selection(out, doc.sel.primIndex);
  3818. }
  3819. // Allow "beforeChange" event handlers to influence a change
  3820. function filterChange(doc, change, update) {
  3821. var obj = {
  3822. canceled: false,
  3823. from: change.from,
  3824. to: change.to,
  3825. text: change.text,
  3826. origin: change.origin,
  3827. cancel: function () { this.canceled = true; }
  3828. };
  3829. if (update) obj.update = function (from, to, text, origin) {
  3830. if (from) this.from = clipPos(doc, from);
  3831. if (to) this.to = clipPos(doc, to);
  3832. if (text) this.text = text;
  3833. if (origin !== undefined) this.origin = origin;
  3834. };
  3835. signal(doc, "beforeChange", doc, obj);
  3836. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3837. if (obj.canceled) return null;
  3838. return { from: obj.from, to: obj.to, text: obj.text, origin: obj.origin };
  3839. }
  3840. // Apply a change to a document, and add it to the document's
  3841. // history, and propagating it to all linked documents.
  3842. function makeChange(doc, change, ignoreReadOnly) {
  3843. if (doc.cm) {
  3844. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3845. if (doc.cm.state.suppressEdits) return;
  3846. }
  3847. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3848. change = filterChange(doc, change, true);
  3849. if (!change) return;
  3850. }
  3851. // Possibly split or suppress the update based on the presence
  3852. // of read-only spans in its range.
  3853. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3854. if (split) {
  3855. for (var i = split.length - 1; i >= 0; --i)
  3856. makeChangeInner(doc, { from: split[i].from, to: split[i].to, text: i ? [""] : change.text });
  3857. } else {
  3858. makeChangeInner(doc, change);
  3859. }
  3860. }
  3861. function makeChangeInner(doc, change) {
  3862. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3863. var selAfter = computeSelAfterChange(doc, change);
  3864. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3865. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3866. var rebased = [];
  3867. linkedDocs(doc, function (doc, sharedHist) {
  3868. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3869. rebaseHist(doc.history, change);
  3870. rebased.push(doc.history);
  3871. }
  3872. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3873. });
  3874. }
  3875. // Revert a change stored in a document's history.
  3876. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3877. if (doc.cm && doc.cm.state.suppressEdits) return;
  3878. var hist = doc.history, event, selAfter = doc.sel;
  3879. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3880. // Verify that there is a useable event (so that ctrl-z won't
  3881. // needlessly clear selection events)
  3882. for (var i = 0; i < source.length; i++) {
  3883. event = source[i];
  3884. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3885. break;
  3886. }
  3887. if (i == source.length) return;
  3888. hist.lastOrigin = hist.lastSelOrigin = null;
  3889. for (; ;) {
  3890. event = source.pop();
  3891. if (event.ranges) {
  3892. pushSelectionToHistory(event, dest);
  3893. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3894. setSelection(doc, event, { clearRedo: false });
  3895. return;
  3896. }
  3897. selAfter = event;
  3898. }
  3899. else break;
  3900. }
  3901. // Build up a reverse change object to add to the opposite history
  3902. // stack (redo when undoing, and vice versa).
  3903. var antiChanges = [];
  3904. pushSelectionToHistory(selAfter, dest);
  3905. dest.push({ changes: antiChanges, generation: hist.generation });
  3906. hist.generation = event.generation || ++hist.maxGeneration;
  3907. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3908. for (var i = event.changes.length - 1; i >= 0; --i) {
  3909. var change = event.changes[i];
  3910. change.origin = type;
  3911. if (filter && !filterChange(doc, change, false)) {
  3912. source.length = 0;
  3913. return;
  3914. }
  3915. antiChanges.push(historyChangeFromChange(doc, change));
  3916. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3917. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3918. if (!i && doc.cm) doc.cm.scrollIntoView({ from: change.from, to: changeEnd(change) });
  3919. var rebased = [];
  3920. // Propagate to the linked documents
  3921. linkedDocs(doc, function (doc, sharedHist) {
  3922. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3923. rebaseHist(doc.history, change);
  3924. rebased.push(doc.history);
  3925. }
  3926. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  3927. });
  3928. }
  3929. }
  3930. // Sub-views need their line numbers shifted when text is added
  3931. // above or below them in the parent document.
  3932. function shiftDoc(doc, distance) {
  3933. if (distance == 0) return;
  3934. doc.first += distance;
  3935. doc.sel = new Selection(map(doc.sel.ranges, function (range) {
  3936. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  3937. Pos(range.head.line + distance, range.head.ch));
  3938. }), doc.sel.primIndex);
  3939. if (doc.cm) {
  3940. regChange(doc.cm, doc.first, doc.first - distance, distance);
  3941. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  3942. regLineChange(doc.cm, l, "gutter");
  3943. }
  3944. }
  3945. // More lower-level change function, handling only a single document
  3946. // (not linked ones).
  3947. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  3948. if (doc.cm && !doc.cm.curOp)
  3949. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  3950. if (change.to.line < doc.first) {
  3951. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  3952. return;
  3953. }
  3954. if (change.from.line > doc.lastLine()) return;
  3955. // Clip the change to the size of this doc
  3956. if (change.from.line < doc.first) {
  3957. var shift = change.text.length - 1 - (doc.first - change.from.line);
  3958. shiftDoc(doc, shift);
  3959. change = {
  3960. from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  3961. text: [lst(change.text)], origin: change.origin
  3962. };
  3963. }
  3964. var last = doc.lastLine();
  3965. if (change.to.line > last) {
  3966. change = {
  3967. from: change.from, to: Pos(last, getLine(doc, last).text.length),
  3968. text: [change.text[0]], origin: change.origin
  3969. };
  3970. }
  3971. change.removed = getBetween(doc, change.from, change.to);
  3972. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  3973. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  3974. else updateDoc(doc, change, spans);
  3975. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  3976. }
  3977. // Handle the interaction of a change to a document with the editor
  3978. // that this document is part of.
  3979. function makeChangeSingleDocInEditor(cm, change, spans) {
  3980. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  3981. var recomputeMaxLength = false, checkWidthStart = from.line;
  3982. if (!cm.options.lineWrapping) {
  3983. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  3984. doc.iter(checkWidthStart, to.line + 1, function (line) {
  3985. if (line == display.maxLine) {
  3986. recomputeMaxLength = true;
  3987. return true;
  3988. }
  3989. });
  3990. }
  3991. if (doc.sel.contains(change.from, change.to) > -1)
  3992. signalCursorActivity(cm);
  3993. updateDoc(doc, change, spans, estimateHeight(cm));
  3994. if (!cm.options.lineWrapping) {
  3995. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  3996. var len = lineLength(line);
  3997. if (len > display.maxLineLength) {
  3998. display.maxLine = line;
  3999. display.maxLineLength = len;
  4000. display.maxLineChanged = true;
  4001. recomputeMaxLength = false;
  4002. }
  4003. });
  4004. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  4005. }
  4006. // Adjust frontier, schedule worker
  4007. doc.frontier = Math.min(doc.frontier, from.line);
  4008. startWorker(cm, 400);
  4009. var lendiff = change.text.length - (to.line - from.line) - 1;
  4010. // Remember that these lines changed, for updating the display
  4011. if (change.full)
  4012. regChange(cm);
  4013. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4014. regLineChange(cm, from.line, "text");
  4015. else
  4016. regChange(cm, from.line, to.line + 1, lendiff);
  4017. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4018. if (changeHandler || changesHandler) {
  4019. var obj = {
  4020. from: from, to: to,
  4021. text: change.text,
  4022. removed: change.removed,
  4023. origin: change.origin
  4024. };
  4025. if (changeHandler) signalLater(cm, "change", cm, obj);
  4026. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  4027. }
  4028. cm.display.selForContextMenu = null;
  4029. }
  4030. function replaceRange(doc, code, from, to, origin) {
  4031. if (!to) to = from;
  4032. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  4033. if (typeof code == "string") code = splitLines(code);
  4034. makeChange(doc, { from: from, to: to, text: code, origin: origin });
  4035. }
  4036. // SCROLLING THINGS INTO VIEW
  4037. // If an editor sits on the top or bottom of the window, partially
  4038. // scrolled out of view, this ensures that the cursor is visible.
  4039. function maybeScrollWindow(cm, coords) {
  4040. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  4041. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4042. if (coords.top + box.top < 0) doScroll = true;
  4043. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  4044. if (doScroll != null && !phantom) {
  4045. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  4046. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  4047. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  4048. coords.left + "px; width: 2px;");
  4049. cm.display.lineSpace.appendChild(scrollNode);
  4050. scrollNode.scrollIntoView(doScroll);
  4051. cm.display.lineSpace.removeChild(scrollNode);
  4052. }
  4053. }
  4054. // Scroll a given position into view (immediately), verifying that
  4055. // it actually became visible (as line heights are accurately
  4056. // measured, the position of something may 'drift' during drawing).
  4057. function scrollPosIntoView(cm, pos, end, margin) {
  4058. if (margin == null) margin = 0;
  4059. for (var limit = 0; limit < 5; limit++) {
  4060. var changed = false, coords = cursorCoords(cm, pos);
  4061. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4062. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  4063. Math.min(coords.top, endCoords.top) - margin,
  4064. Math.max(coords.left, endCoords.left),
  4065. Math.max(coords.bottom, endCoords.bottom) + margin);
  4066. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4067. if (scrollPos.scrollTop != null) {
  4068. setScrollTop(cm, scrollPos.scrollTop);
  4069. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  4070. }
  4071. if (scrollPos.scrollLeft != null) {
  4072. setScrollLeft(cm, scrollPos.scrollLeft);
  4073. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  4074. }
  4075. if (!changed) break;
  4076. }
  4077. return coords;
  4078. }
  4079. // Scroll a given set of coordinates into view (immediately).
  4080. function scrollIntoView(cm, x1, y1, x2, y2) {
  4081. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  4082. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  4083. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  4084. }
  4085. // Calculate a new scroll position needed to scroll the given
  4086. // rectangle into view. Returns an object with scrollTop and
  4087. // scrollLeft properties. When these are undefined, the
  4088. // vertical/horizontal position does not need to be adjusted.
  4089. function calculateScrollPos(cm, x1, y1, x2, y2) {
  4090. var display = cm.display, snapMargin = textHeight(cm.display);
  4091. if (y1 < 0) y1 = 0;
  4092. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4093. var screen = displayHeight(cm), result = {};
  4094. if (y2 - y1 > screen) y2 = y1 + screen;
  4095. var docBottom = cm.doc.height + paddingVert(display);
  4096. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4097. if (y1 < screentop) {
  4098. result.scrollTop = atTop ? 0 : y1;
  4099. } else if (y2 > screentop + screen) {
  4100. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4101. if (newTop != screentop) result.scrollTop = newTop;
  4102. }
  4103. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4104. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4105. var tooWide = x2 - x1 > screenw;
  4106. if (tooWide) x2 = x1 + screenw;
  4107. if (x1 < 10)
  4108. result.scrollLeft = 0;
  4109. else if (x1 < screenleft)
  4110. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4111. else if (x2 > screenw + screenleft - 3)
  4112. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4113. return result;
  4114. }
  4115. // Store a relative adjustment to the scroll position in the current
  4116. // operation (to be applied when the operation finishes).
  4117. function addToScrollPos(cm, left, top) {
  4118. if (left != null || top != null) resolveScrollToPos(cm);
  4119. if (left != null)
  4120. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4121. if (top != null)
  4122. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4123. }
  4124. // Make sure that at the end of the operation the current cursor is
  4125. // shown.
  4126. function ensureCursorVisible(cm) {
  4127. resolveScrollToPos(cm);
  4128. var cur = cm.getCursor(), from = cur, to = cur;
  4129. if (!cm.options.lineWrapping) {
  4130. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4131. to = Pos(cur.line, cur.ch + 1);
  4132. }
  4133. cm.curOp.scrollToPos = { from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true };
  4134. }
  4135. // When an operation has its scrollToPos property set, and another
  4136. // scroll action is applied before the end of the operation, this
  4137. // 'simulates' scrolling that position into view in a cheap way, so
  4138. // that the effect of intermediate scroll commands is not ignored.
  4139. function resolveScrollToPos(cm) {
  4140. var range = cm.curOp.scrollToPos;
  4141. if (range) {
  4142. cm.curOp.scrollToPos = null;
  4143. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4144. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4145. Math.min(from.top, to.top) - range.margin,
  4146. Math.max(from.right, to.right),
  4147. Math.max(from.bottom, to.bottom) + range.margin);
  4148. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4149. }
  4150. }
  4151. // API UTILITIES
  4152. // Indent the given line. The how parameter can be "smart",
  4153. // "add"/null, "subtract", or "prev". When aggressive is false
  4154. // (typically set to true for forced single-line indents), empty
  4155. // lines are not indented, and places where the mode returns Pass
  4156. // are left alone.
  4157. function indentLine(cm, n, how, aggressive) {
  4158. var doc = cm.doc, state;
  4159. if (how == null) how = "add";
  4160. if (how == "smart") {
  4161. // Fall back to "prev" when the mode doesn't have an indentation
  4162. // method.
  4163. if (!doc.mode.indent) how = "prev";
  4164. else state = getStateBefore(cm, n);
  4165. }
  4166. var tabSize = cm.options.tabSize;
  4167. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4168. if (line.stateAfter) line.stateAfter = null;
  4169. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4170. if (!aggressive && !/\S/.test(line.text)) {
  4171. indentation = 0;
  4172. how = "not";
  4173. } else if (how == "smart") {
  4174. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4175. if (indentation == Pass || indentation > 150) {
  4176. if (!aggressive) return;
  4177. how = "prev";
  4178. }
  4179. }
  4180. if (how == "prev") {
  4181. if (n > doc.first) indentation = countColumn(getLine(doc, n - 1).text, null, tabSize);
  4182. else indentation = 0;
  4183. } else if (how == "add") {
  4184. indentation = curSpace + cm.options.indentUnit;
  4185. } else if (how == "subtract") {
  4186. indentation = curSpace - cm.options.indentUnit;
  4187. } else if (typeof how == "number") {
  4188. indentation = curSpace + how;
  4189. }
  4190. indentation = Math.max(0, indentation);
  4191. var indentString = "", pos = 0;
  4192. if (cm.options.indentWithTabs)
  4193. for (var i = Math.floor(indentation / tabSize); i; --i) { pos += tabSize; indentString += "\t"; }
  4194. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4195. if (indentString != curSpaceString) {
  4196. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4197. line.stateAfter = null;
  4198. return true;
  4199. } else {
  4200. // Ensure that, if the cursor was in the whitespace at the start
  4201. // of the line, it is moved to the end of that space.
  4202. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4203. var range = doc.sel.ranges[i];
  4204. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4205. var pos = Pos(n, curSpaceString.length);
  4206. replaceOneSelection(doc, i, new Range(pos, pos));
  4207. break;
  4208. }
  4209. }
  4210. }
  4211. }
  4212. // Utility for applying a change to a line by handle or number,
  4213. // returning the number and optionally registering the line as
  4214. // changed.
  4215. function changeLine(doc, handle, changeType, op) {
  4216. var no = handle, line = handle;
  4217. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4218. else no = lineNo(handle);
  4219. if (no == null) return null;
  4220. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4221. return line;
  4222. }
  4223. // Helper for deleting text near the selection(s), used to implement
  4224. // backspace, delete, and similar functionality.
  4225. function deleteNearSelection(cm, compute) {
  4226. var ranges = cm.doc.sel.ranges, kill = [];
  4227. // Build up a set of ranges to kill first, merging overlapping
  4228. // ranges.
  4229. for (var i = 0; i < ranges.length; i++) {
  4230. var toKill = compute(ranges[i]);
  4231. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4232. var replaced = kill.pop();
  4233. if (cmp(replaced.from, toKill.from) < 0) {
  4234. toKill.from = replaced.from;
  4235. break;
  4236. }
  4237. }
  4238. kill.push(toKill);
  4239. }
  4240. // Next, remove those actual ranges.
  4241. runInOp(cm, function () {
  4242. for (var i = kill.length - 1; i >= 0; i--)
  4243. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4244. ensureCursorVisible(cm);
  4245. });
  4246. }
  4247. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4248. // right), unit can be "char", "column" (like char, but doesn't
  4249. // cross line boundaries), "word" (across next word), or "group" (to
  4250. // the start of next group of word or non-word-non-whitespace
  4251. // chars). The visually param controls whether, in right-to-left
  4252. // text, direction 1 means to move towards the next index in the
  4253. // string, or towards the character to the right of the current
  4254. // position. The resulting position will have a hitSide=true
  4255. // property if it reached the end of the document.
  4256. function findPosH(doc, pos, dir, unit, visually) {
  4257. var line = pos.line, ch = pos.ch, origDir = dir;
  4258. var lineObj = getLine(doc, line);
  4259. var possible = true;
  4260. function findNextLine() {
  4261. var l = line + dir;
  4262. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  4263. line = l;
  4264. return lineObj = getLine(doc, l);
  4265. }
  4266. function moveOnce(boundToLine) {
  4267. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4268. if (next == null) {
  4269. if (!boundToLine && findNextLine()) {
  4270. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4271. else ch = dir < 0 ? lineObj.text.length : 0;
  4272. } else return (possible = false);
  4273. } else ch = next;
  4274. return true;
  4275. }
  4276. if (unit == "char") moveOnce();
  4277. else if (unit == "column") moveOnce(true);
  4278. else if (unit == "word" || unit == "group") {
  4279. var sawType = null, group = unit == "group";
  4280. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4281. for (var first = true; ; first = false) {
  4282. if (dir < 0 && !moveOnce(!first)) break;
  4283. var cur = lineObj.text.charAt(ch) || "\n";
  4284. var type = isWordChar(cur, helper) ? "w"
  4285. : group && cur == "\n" ? "n"
  4286. : !group || /\s/.test(cur) ? null
  4287. : "p";
  4288. if (group && !first && !type) type = "s";
  4289. if (sawType && sawType != type) {
  4290. if (dir < 0) { dir = 1; moveOnce(); }
  4291. break;
  4292. }
  4293. if (type) sawType = type;
  4294. if (dir > 0 && !moveOnce(!first)) break;
  4295. }
  4296. }
  4297. var result = skipAtomic(doc, Pos(line, ch), origDir, true);
  4298. if (!possible) result.hitSide = true;
  4299. return result;
  4300. }
  4301. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4302. // "page" or "line". The resulting position will have a hitSide=true
  4303. // property if it reached the end of the document.
  4304. function findPosV(cm, pos, dir, unit) {
  4305. var doc = cm.doc, x = pos.left, y;
  4306. if (unit == "page") {
  4307. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4308. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4309. } else if (unit == "line") {
  4310. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4311. }
  4312. for (; ;) {
  4313. var target = coordsChar(cm, x, y);
  4314. if (!target.outside) break;
  4315. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4316. y += dir * 5;
  4317. }
  4318. return target;
  4319. }
  4320. // EDITOR METHODS
  4321. // The publicly visible API. Note that methodOp(f) means
  4322. // 'wrap f in an operation, performed on its `this` parameter'.
  4323. // This is not the complete set of editor methods. Most of the
  4324. // methods defined on the Doc type are also injected into
  4325. // CodeMirror.prototype, for backwards compatibility and
  4326. // convenience.
  4327. CodeMirror.prototype = {
  4328. constructor: CodeMirror,
  4329. focus: function () { window.focus(); this.display.input.focus(); },
  4330. setOption: function (option, value) {
  4331. var options = this.options, old = options[option];
  4332. if (options[option] == value && option != "mode") return;
  4333. options[option] = value;
  4334. if (optionHandlers.hasOwnProperty(option))
  4335. operation(this, optionHandlers[option])(this, value, old);
  4336. },
  4337. getOption: function (option) { return this.options[option]; },
  4338. getDoc: function () { return this.doc; },
  4339. addKeyMap: function (map, bottom) {
  4340. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4341. },
  4342. removeKeyMap: function (map) {
  4343. var maps = this.state.keyMaps;
  4344. for (var i = 0; i < maps.length; ++i)
  4345. if (maps[i] == map || maps[i].name == map) {
  4346. maps.splice(i, 1);
  4347. return true;
  4348. }
  4349. },
  4350. addOverlay: methodOp(function (spec, options) {
  4351. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4352. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4353. this.state.overlays.push({ mode: mode, modeSpec: spec, opaque: options && options.opaque });
  4354. this.state.modeGen++;
  4355. regChange(this);
  4356. }),
  4357. removeOverlay: methodOp(function (spec) {
  4358. var overlays = this.state.overlays;
  4359. for (var i = 0; i < overlays.length; ++i) {
  4360. var cur = overlays[i].modeSpec;
  4361. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4362. overlays.splice(i, 1);
  4363. this.state.modeGen++;
  4364. regChange(this);
  4365. return;
  4366. }
  4367. }
  4368. }),
  4369. indentLine: methodOp(function (n, dir, aggressive) {
  4370. if (typeof dir != "string" && typeof dir != "number") {
  4371. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4372. else dir = dir ? "add" : "subtract";
  4373. }
  4374. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4375. }),
  4376. indentSelection: methodOp(function (how) {
  4377. var ranges = this.doc.sel.ranges, end = -1;
  4378. for (var i = 0; i < ranges.length; i++) {
  4379. var range = ranges[i];
  4380. if (!range.empty()) {
  4381. var from = range.from(), to = range.to();
  4382. var start = Math.max(end, from.line);
  4383. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4384. for (var j = start; j < end; ++j)
  4385. indentLine(this, j, how);
  4386. var newRanges = this.doc.sel.ranges;
  4387. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4388. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4389. } else if (range.head.line > end) {
  4390. indentLine(this, range.head.line, how, true);
  4391. end = range.head.line;
  4392. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4393. }
  4394. }
  4395. }),
  4396. // Fetch the parser token for a given character. Useful for hacks
  4397. // that want to inspect the mode state (say, for completion).
  4398. getTokenAt: function (pos, precise) {
  4399. return takeToken(this, pos, precise);
  4400. },
  4401. getLineTokens: function (line, precise) {
  4402. return takeToken(this, Pos(line), precise, true);
  4403. },
  4404. getTokenTypeAt: function (pos) {
  4405. pos = clipPos(this.doc, pos);
  4406. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4407. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4408. var type;
  4409. if (ch == 0) type = styles[2];
  4410. else for (; ;) {
  4411. var mid = (before + after) >> 1;
  4412. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4413. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4414. else { type = styles[mid * 2 + 2]; break; }
  4415. }
  4416. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4417. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4418. },
  4419. getModeAt: function (pos) {
  4420. var mode = this.doc.mode;
  4421. if (!mode.innerMode) return mode;
  4422. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4423. },
  4424. getHelper: function (pos, type) {
  4425. return this.getHelpers(pos, type)[0];
  4426. },
  4427. getHelpers: function (pos, type) {
  4428. var found = [];
  4429. if (!helpers.hasOwnProperty(type)) return found;
  4430. var help = helpers[type], mode = this.getModeAt(pos);
  4431. if (typeof mode[type] == "string") {
  4432. if (help[mode[type]]) found.push(help[mode[type]]);
  4433. } else if (mode[type]) {
  4434. for (var i = 0; i < mode[type].length; i++) {
  4435. var val = help[mode[type][i]];
  4436. if (val) found.push(val);
  4437. }
  4438. } else if (mode.helperType && help[mode.helperType]) {
  4439. found.push(help[mode.helperType]);
  4440. } else if (help[mode.name]) {
  4441. found.push(help[mode.name]);
  4442. }
  4443. for (var i = 0; i < help._global.length; i++) {
  4444. var cur = help._global[i];
  4445. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4446. found.push(cur.val);
  4447. }
  4448. return found;
  4449. },
  4450. getStateAfter: function (line, precise) {
  4451. var doc = this.doc;
  4452. line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line);
  4453. return getStateBefore(this, line + 1, precise);
  4454. },
  4455. cursorCoords: function (start, mode) {
  4456. var pos, range = this.doc.sel.primary();
  4457. if (start == null) pos = range.head;
  4458. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4459. else pos = start ? range.from() : range.to();
  4460. return cursorCoords(this, pos, mode || "page");
  4461. },
  4462. charCoords: function (pos, mode) {
  4463. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4464. },
  4465. coordsChar: function (coords, mode) {
  4466. coords = fromCoordSystem(this, coords, mode || "page");
  4467. return coordsChar(this, coords.left, coords.top);
  4468. },
  4469. lineAtHeight: function (height, mode) {
  4470. height = fromCoordSystem(this, { top: height, left: 0 }, mode || "page").top;
  4471. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4472. },
  4473. heightAtLine: function (line, mode) {
  4474. var end = false, lineObj;
  4475. if (typeof line == "number") {
  4476. var last = this.doc.first + this.doc.size - 1;
  4477. if (line < this.doc.first) line = this.doc.first;
  4478. else if (line > last) { line = last; end = true; }
  4479. lineObj = getLine(this.doc, line);
  4480. } else {
  4481. lineObj = line;
  4482. }
  4483. return intoCoordSystem(this, lineObj, { top: 0, left: 0 }, mode || "page").top +
  4484. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4485. },
  4486. defaultTextHeight: function () { return textHeight(this.display); },
  4487. defaultCharWidth: function () { return charWidth(this.display); },
  4488. setGutterMarker: methodOp(function (line, gutterID, value) {
  4489. return changeLine(this.doc, line, "gutter", function (line) {
  4490. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4491. markers[gutterID] = value;
  4492. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4493. return true;
  4494. });
  4495. }),
  4496. clearGutter: methodOp(function (gutterID) {
  4497. var cm = this, doc = cm.doc, i = doc.first;
  4498. doc.iter(function (line) {
  4499. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4500. line.gutterMarkers[gutterID] = null;
  4501. regLineChange(cm, i, "gutter");
  4502. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4503. }
  4504. ++i;
  4505. });
  4506. }),
  4507. lineInfo: function (line) {
  4508. if (typeof line == "number") {
  4509. if (!isLine(this.doc, line)) return null;
  4510. var n = line;
  4511. line = getLine(this.doc, line);
  4512. if (!line) return null;
  4513. } else {
  4514. var n = lineNo(line);
  4515. if (n == null) return null;
  4516. }
  4517. return {
  4518. line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4519. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4520. widgets: line.widgets
  4521. };
  4522. },
  4523. getViewport: function () { return { from: this.display.viewFrom, to: this.display.viewTo }; },
  4524. addWidget: function (pos, node, scroll, vert, horiz) {
  4525. var display = this.display;
  4526. pos = cursorCoords(this, clipPos(this.doc, pos));
  4527. var top = pos.bottom, left = pos.left;
  4528. node.style.position = "absolute";
  4529. node.setAttribute("cm-ignore-events", "true");
  4530. this.display.input.setUneditable(node);
  4531. display.sizer.appendChild(node);
  4532. if (vert == "over") {
  4533. top = pos.top;
  4534. } else if (vert == "above" || vert == "near") {
  4535. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4536. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4537. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4538. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4539. top = pos.top - node.offsetHeight;
  4540. else if (pos.bottom + node.offsetHeight <= vspace)
  4541. top = pos.bottom;
  4542. if (left + node.offsetWidth > hspace)
  4543. left = hspace - node.offsetWidth;
  4544. }
  4545. node.style.top = top + "px";
  4546. node.style.left = node.style.right = "";
  4547. if (horiz == "right") {
  4548. left = display.sizer.clientWidth - node.offsetWidth;
  4549. node.style.right = "0px";
  4550. } else {
  4551. if (horiz == "left") left = 0;
  4552. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4553. node.style.left = left + "px";
  4554. }
  4555. if (scroll)
  4556. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4557. },
  4558. triggerOnKeyDown: methodOp(onKeyDown),
  4559. triggerOnKeyPress: methodOp(onKeyPress),
  4560. triggerOnKeyUp: onKeyUp,
  4561. execCommand: function (cmd) {
  4562. if (commands.hasOwnProperty(cmd))
  4563. return commands[cmd](this);
  4564. },
  4565. triggerElectric: methodOp(function (text) { triggerElectric(this, text); }),
  4566. findPosH: function (from, amount, unit, visually) {
  4567. var dir = 1;
  4568. if (amount < 0) { dir = -1; amount = -amount; }
  4569. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4570. cur = findPosH(this.doc, cur, dir, unit, visually);
  4571. if (cur.hitSide) break;
  4572. }
  4573. return cur;
  4574. },
  4575. moveH: methodOp(function (dir, unit) {
  4576. var cm = this;
  4577. cm.extendSelectionsBy(function (range) {
  4578. if (cm.display.shift || cm.doc.extend || range.empty())
  4579. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4580. else
  4581. return dir < 0 ? range.from() : range.to();
  4582. }, sel_move);
  4583. }),
  4584. deleteH: methodOp(function (dir, unit) {
  4585. var sel = this.doc.sel, doc = this.doc;
  4586. if (sel.somethingSelected())
  4587. doc.replaceSelection("", null, "+delete");
  4588. else
  4589. deleteNearSelection(this, function (range) {
  4590. var other = findPosH(doc, range.head, dir, unit, false);
  4591. return dir < 0 ? { from: other, to: range.head } : { from: range.head, to: other };
  4592. });
  4593. }),
  4594. findPosV: function (from, amount, unit, goalColumn) {
  4595. var dir = 1, x = goalColumn;
  4596. if (amount < 0) { dir = -1; amount = -amount; }
  4597. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4598. var coords = cursorCoords(this, cur, "div");
  4599. if (x == null) x = coords.left;
  4600. else coords.left = x;
  4601. cur = findPosV(this, coords, dir, unit);
  4602. if (cur.hitSide) break;
  4603. }
  4604. return cur;
  4605. },
  4606. moveV: methodOp(function (dir, unit) {
  4607. var cm = this, doc = this.doc, goals = [];
  4608. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4609. doc.extendSelectionsBy(function (range) {
  4610. if (collapse)
  4611. return dir < 0 ? range.from() : range.to();
  4612. var headPos = cursorCoords(cm, range.head, "div");
  4613. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4614. goals.push(headPos.left);
  4615. var pos = findPosV(cm, headPos, dir, unit);
  4616. if (unit == "page" && range == doc.sel.primary())
  4617. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4618. return pos;
  4619. }, sel_move);
  4620. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4621. doc.sel.ranges[i].goalColumn = goals[i];
  4622. }),
  4623. // Find the word at the given position (as returned by coordsChar).
  4624. findWordAt: function (pos) {
  4625. var doc = this.doc, line = getLine(doc, pos.line).text;
  4626. var start = pos.ch, end = pos.ch;
  4627. if (line) {
  4628. var helper = this.getHelper(pos, "wordChars");
  4629. if ((pos.xRel < 0 || end == line.length) && start)--start; else ++end;
  4630. var startChar = line.charAt(start);
  4631. var check = isWordChar(startChar, helper)
  4632. ? function (ch) { return isWordChar(ch, helper); }
  4633. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  4634. : function (ch) { return !/\s/.test(ch) && !isWordChar(ch); };
  4635. while (start > 0 && check(line.charAt(start - 1)))--start;
  4636. while (end < line.length && check(line.charAt(end)))++end;
  4637. }
  4638. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4639. },
  4640. toggleOverwrite: function (value) {
  4641. if (value != null && value == this.state.overwrite) return;
  4642. if (this.state.overwrite = !this.state.overwrite)
  4643. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4644. else
  4645. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4646. signal(this, "overwriteToggle", this, this.state.overwrite);
  4647. },
  4648. hasFocus: function () { return this.display.input.getField() == activeElt(); },
  4649. scrollTo: methodOp(function (x, y) {
  4650. if (x != null || y != null) resolveScrollToPos(this);
  4651. if (x != null) this.curOp.scrollLeft = x;
  4652. if (y != null) this.curOp.scrollTop = y;
  4653. }),
  4654. getScrollInfo: function () {
  4655. var scroller = this.display.scroller;
  4656. return {
  4657. left: scroller.scrollLeft, top: scroller.scrollTop,
  4658. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4659. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4660. clientHeight: displayHeight(this), clientWidth: displayWidth(this)
  4661. };
  4662. },
  4663. scrollIntoView: methodOp(function (range, margin) {
  4664. if (range == null) {
  4665. range = { from: this.doc.sel.primary().head, to: null };
  4666. if (margin == null) margin = this.options.cursorScrollMargin;
  4667. } else if (typeof range == "number") {
  4668. range = { from: Pos(range, 0), to: null };
  4669. } else if (range.from == null) {
  4670. range = { from: range, to: null };
  4671. }
  4672. if (!range.to) range.to = range.from;
  4673. range.margin = margin || 0;
  4674. if (range.from.line != null) {
  4675. resolveScrollToPos(this);
  4676. this.curOp.scrollToPos = range;
  4677. } else {
  4678. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4679. Math.min(range.from.top, range.to.top) - range.margin,
  4680. Math.max(range.from.right, range.to.right),
  4681. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4682. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4683. }
  4684. }),
  4685. setSize: methodOp(function (width, height) {
  4686. var cm = this;
  4687. function interpret(val) {
  4688. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4689. }
  4690. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4691. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4692. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4693. var lineNo = cm.display.viewFrom;
  4694. cm.doc.iter(lineNo, cm.display.viewTo, function (line) {
  4695. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4696. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4697. ++lineNo;
  4698. });
  4699. cm.curOp.forceUpdate = true;
  4700. signal(cm, "refresh", this);
  4701. }),
  4702. operation: function (f) { return runInOp(this, f); },
  4703. refresh: methodOp(function () {
  4704. var oldHeight = this.display.cachedTextHeight;
  4705. regChange(this);
  4706. this.curOp.forceUpdate = true;
  4707. clearCaches(this);
  4708. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4709. updateGutterSpace(this);
  4710. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4711. estimateLineHeights(this);
  4712. signal(this, "refresh", this);
  4713. }),
  4714. swapDoc: methodOp(function (doc) {
  4715. var old = this.doc;
  4716. old.cm = null;
  4717. attachDoc(this, doc);
  4718. clearCaches(this);
  4719. this.display.input.reset();
  4720. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4721. this.curOp.forceScroll = true;
  4722. signalLater(this, "swapDoc", this, old);
  4723. return old;
  4724. }),
  4725. getInputField: function () { return this.display.input.getField(); },
  4726. getWrapperElement: function () { return this.display.wrapper; },
  4727. getScrollerElement: function () { return this.display.scroller; },
  4728. getGutterElement: function () { return this.display.gutters; }
  4729. };
  4730. eventMixin(CodeMirror);
  4731. // OPTION DEFAULTS
  4732. // The default configuration options.
  4733. var defaults = CodeMirror.defaults = {};
  4734. // Functions to run when options are changed.
  4735. var optionHandlers = CodeMirror.optionHandlers = {};
  4736. function option(name, deflt, handle, notOnInit) {
  4737. CodeMirror.defaults[name] = deflt;
  4738. if (handle) optionHandlers[name] =
  4739. notOnInit ? function (cm, val, old) { if (old != Init) handle(cm, val, old); } : handle;
  4740. }
  4741. // Passed to option handlers when there is no old value.
  4742. var Init = CodeMirror.Init = { toString: function () { return "CodeMirror.Init"; } };
  4743. // These two are, on init, called from the constructor because they
  4744. // have to be initialized before the editor can start at all.
  4745. option("value", "", function (cm, val) {
  4746. cm.setValue(val);
  4747. }, true);
  4748. option("mode", null, function (cm, val) {
  4749. cm.doc.modeOption = val;
  4750. loadMode(cm);
  4751. }, true);
  4752. option("indentUnit", 2, loadMode, true);
  4753. option("indentWithTabs", false);
  4754. option("smartIndent", true);
  4755. option("tabSize", 4, function (cm) {
  4756. resetModeState(cm);
  4757. clearCaches(cm);
  4758. regChange(cm);
  4759. }, true);
  4760. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  4761. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4762. if (old != CodeMirror.Init) cm.refresh();
  4763. });
  4764. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { cm.refresh(); }, true);
  4765. option("electricChars", true);
  4766. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  4767. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4768. }, true);
  4769. option("rtlMoveVisually", !windows);
  4770. option("wholeLineUpdateBefore", true);
  4771. option("theme", "default", function (cm) {
  4772. themeChanged(cm);
  4773. guttersChanged(cm);
  4774. }, true);
  4775. option("keyMap", "default", function (cm, val, old) {
  4776. var next = getKeyMap(val);
  4777. var prev = old != CodeMirror.Init && getKeyMap(old);
  4778. if (prev && prev.detach) prev.detach(cm, next);
  4779. if (next.attach) next.attach(cm, prev || null);
  4780. });
  4781. option("extraKeys", null);
  4782. option("lineWrapping", false, wrappingChanged, true);
  4783. option("gutters", [], function (cm) {
  4784. setGuttersForLineNumbers(cm.options);
  4785. guttersChanged(cm);
  4786. }, true);
  4787. option("fixedGutter", true, function (cm, val) {
  4788. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4789. cm.refresh();
  4790. }, true);
  4791. option("coverGutterNextToScrollbar", false, function (cm) { updateScrollbars(cm); }, true);
  4792. option("scrollbarStyle", "native", function (cm) {
  4793. initScrollbars(cm);
  4794. updateScrollbars(cm);
  4795. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4796. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4797. }, true);
  4798. option("lineNumbers", false, function (cm) {
  4799. setGuttersForLineNumbers(cm.options);
  4800. guttersChanged(cm);
  4801. }, true);
  4802. option("firstLineNumber", 1, guttersChanged, true);
  4803. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
  4804. option("showCursorWhenSelecting", false, updateSelection, true);
  4805. option("resetSelectionOnContextMenu", true);
  4806. option("lineWiseCopyCut", true);
  4807. option("readOnly", false, function (cm, val) {
  4808. if (val == "nocursor") {
  4809. onBlur(cm);
  4810. cm.display.input.blur();
  4811. cm.display.disabled = true;
  4812. } else {
  4813. cm.display.disabled = false;
  4814. if (!val) cm.display.input.reset();
  4815. }
  4816. });
  4817. option("disableInput", false, function (cm, val) { if (!val) cm.display.input.reset(); }, true);
  4818. option("dragDrop", true, dragDropChanged);
  4819. option("cursorBlinkRate", 530);
  4820. option("cursorScrollMargin", 0);
  4821. option("cursorHeight", 1, updateSelection, true);
  4822. option("singleCursorHeightPerLine", true, updateSelection, true);
  4823. option("workTime", 100);
  4824. option("workDelay", 100);
  4825. option("flattenSpans", true, resetModeState, true);
  4826. option("addModeClass", false, resetModeState, true);
  4827. option("pollInterval", 100);
  4828. option("undoDepth", 200, function (cm, val) { cm.doc.history.undoDepth = val; });
  4829. option("historyEventDelay", 1250);
  4830. option("viewportMargin", 10, function (cm) { cm.refresh(); }, true);
  4831. option("maxHighlightLength", 10000, resetModeState, true);
  4832. option("moveInputWithCursor", true, function (cm, val) {
  4833. if (!val) cm.display.input.resetPosition();
  4834. });
  4835. option("tabindex", null, function (cm, val) {
  4836. cm.display.input.getField().tabIndex = val || "";
  4837. });
  4838. option("autofocus", null);
  4839. // MODE DEFINITION AND QUERYING
  4840. // Known modes, by name and by MIME
  4841. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4842. // Extra arguments are stored as the mode's dependencies, which is
  4843. // used by (legacy) mechanisms like loadmode.js to automatically
  4844. // load a mode. (Preferred mechanism is the require/define calls.)
  4845. CodeMirror.defineMode = function (name, mode) {
  4846. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4847. if (arguments.length > 2)
  4848. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4849. modes[name] = mode;
  4850. };
  4851. CodeMirror.defineMIME = function (mime, spec) {
  4852. mimeModes[mime] = spec;
  4853. };
  4854. // Given a MIME type, a {name, ...options} config object, or a name
  4855. // string, return a mode config object.
  4856. CodeMirror.resolveMode = function (spec) {
  4857. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4858. spec = mimeModes[spec];
  4859. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4860. var found = mimeModes[spec.name];
  4861. if (typeof found == "string") found = { name: found };
  4862. spec = createObj(found, spec);
  4863. spec.name = found.name;
  4864. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4865. return CodeMirror.resolveMode("application/xml");
  4866. }
  4867. if (typeof spec == "string") return { name: spec };
  4868. else return spec || { name: "null" };
  4869. };
  4870. // Given a mode spec (anything that resolveMode accepts), find and
  4871. // initialize an actual mode object.
  4872. CodeMirror.getMode = function (options, spec) {
  4873. var spec = CodeMirror.resolveMode(spec);
  4874. var mfactory = modes[spec.name];
  4875. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4876. var modeObj = mfactory(options, spec);
  4877. if (modeExtensions.hasOwnProperty(spec.name)) {
  4878. var exts = modeExtensions[spec.name];
  4879. for (var prop in exts) {
  4880. if (!exts.hasOwnProperty(prop)) continue;
  4881. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4882. modeObj[prop] = exts[prop];
  4883. }
  4884. }
  4885. modeObj.name = spec.name;
  4886. if (spec.helperType) modeObj.helperType = spec.helperType;
  4887. if (spec.modeProps) for (var prop in spec.modeProps)
  4888. modeObj[prop] = spec.modeProps[prop];
  4889. return modeObj;
  4890. };
  4891. // Minimal default mode.
  4892. CodeMirror.defineMode("null", function () {
  4893. return { token: function (stream) { stream.skipToEnd(); } };
  4894. });
  4895. CodeMirror.defineMIME("text/plain", "null");
  4896. // This can be used to attach properties to mode objects from
  4897. // outside the actual mode definition.
  4898. var modeExtensions = CodeMirror.modeExtensions = {};
  4899. CodeMirror.extendMode = function (mode, properties) {
  4900. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4901. copyObj(properties, exts);
  4902. };
  4903. // EXTENSIONS
  4904. CodeMirror.defineExtension = function (name, func) {
  4905. CodeMirror.prototype[name] = func;
  4906. };
  4907. CodeMirror.defineDocExtension = function (name, func) {
  4908. Doc.prototype[name] = func;
  4909. };
  4910. CodeMirror.defineOption = option;
  4911. var initHooks = [];
  4912. CodeMirror.defineInitHook = function (f) { initHooks.push(f); };
  4913. var helpers = CodeMirror.helpers = {};
  4914. CodeMirror.registerHelper = function (type, name, value) {
  4915. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = { _global: [] };
  4916. helpers[type][name] = value;
  4917. };
  4918. CodeMirror.registerGlobalHelper = function (type, name, predicate, value) {
  4919. CodeMirror.registerHelper(type, name, value);
  4920. helpers[type]._global.push({ pred: predicate, val: value });
  4921. };
  4922. // MODE STATE HANDLING
  4923. // Utility functions for working with state. Exported because nested
  4924. // modes need to do this for their inner modes.
  4925. var copyState = CodeMirror.copyState = function (mode, state) {
  4926. if (state === true) return state;
  4927. if (mode.copyState) return mode.copyState(state);
  4928. var nstate = {};
  4929. for (var n in state) {
  4930. var val = state[n];
  4931. if (val instanceof Array) val = val.concat([]);
  4932. nstate[n] = val;
  4933. }
  4934. return nstate;
  4935. };
  4936. var startState = CodeMirror.startState = function (mode, a1, a2) {
  4937. return mode.startState ? mode.startState(a1, a2) : true;
  4938. };
  4939. // Given a mode and a state (for that mode), find the inner mode and
  4940. // state at the position that the state refers to.
  4941. CodeMirror.innerMode = function (mode, state) {
  4942. while (mode.innerMode) {
  4943. var info = mode.innerMode(state);
  4944. if (!info || info.mode == mode) break;
  4945. state = info.state;
  4946. mode = info.mode;
  4947. }
  4948. return info || { mode: mode, state: state };
  4949. };
  4950. // STANDARD COMMANDS
  4951. // Commands are parameter-less actions that can be performed on an
  4952. // editor, mostly used for keybindings.
  4953. var commands = CodeMirror.commands = {
  4954. selectAll: function (cm) { cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); },
  4955. singleSelection: function (cm) {
  4956. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  4957. },
  4958. killLine: function (cm) {
  4959. deleteNearSelection(cm, function (range) {
  4960. if (range.empty()) {
  4961. var len = getLine(cm.doc, range.head.line).text.length;
  4962. if (range.head.ch == len && range.head.line < cm.lastLine())
  4963. return { from: range.head, to: Pos(range.head.line + 1, 0) };
  4964. else
  4965. return { from: range.head, to: Pos(range.head.line, len) };
  4966. } else {
  4967. return { from: range.from(), to: range.to() };
  4968. }
  4969. });
  4970. },
  4971. deleteLine: function (cm) {
  4972. deleteNearSelection(cm, function (range) {
  4973. return {
  4974. from: Pos(range.from().line, 0),
  4975. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  4976. };
  4977. });
  4978. },
  4979. delLineLeft: function (cm) {
  4980. deleteNearSelection(cm, function (range) {
  4981. return { from: Pos(range.from().line, 0), to: range.from() };
  4982. });
  4983. },
  4984. delWrappedLineLeft: function (cm) {
  4985. deleteNearSelection(cm, function (range) {
  4986. var top = cm.charCoords(range.head, "div").top + 5;
  4987. var leftPos = cm.coordsChar({ left: 0, top: top }, "div");
  4988. return { from: leftPos, to: range.from() };
  4989. });
  4990. },
  4991. delWrappedLineRight: function (cm) {
  4992. deleteNearSelection(cm, function (range) {
  4993. var top = cm.charCoords(range.head, "div").top + 5;
  4994. var rightPos = cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top }, "div");
  4995. return { from: range.from(), to: rightPos };
  4996. });
  4997. },
  4998. undo: function (cm) { cm.undo(); },
  4999. redo: function (cm) { cm.redo(); },
  5000. undoSelection: function (cm) { cm.undoSelection(); },
  5001. redoSelection: function (cm) { cm.redoSelection(); },
  5002. goDocStart: function (cm) { cm.extendSelection(Pos(cm.firstLine(), 0)); },
  5003. goDocEnd: function (cm) { cm.extendSelection(Pos(cm.lastLine())); },
  5004. goLineStart: function (cm) {
  5005. cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  5006. { origin: "+move", bias: 1 });
  5007. },
  5008. goLineStartSmart: function (cm) {
  5009. cm.extendSelectionsBy(function (range) {
  5010. return lineStartSmart(cm, range.head);
  5011. }, { origin: "+move", bias: 1 });
  5012. },
  5013. goLineEnd: function (cm) {
  5014. cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  5015. { origin: "+move", bias: -1 });
  5016. },
  5017. goLineRight: function (cm) {
  5018. cm.extendSelectionsBy(function (range) {
  5019. var top = cm.charCoords(range.head, "div").top + 5;
  5020. return cm.coordsChar({ left: cm.display.lineDiv.offsetWidth + 100, top: top }, "div");
  5021. }, sel_move);
  5022. },
  5023. goLineLeft: function (cm) {
  5024. cm.extendSelectionsBy(function (range) {
  5025. var top = cm.charCoords(range.head, "div").top + 5;
  5026. return cm.coordsChar({ left: 0, top: top }, "div");
  5027. }, sel_move);
  5028. },
  5029. goLineLeftSmart: function (cm) {
  5030. cm.extendSelectionsBy(function (range) {
  5031. var top = cm.charCoords(range.head, "div").top + 5;
  5032. var pos = cm.coordsChar({ left: 0, top: top }, "div");
  5033. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  5034. return pos;
  5035. }, sel_move);
  5036. },
  5037. goLineUp: function (cm) { cm.moveV(-1, "line"); },
  5038. goLineDown: function (cm) { cm.moveV(1, "line"); },
  5039. goPageUp: function (cm) { cm.moveV(-1, "page"); },
  5040. goPageDown: function (cm) { cm.moveV(1, "page"); },
  5041. goCharLeft: function (cm) { cm.moveH(-1, "char"); },
  5042. goCharRight: function (cm) { cm.moveH(1, "char"); },
  5043. goColumnLeft: function (cm) { cm.moveH(-1, "column"); },
  5044. goColumnRight: function (cm) { cm.moveH(1, "column"); },
  5045. goWordLeft: function (cm) { cm.moveH(-1, "word"); },
  5046. goGroupRight: function (cm) { cm.moveH(1, "group"); },
  5047. goGroupLeft: function (cm) { cm.moveH(-1, "group"); },
  5048. goWordRight: function (cm) { cm.moveH(1, "word"); },
  5049. delCharBefore: function (cm) { cm.deleteH(-1, "char"); },
  5050. delCharAfter: function (cm) { cm.deleteH(1, "char"); },
  5051. delWordBefore: function (cm) { cm.deleteH(-1, "word"); },
  5052. delWordAfter: function (cm) { cm.deleteH(1, "word"); },
  5053. delGroupBefore: function (cm) { cm.deleteH(-1, "group"); },
  5054. delGroupAfter: function (cm) { cm.deleteH(1, "group"); },
  5055. indentAuto: function (cm) { cm.indentSelection("smart"); },
  5056. indentMore: function (cm) { cm.indentSelection("add"); },
  5057. indentLess: function (cm) { cm.indentSelection("subtract"); },
  5058. insertTab: function (cm) { cm.replaceSelection("\t"); },
  5059. insertSoftTab: function (cm) {
  5060. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  5061. for (var i = 0; i < ranges.length; i++) {
  5062. var pos = ranges[i].from();
  5063. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  5064. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  5065. }
  5066. cm.replaceSelections(spaces);
  5067. },
  5068. defaultTab: function (cm) {
  5069. if (cm.somethingSelected()) cm.indentSelection("add");
  5070. else cm.execCommand("insertTab");
  5071. },
  5072. transposeChars: function (cm) {
  5073. runInOp(cm, function () {
  5074. var ranges = cm.listSelections(), newSel = [];
  5075. for (var i = 0; i < ranges.length; i++) {
  5076. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  5077. if (line) {
  5078. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  5079. if (cur.ch > 0) {
  5080. cur = new Pos(cur.line, cur.ch + 1);
  5081. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5082. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  5083. } else if (cur.line > cm.doc.first) {
  5084. var prev = getLine(cm.doc, cur.line - 1).text;
  5085. if (prev)
  5086. cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
  5087. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  5088. }
  5089. }
  5090. newSel.push(new Range(cur, cur));
  5091. }
  5092. cm.setSelections(newSel);
  5093. });
  5094. },
  5095. newlineAndIndent: function (cm) {
  5096. runInOp(cm, function () {
  5097. var len = cm.listSelections().length;
  5098. for (var i = 0; i < len; i++) {
  5099. var range = cm.listSelections()[i];
  5100. cm.replaceRange("\n", range.anchor, range.head, "+input");
  5101. cm.indentLine(range.from().line + 1, null, true);
  5102. ensureCursorVisible(cm);
  5103. }
  5104. });
  5105. },
  5106. toggleOverwrite: function (cm) { cm.toggleOverwrite(); }
  5107. };
  5108. // STANDARD KEYMAPS
  5109. var keyMap = CodeMirror.keyMap = {};
  5110. keyMap.basic = {
  5111. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5112. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5113. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5114. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5115. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5116. "Esc": "singleSelection"
  5117. };
  5118. // Note that the save and find-related commands aren't defined by
  5119. // default. User code or addons can define them. Unknown commands
  5120. // are simply ignored.
  5121. keyMap.pcDefault = {
  5122. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5123. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5124. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5125. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5126. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5127. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5128. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5129. fallthrough: "basic"
  5130. };
  5131. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5132. keyMap.emacsy = {
  5133. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5134. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5135. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5136. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  5137. };
  5138. keyMap.macDefault = {
  5139. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5140. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5141. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5142. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5143. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5144. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5145. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5146. fallthrough: ["basic", "emacsy"]
  5147. };
  5148. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5149. // KEYMAP DISPATCH
  5150. function normalizeKeyName(name) {
  5151. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5152. var alt, ctrl, shift, cmd;
  5153. for (var i = 0; i < parts.length - 1; i++) {
  5154. var mod = parts[i];
  5155. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5156. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5157. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5158. else if (/^s(hift)$/i.test(mod)) shift = true;
  5159. else throw new Error("Unrecognized modifier name: " + mod);
  5160. }
  5161. if (alt) name = "Alt-" + name;
  5162. if (ctrl) name = "Ctrl-" + name;
  5163. if (cmd) name = "Cmd-" + name;
  5164. if (shift) name = "Shift-" + name;
  5165. return name;
  5166. }
  5167. // This is a kludge to keep keymaps mostly working as raw objects
  5168. // (backwards compatibility) while at the same time support features
  5169. // like normalization and multi-stroke key bindings. It compiles a
  5170. // new normalized keymap, and then updates the old object to reflect
  5171. // this.
  5172. CodeMirror.normalizeKeyMap = function (keymap) {
  5173. var copy = {};
  5174. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5175. var value = keymap[keyname];
  5176. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5177. if (value == "...") { delete keymap[keyname]; continue; }
  5178. var keys = map(keyname.split(" "), normalizeKeyName);
  5179. for (var i = 0; i < keys.length; i++) {
  5180. var val, name;
  5181. if (i == keys.length - 1) {
  5182. name = keys.join(" ");
  5183. val = value;
  5184. } else {
  5185. name = keys.slice(0, i + 1).join(" ");
  5186. val = "...";
  5187. }
  5188. var prev = copy[name];
  5189. if (!prev) copy[name] = val;
  5190. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5191. }
  5192. delete keymap[keyname];
  5193. }
  5194. for (var prop in copy) keymap[prop] = copy[prop];
  5195. return keymap;
  5196. };
  5197. var lookupKey = CodeMirror.lookupKey = function (key, map, handle, context) {
  5198. map = getKeyMap(map);
  5199. var found = map.call ? map.call(key, context) : map[key];
  5200. if (found === false) return "nothing";
  5201. if (found === "...") return "multi";
  5202. if (found != null && handle(found)) return "handled";
  5203. if (map.fallthrough) {
  5204. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5205. return lookupKey(key, map.fallthrough, handle, context);
  5206. for (var i = 0; i < map.fallthrough.length; i++) {
  5207. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5208. if (result) return result;
  5209. }
  5210. }
  5211. };
  5212. // Modifier key presses don't count as 'real' key presses for the
  5213. // purpose of keymap fallthrough.
  5214. var isModifierKey = CodeMirror.isModifierKey = function (value) {
  5215. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5216. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5217. };
  5218. // Look up the name of a key as indicated by an event object.
  5219. var keyName = CodeMirror.keyName = function (event, noShift) {
  5220. if (presto && event.keyCode == 34 && event["char"]) return false;
  5221. var base = keyNames[event.keyCode], name = base;
  5222. if (name == null || event.altGraphKey) return false;
  5223. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5224. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5225. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5226. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5227. return name;
  5228. };
  5229. function getKeyMap(val) {
  5230. return typeof val == "string" ? keyMap[val] : val;
  5231. }
  5232. // FROMTEXTAREA
  5233. CodeMirror.fromTextArea = function (textarea, options) {
  5234. options = options ? copyObj(options) : {};
  5235. options.value = textarea.value;
  5236. if (!options.tabindex && textarea.tabIndex)
  5237. options.tabindex = textarea.tabIndex;
  5238. if (!options.placeholder && textarea.placeholder)
  5239. options.placeholder = textarea.placeholder;
  5240. // Set autofocus to true if this textarea is focused, or if it has
  5241. // autofocus and no other element is focused.
  5242. if (options.autofocus == null) {
  5243. var hasFocus = activeElt();
  5244. options.autofocus = hasFocus == textarea ||
  5245. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5246. }
  5247. function save() { textarea.value = cm.getValue(); }
  5248. if (textarea.form) {
  5249. on(textarea.form, "submit", save);
  5250. // Deplorable hack to make the submit method do the right thing.
  5251. if (!options.leaveSubmitMethodAlone) {
  5252. var form = textarea.form, realSubmit = form.submit;
  5253. try {
  5254. var wrappedSubmit = form.submit = function () {
  5255. save();
  5256. form.submit = realSubmit;
  5257. form.submit();
  5258. form.submit = wrappedSubmit;
  5259. };
  5260. } catch (e) { }
  5261. }
  5262. }
  5263. options.finishInit = function (cm) {
  5264. cm.save = save;
  5265. cm.getTextArea = function () { return textarea; };
  5266. cm.toTextArea = function () {
  5267. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5268. save();
  5269. textarea.parentNode.removeChild(cm.getWrapperElement());
  5270. textarea.style.display = "";
  5271. if (textarea.form) {
  5272. off(textarea.form, "submit", save);
  5273. if (typeof textarea.form.submit == "function")
  5274. textarea.form.submit = realSubmit;
  5275. }
  5276. };
  5277. };
  5278. textarea.style.display = "none";
  5279. var cm = CodeMirror(function (node) {
  5280. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5281. }, options);
  5282. return cm;
  5283. };
  5284. // STRING STREAM
  5285. // Fed to the mode parsers, provides helper functions to make
  5286. // parsers more succinct.
  5287. var StringStream = CodeMirror.StringStream = function (string, tabSize) {
  5288. this.pos = this.start = 0;
  5289. this.string = string;
  5290. this.tabSize = tabSize || 8;
  5291. this.lastColumnPos = this.lastColumnValue = 0;
  5292. this.lineStart = 0;
  5293. };
  5294. StringStream.prototype = {
  5295. eol: function () { return this.pos >= this.string.length; },
  5296. sol: function () { return this.pos == this.lineStart; },
  5297. peek: function () { return this.string.charAt(this.pos) || undefined; },
  5298. next: function () {
  5299. if (this.pos < this.string.length)
  5300. return this.string.charAt(this.pos++);
  5301. },
  5302. eat: function (match) {
  5303. var ch = this.string.charAt(this.pos);
  5304. if (typeof match == "string") var ok = ch == match;
  5305. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5306. if (ok) { ++this.pos; return ch; }
  5307. },
  5308. eatWhile: function (match) {
  5309. var start = this.pos;
  5310. while (this.eat(match)) { }
  5311. return this.pos > start;
  5312. },
  5313. eatSpace: function () {
  5314. var start = this.pos;
  5315. while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))++this.pos;
  5316. return this.pos > start;
  5317. },
  5318. skipToEnd: function () { this.pos = this.string.length; },
  5319. skipTo: function (ch) {
  5320. var found = this.string.indexOf(ch, this.pos);
  5321. if (found > -1) { this.pos = found; return true; }
  5322. },
  5323. backUp: function (n) { this.pos -= n; },
  5324. column: function () {
  5325. if (this.lastColumnPos < this.start) {
  5326. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5327. this.lastColumnPos = this.start;
  5328. }
  5329. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5330. },
  5331. indentation: function () {
  5332. return countColumn(this.string, null, this.tabSize) -
  5333. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5334. },
  5335. match: function (pattern, consume, caseInsensitive) {
  5336. if (typeof pattern == "string") {
  5337. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  5338. var substr = this.string.substr(this.pos, pattern.length);
  5339. if (cased(substr) == cased(pattern)) {
  5340. if (consume !== false) this.pos += pattern.length;
  5341. return true;
  5342. }
  5343. } else {
  5344. var match = this.string.slice(this.pos).match(pattern);
  5345. if (match && match.index > 0) return null;
  5346. if (match && consume !== false) this.pos += match[0].length;
  5347. return match;
  5348. }
  5349. },
  5350. current: function () { return this.string.slice(this.start, this.pos); },
  5351. hideFirstChars: function (n, inner) {
  5352. this.lineStart += n;
  5353. try { return inner(); }
  5354. finally { this.lineStart -= n; }
  5355. }
  5356. };
  5357. // TEXTMARKERS
  5358. // Created with markText and setBookmark methods. A TextMarker is a
  5359. // handle that can be used to clear or find a marked position in the
  5360. // document. Line objects hold arrays (markedSpans) containing
  5361. // {from, to, marker} object pointing to such marker objects, and
  5362. // indicating that such a marker is present on that line. Multiple
  5363. // lines may point to the same marker when it spans across lines.
  5364. // The spans will have null for their from/to properties when the
  5365. // marker continues beyond the start/end of the line. Markers have
  5366. // links back to the lines they currently touch.
  5367. var nextMarkerId = 0;
  5368. var TextMarker = CodeMirror.TextMarker = function (doc, type) {
  5369. this.lines = [];
  5370. this.type = type;
  5371. this.doc = doc;
  5372. this.id = ++nextMarkerId;
  5373. };
  5374. eventMixin(TextMarker);
  5375. // Clear the marker.
  5376. TextMarker.prototype.clear = function () {
  5377. if (this.explicitlyCleared) return;
  5378. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5379. if (withOp) startOperation(cm);
  5380. if (hasHandler(this, "clear")) {
  5381. var found = this.find();
  5382. if (found) signalLater(this, "clear", found.from, found.to);
  5383. }
  5384. var min = null, max = null;
  5385. for (var i = 0; i < this.lines.length; ++i) {
  5386. var line = this.lines[i];
  5387. var span = getMarkedSpanFor(line.markedSpans, this);
  5388. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5389. else if (cm) {
  5390. if (span.to != null) max = lineNo(line);
  5391. if (span.from != null) min = lineNo(line);
  5392. }
  5393. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5394. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5395. updateLineHeight(line, textHeight(cm.display));
  5396. }
  5397. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5398. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5399. if (len > cm.display.maxLineLength) {
  5400. cm.display.maxLine = visual;
  5401. cm.display.maxLineLength = len;
  5402. cm.display.maxLineChanged = true;
  5403. }
  5404. }
  5405. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5406. this.lines.length = 0;
  5407. this.explicitlyCleared = true;
  5408. if (this.atomic && this.doc.cantEdit) {
  5409. this.doc.cantEdit = false;
  5410. if (cm) reCheckSelection(cm.doc);
  5411. }
  5412. if (cm) signalLater(cm, "markerCleared", cm, this);
  5413. if (withOp) endOperation(cm);
  5414. if (this.parent) this.parent.clear();
  5415. };
  5416. // Find the position of the marker in the document. Returns a {from,
  5417. // to} object by default. Side can be passed to get a specific side
  5418. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5419. // Pos objects returned contain a line object, rather than a line
  5420. // number (used to prevent looking up the same line twice).
  5421. TextMarker.prototype.find = function (side, lineObj) {
  5422. if (side == null && this.type == "bookmark") side = 1;
  5423. var from, to;
  5424. for (var i = 0; i < this.lines.length; ++i) {
  5425. var line = this.lines[i];
  5426. var span = getMarkedSpanFor(line.markedSpans, this);
  5427. if (span.from != null) {
  5428. from = Pos(lineObj ? line : lineNo(line), span.from);
  5429. if (side == -1) return from;
  5430. }
  5431. if (span.to != null) {
  5432. to = Pos(lineObj ? line : lineNo(line), span.to);
  5433. if (side == 1) return to;
  5434. }
  5435. }
  5436. return from && { from: from, to: to };
  5437. };
  5438. // Signals that the marker's widget changed, and surrounding layout
  5439. // should be recomputed.
  5440. TextMarker.prototype.changed = function () {
  5441. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5442. if (!pos || !cm) return;
  5443. runInOp(cm, function () {
  5444. var line = pos.line, lineN = lineNo(pos.line);
  5445. var view = findViewForLine(cm, lineN);
  5446. if (view) {
  5447. clearLineMeasurementCacheFor(view);
  5448. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5449. }
  5450. cm.curOp.updateMaxLine = true;
  5451. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5452. var oldHeight = widget.height;
  5453. widget.height = null;
  5454. var dHeight = widgetHeight(widget) - oldHeight;
  5455. if (dHeight)
  5456. updateLineHeight(line, line.height + dHeight);
  5457. }
  5458. });
  5459. };
  5460. TextMarker.prototype.attachLine = function (line) {
  5461. if (!this.lines.length && this.doc.cm) {
  5462. var op = this.doc.cm.curOp;
  5463. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5464. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5465. }
  5466. this.lines.push(line);
  5467. };
  5468. TextMarker.prototype.detachLine = function (line) {
  5469. this.lines.splice(indexOf(this.lines, line), 1);
  5470. if (!this.lines.length && this.doc.cm) {
  5471. var op = this.doc.cm.curOp;
  5472. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5473. }
  5474. };
  5475. // Collapsed markers have unique ids, in order to be able to order
  5476. // them, which is needed for uniquely determining an outer marker
  5477. // when they overlap (they may nest, but not partially overlap).
  5478. var nextMarkerId = 0;
  5479. // Create a marker, wire it up to the right lines, and
  5480. function markText(doc, from, to, options, type) {
  5481. // Shared markers (across linked documents) are handled separately
  5482. // (markTextShared will call out to this again, once per
  5483. // document).
  5484. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5485. // Ensure we are in an operation.
  5486. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5487. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5488. if (options) copyObj(options, marker, false);
  5489. // Don't connect empty markers unless clearWhenEmpty is false
  5490. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5491. return marker;
  5492. if (marker.replacedWith) {
  5493. // Showing up as a widget implies collapsed (widget replaces text)
  5494. marker.collapsed = true;
  5495. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5496. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5497. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5498. }
  5499. if (marker.collapsed) {
  5500. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5501. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5502. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5503. sawCollapsedSpans = true;
  5504. }
  5505. if (marker.addToHistory)
  5506. addChangeToHistory(doc, { from: from, to: to, origin: "markText" }, doc.sel, NaN);
  5507. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5508. doc.iter(curLine, to.line + 1, function (line) {
  5509. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5510. updateMaxLine = true;
  5511. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5512. addMarkedSpan(line, new MarkedSpan(marker,
  5513. curLine == from.line ? from.ch : null,
  5514. curLine == to.line ? to.ch : null));
  5515. ++curLine;
  5516. });
  5517. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5518. if (marker.collapsed) doc.iter(from.line, to.line + 1, function (line) {
  5519. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5520. });
  5521. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function () { marker.clear(); });
  5522. if (marker.readOnly) {
  5523. sawReadOnlySpans = true;
  5524. if (doc.history.done.length || doc.history.undone.length)
  5525. doc.clearHistory();
  5526. }
  5527. if (marker.collapsed) {
  5528. marker.id = ++nextMarkerId;
  5529. marker.atomic = true;
  5530. }
  5531. if (cm) {
  5532. // Sync editor state
  5533. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5534. if (marker.collapsed)
  5535. regChange(cm, from.line, to.line + 1);
  5536. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5537. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5538. if (marker.atomic) reCheckSelection(cm.doc);
  5539. signalLater(cm, "markerAdded", cm, marker);
  5540. }
  5541. return marker;
  5542. }
  5543. // SHARED TEXTMARKERS
  5544. // A shared marker spans multiple linked documents. It is
  5545. // implemented as a meta-marker-object controlling multiple normal
  5546. // markers.
  5547. var SharedTextMarker = CodeMirror.SharedTextMarker = function (markers, primary) {
  5548. this.markers = markers;
  5549. this.primary = primary;
  5550. for (var i = 0; i < markers.length; ++i)
  5551. markers[i].parent = this;
  5552. };
  5553. eventMixin(SharedTextMarker);
  5554. SharedTextMarker.prototype.clear = function () {
  5555. if (this.explicitlyCleared) return;
  5556. this.explicitlyCleared = true;
  5557. for (var i = 0; i < this.markers.length; ++i)
  5558. this.markers[i].clear();
  5559. signalLater(this, "clear");
  5560. };
  5561. SharedTextMarker.prototype.find = function (side, lineObj) {
  5562. return this.primary.find(side, lineObj);
  5563. };
  5564. function markTextShared(doc, from, to, options, type) {
  5565. options = copyObj(options);
  5566. options.shared = false;
  5567. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5568. var widget = options.widgetNode;
  5569. linkedDocs(doc, function (doc) {
  5570. if (widget) options.widgetNode = widget.cloneNode(true);
  5571. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5572. for (var i = 0; i < doc.linked.length; ++i)
  5573. if (doc.linked[i].isParent) return;
  5574. primary = lst(markers);
  5575. });
  5576. return new SharedTextMarker(markers, primary);
  5577. }
  5578. function findSharedMarkers(doc) {
  5579. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5580. function (m) { return m.parent; });
  5581. }
  5582. function copySharedMarkers(doc, markers) {
  5583. for (var i = 0; i < markers.length; i++) {
  5584. var marker = markers[i], pos = marker.find();
  5585. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5586. if (cmp(mFrom, mTo)) {
  5587. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5588. marker.markers.push(subMark);
  5589. subMark.parent = marker;
  5590. }
  5591. }
  5592. }
  5593. function detachSharedMarkers(markers) {
  5594. for (var i = 0; i < markers.length; i++) {
  5595. var marker = markers[i], linked = [marker.primary.doc];;
  5596. linkedDocs(marker.primary.doc, function (d) { linked.push(d); });
  5597. for (var j = 0; j < marker.markers.length; j++) {
  5598. var subMarker = marker.markers[j];
  5599. if (indexOf(linked, subMarker.doc) == -1) {
  5600. subMarker.parent = null;
  5601. marker.markers.splice(j--, 1);
  5602. }
  5603. }
  5604. }
  5605. }
  5606. // TEXTMARKER SPANS
  5607. function MarkedSpan(marker, from, to) {
  5608. this.marker = marker;
  5609. this.from = from; this.to = to;
  5610. }
  5611. // Search an array of spans for a span matching the given marker.
  5612. function getMarkedSpanFor(spans, marker) {
  5613. if (spans) for (var i = 0; i < spans.length; ++i) {
  5614. var span = spans[i];
  5615. if (span.marker == marker) return span;
  5616. }
  5617. }
  5618. // Remove a span from an array, returning undefined if no spans are
  5619. // left (we don't store arrays for lines without spans).
  5620. function removeMarkedSpan(spans, span) {
  5621. for (var r, i = 0; i < spans.length; ++i)
  5622. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5623. return r;
  5624. }
  5625. // Add a span to a line.
  5626. function addMarkedSpan(line, span) {
  5627. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5628. span.marker.attachLine(line);
  5629. }
  5630. // Used for the algorithm that adjusts markers for a change in the
  5631. // document. These functions cut an array of spans at a given
  5632. // character position, returning an array of remaining chunks (or
  5633. // undefined if nothing remains).
  5634. function markedSpansBefore(old, startCh, isInsert) {
  5635. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5636. var span = old[i], marker = span.marker;
  5637. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5638. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5639. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5640. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5641. }
  5642. }
  5643. return nw;
  5644. }
  5645. function markedSpansAfter(old, endCh, isInsert) {
  5646. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5647. var span = old[i], marker = span.marker;
  5648. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5649. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5650. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5651. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5652. span.to == null ? null : span.to - endCh));
  5653. }
  5654. }
  5655. return nw;
  5656. }
  5657. // Given a change object, compute the new set of marker spans that
  5658. // cover the line in which the change took place. Removes spans
  5659. // entirely within the change, reconnects spans belonging to the
  5660. // same marker that appear on both sides of the change, and cuts off
  5661. // spans partially within the change. Returns an array of span
  5662. // arrays with one element for each line in (after) the change.
  5663. function stretchSpansOverChange(doc, change) {
  5664. if (change.full) return null;
  5665. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5666. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5667. if (!oldFirst && !oldLast) return null;
  5668. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5669. // Get the spans that 'stick out' on both sides
  5670. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5671. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5672. // Next, merge those two ends
  5673. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5674. if (first) {
  5675. // Fix up .to properties of first
  5676. for (var i = 0; i < first.length; ++i) {
  5677. var span = first[i];
  5678. if (span.to == null) {
  5679. var found = getMarkedSpanFor(last, span.marker);
  5680. if (!found) span.to = startCh;
  5681. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5682. }
  5683. }
  5684. }
  5685. if (last) {
  5686. // Fix up .from in last (or move them into first in case of sameLine)
  5687. for (var i = 0; i < last.length; ++i) {
  5688. var span = last[i];
  5689. if (span.to != null) span.to += offset;
  5690. if (span.from == null) {
  5691. var found = getMarkedSpanFor(first, span.marker);
  5692. if (!found) {
  5693. span.from = offset;
  5694. if (sameLine) (first || (first = [])).push(span);
  5695. }
  5696. } else {
  5697. span.from += offset;
  5698. if (sameLine) (first || (first = [])).push(span);
  5699. }
  5700. }
  5701. }
  5702. // Make sure we didn't create any zero-length spans
  5703. if (first) first = clearEmptySpans(first);
  5704. if (last && last != first) last = clearEmptySpans(last);
  5705. var newMarkers = [first];
  5706. if (!sameLine) {
  5707. // Fill gap with whole-line-spans
  5708. var gap = change.text.length - 2, gapMarkers;
  5709. if (gap > 0 && first)
  5710. for (var i = 0; i < first.length; ++i)
  5711. if (first[i].to == null)
  5712. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5713. for (var i = 0; i < gap; ++i)
  5714. newMarkers.push(gapMarkers);
  5715. newMarkers.push(last);
  5716. }
  5717. return newMarkers;
  5718. }
  5719. // Remove spans that are empty and don't have a clearWhenEmpty
  5720. // option of false.
  5721. function clearEmptySpans(spans) {
  5722. for (var i = 0; i < spans.length; ++i) {
  5723. var span = spans[i];
  5724. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5725. spans.splice(i--, 1);
  5726. }
  5727. if (!spans.length) return null;
  5728. return spans;
  5729. }
  5730. // Used for un/re-doing changes from the history. Combines the
  5731. // result of computing the existing spans with the set of spans that
  5732. // existed in the history (so that deleting around a span and then
  5733. // undoing brings back the span).
  5734. function mergeOldSpans(doc, change) {
  5735. var old = getOldSpans(doc, change);
  5736. var stretched = stretchSpansOverChange(doc, change);
  5737. if (!old) return stretched;
  5738. if (!stretched) return old;
  5739. for (var i = 0; i < old.length; ++i) {
  5740. var oldCur = old[i], stretchCur = stretched[i];
  5741. if (oldCur && stretchCur) {
  5742. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5743. var span = stretchCur[j];
  5744. for (var k = 0; k < oldCur.length; ++k)
  5745. if (oldCur[k].marker == span.marker) continue spans;
  5746. oldCur.push(span);
  5747. }
  5748. } else if (stretchCur) {
  5749. old[i] = stretchCur;
  5750. }
  5751. }
  5752. return old;
  5753. }
  5754. // Used to 'clip' out readOnly ranges when making a change.
  5755. function removeReadOnlyRanges(doc, from, to) {
  5756. var markers = null;
  5757. doc.iter(from.line, to.line + 1, function (line) {
  5758. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5759. var mark = line.markedSpans[i].marker;
  5760. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5761. (markers || (markers = [])).push(mark);
  5762. }
  5763. });
  5764. if (!markers) return null;
  5765. var parts = [{ from: from, to: to }];
  5766. for (var i = 0; i < markers.length; ++i) {
  5767. var mk = markers[i], m = mk.find(0);
  5768. for (var j = 0; j < parts.length; ++j) {
  5769. var p = parts[j];
  5770. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5771. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5772. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5773. newParts.push({ from: p.from, to: m.from });
  5774. if (dto > 0 || !mk.inclusiveRight && !dto)
  5775. newParts.push({ from: m.to, to: p.to });
  5776. parts.splice.apply(parts, newParts);
  5777. j += newParts.length - 1;
  5778. }
  5779. }
  5780. return parts;
  5781. }
  5782. // Connect or disconnect spans from a line.
  5783. function detachMarkedSpans(line) {
  5784. var spans = line.markedSpans;
  5785. if (!spans) return;
  5786. for (var i = 0; i < spans.length; ++i)
  5787. spans[i].marker.detachLine(line);
  5788. line.markedSpans = null;
  5789. }
  5790. function attachMarkedSpans(line, spans) {
  5791. if (!spans) return;
  5792. for (var i = 0; i < spans.length; ++i)
  5793. spans[i].marker.attachLine(line);
  5794. line.markedSpans = spans;
  5795. }
  5796. // Helpers used when computing which overlapping collapsed span
  5797. // counts as the larger one.
  5798. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5799. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5800. // Returns a number indicating which of two overlapping collapsed
  5801. // spans is larger (and thus includes the other). Falls back to
  5802. // comparing ids when the spans cover exactly the same range.
  5803. function compareCollapsedMarkers(a, b) {
  5804. var lenDiff = a.lines.length - b.lines.length;
  5805. if (lenDiff != 0) return lenDiff;
  5806. var aPos = a.find(), bPos = b.find();
  5807. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5808. if (fromCmp) return -fromCmp;
  5809. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5810. if (toCmp) return toCmp;
  5811. return b.id - a.id;
  5812. }
  5813. // Find out whether a line ends or starts in a collapsed span. If
  5814. // so, return the marker for that span.
  5815. function collapsedSpanAtSide(line, start) {
  5816. var sps = sawCollapsedSpans && line.markedSpans, found;
  5817. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5818. sp = sps[i];
  5819. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5820. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5821. found = sp.marker;
  5822. }
  5823. return found;
  5824. }
  5825. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5826. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5827. // Test whether there exists a collapsed span that partially
  5828. // overlaps (covers the start or end, but not both) of a new span.
  5829. // Such overlap is not allowed.
  5830. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5831. var line = getLine(doc, lineNo);
  5832. var sps = sawCollapsedSpans && line.markedSpans;
  5833. if (sps) for (var i = 0; i < sps.length; ++i) {
  5834. var sp = sps[i];
  5835. if (!sp.marker.collapsed) continue;
  5836. var found = sp.marker.find(0);
  5837. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5838. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5839. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5840. if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
  5841. fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
  5842. return true;
  5843. }
  5844. }
  5845. // A visual line is a line as drawn on the screen. Folding, for
  5846. // example, can cause multiple logical lines to appear on the same
  5847. // visual line. This finds the start of the visual line that the
  5848. // given line is part of (usually that is the line itself).
  5849. function visualLine(line) {
  5850. var merged;
  5851. while (merged = collapsedSpanAtStart(line))
  5852. line = merged.find(-1, true).line;
  5853. return line;
  5854. }
  5855. // Returns an array of logical lines that continue the visual line
  5856. // started by the argument, or undefined if there are no such lines.
  5857. function visualLineContinued(line) {
  5858. var merged, lines;
  5859. while (merged = collapsedSpanAtEnd(line)) {
  5860. line = merged.find(1, true).line;
  5861. (lines || (lines = [])).push(line);
  5862. }
  5863. return lines;
  5864. }
  5865. // Get the line number of the start of the visual line that the
  5866. // given line number is part of.
  5867. function visualLineNo(doc, lineN) {
  5868. var line = getLine(doc, lineN), vis = visualLine(line);
  5869. if (line == vis) return lineN;
  5870. return lineNo(vis);
  5871. }
  5872. // Get the line number of the start of the next visual line after
  5873. // the given line.
  5874. function visualLineEndNo(doc, lineN) {
  5875. if (lineN > doc.lastLine()) return lineN;
  5876. var line = getLine(doc, lineN), merged;
  5877. if (!lineIsHidden(doc, line)) return lineN;
  5878. while (merged = collapsedSpanAtEnd(line))
  5879. line = merged.find(1, true).line;
  5880. return lineNo(line) + 1;
  5881. }
  5882. // Compute whether a line is hidden. Lines count as hidden when they
  5883. // are part of a visual line that starts with another line, or when
  5884. // they are entirely covered by collapsed, non-widget span.
  5885. function lineIsHidden(doc, line) {
  5886. var sps = sawCollapsedSpans && line.markedSpans;
  5887. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5888. sp = sps[i];
  5889. if (!sp.marker.collapsed) continue;
  5890. if (sp.from == null) return true;
  5891. if (sp.marker.widgetNode) continue;
  5892. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5893. return true;
  5894. }
  5895. }
  5896. function lineIsHiddenInner(doc, line, span) {
  5897. if (span.to == null) {
  5898. var end = span.marker.find(1, true);
  5899. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5900. }
  5901. if (span.marker.inclusiveRight && span.to == line.text.length)
  5902. return true;
  5903. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5904. sp = line.markedSpans[i];
  5905. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5906. (sp.to == null || sp.to != span.from) &&
  5907. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5908. lineIsHiddenInner(doc, line, sp)) return true;
  5909. }
  5910. }
  5911. // LINE WIDGETS
  5912. // Line widgets are block elements displayed above or below a line.
  5913. var LineWidget = CodeMirror.LineWidget = function (doc, node, options) {
  5914. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  5915. this[opt] = options[opt];
  5916. this.doc = doc;
  5917. this.node = node;
  5918. };
  5919. eventMixin(LineWidget);
  5920. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5921. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5922. addToScrollPos(cm, null, diff);
  5923. }
  5924. LineWidget.prototype.clear = function () {
  5925. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5926. if (no == null || !ws) return;
  5927. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  5928. if (!ws.length) line.widgets = null;
  5929. var height = widgetHeight(this);
  5930. updateLineHeight(line, Math.max(0, line.height - height));
  5931. if (cm) runInOp(cm, function () {
  5932. adjustScrollWhenAboveVisible(cm, line, -height);
  5933. regLineChange(cm, no, "widget");
  5934. });
  5935. };
  5936. LineWidget.prototype.changed = function () {
  5937. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5938. this.height = null;
  5939. var diff = widgetHeight(this) - oldH;
  5940. if (!diff) return;
  5941. updateLineHeight(line, line.height + diff);
  5942. if (cm) runInOp(cm, function () {
  5943. cm.curOp.forceUpdate = true;
  5944. adjustScrollWhenAboveVisible(cm, line, diff);
  5945. });
  5946. };
  5947. function widgetHeight(widget) {
  5948. if (widget.height != null) return widget.height;
  5949. var cm = widget.doc.cm;
  5950. if (!cm) return 0;
  5951. if (!contains(document.body, widget.node)) {
  5952. var parentStyle = "position: relative;";
  5953. if (widget.coverGutter)
  5954. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  5955. if (widget.noHScroll)
  5956. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  5957. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  5958. }
  5959. return widget.height = widget.node.offsetHeight;
  5960. }
  5961. function addLineWidget(doc, handle, node, options) {
  5962. var widget = new LineWidget(doc, node, options);
  5963. var cm = doc.cm;
  5964. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  5965. changeLine(doc, handle, "widget", function (line) {
  5966. var widgets = line.widgets || (line.widgets = []);
  5967. if (widget.insertAt == null) widgets.push(widget);
  5968. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  5969. widget.line = line;
  5970. if (cm && !lineIsHidden(doc, line)) {
  5971. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5972. updateLineHeight(line, line.height + widgetHeight(widget));
  5973. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  5974. cm.curOp.forceUpdate = true;
  5975. }
  5976. return true;
  5977. });
  5978. return widget;
  5979. }
  5980. // LINE DATA STRUCTURE
  5981. // Line objects. These hold state related to a line, including
  5982. // highlighting info (the styles array).
  5983. var Line = CodeMirror.Line = function (text, markedSpans, estimateHeight) {
  5984. this.text = text;
  5985. attachMarkedSpans(this, markedSpans);
  5986. this.height = estimateHeight ? estimateHeight(this) : 1;
  5987. };
  5988. eventMixin(Line);
  5989. Line.prototype.lineNo = function () { return lineNo(this); };
  5990. // Change the content (text, markers) of a line. Automatically
  5991. // invalidates cached information and tries to re-estimate the
  5992. // line's height.
  5993. function updateLine(line, text, markedSpans, estimateHeight) {
  5994. line.text = text;
  5995. if (line.stateAfter) line.stateAfter = null;
  5996. if (line.styles) line.styles = null;
  5997. if (line.order != null) line.order = null;
  5998. detachMarkedSpans(line);
  5999. attachMarkedSpans(line, markedSpans);
  6000. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  6001. if (estHeight != line.height) updateLineHeight(line, estHeight);
  6002. }
  6003. // Detach a line from the document tree and its markers.
  6004. function cleanUpLine(line) {
  6005. line.parent = null;
  6006. detachMarkedSpans(line);
  6007. }
  6008. function extractLineClasses(type, output) {
  6009. if (type) for (; ;) {
  6010. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  6011. if (!lineClass) break;
  6012. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  6013. var prop = lineClass[1] ? "bgClass" : "textClass";
  6014. if (output[prop] == null)
  6015. output[prop] = lineClass[2];
  6016. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  6017. output[prop] += " " + lineClass[2];
  6018. }
  6019. return type;
  6020. }
  6021. function callBlankLine(mode, state) {
  6022. if (mode.blankLine) return mode.blankLine(state);
  6023. if (!mode.innerMode) return;
  6024. var inner = CodeMirror.innerMode(mode, state);
  6025. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  6026. }
  6027. function readToken(mode, stream, state, inner) {
  6028. for (var i = 0; i < 10; i++) {
  6029. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  6030. var style = mode.token(stream, state);
  6031. if (stream.pos > stream.start) return style;
  6032. }
  6033. throw new Error("Mode " + mode.name + " failed to advance stream.");
  6034. }
  6035. // Utility for getTokenAt and getLineTokens
  6036. function takeToken(cm, pos, precise, asArray) {
  6037. function getObj(copy) {
  6038. return {
  6039. start: stream.start, end: stream.pos,
  6040. string: stream.current(),
  6041. type: style || null,
  6042. state: copy ? copyState(doc.mode, state) : state
  6043. };
  6044. }
  6045. var doc = cm.doc, mode = doc.mode, style;
  6046. pos = clipPos(doc, pos);
  6047. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  6048. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  6049. if (asArray) tokens = [];
  6050. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  6051. stream.start = stream.pos;
  6052. style = readToken(mode, stream, state);
  6053. if (asArray) tokens.push(getObj(true));
  6054. }
  6055. return asArray ? tokens : getObj();
  6056. }
  6057. // Run the given mode's parser over a line, calling f for each token.
  6058. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  6059. var flattenSpans = mode.flattenSpans;
  6060. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  6061. var curStart = 0, curStyle = null;
  6062. var stream = new StringStream(text, cm.options.tabSize), style;
  6063. var inner = cm.options.addModeClass && [null];
  6064. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  6065. while (!stream.eol()) {
  6066. if (stream.pos > cm.options.maxHighlightLength) {
  6067. flattenSpans = false;
  6068. if (forceToEnd) processLine(cm, text, state, stream.pos);
  6069. stream.pos = text.length;
  6070. style = null;
  6071. } else {
  6072. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  6073. }
  6074. if (inner) {
  6075. var mName = inner[0].name;
  6076. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  6077. }
  6078. if (!flattenSpans || curStyle != style) {
  6079. while (curStart < stream.start) {
  6080. curStart = Math.min(stream.start, curStart + 50000);
  6081. f(curStart, curStyle);
  6082. }
  6083. curStyle = style;
  6084. }
  6085. stream.start = stream.pos;
  6086. }
  6087. while (curStart < stream.pos) {
  6088. // Webkit seems to refuse to render text nodes longer than 57444 characters
  6089. var pos = Math.min(stream.pos, curStart + 50000);
  6090. f(pos, curStyle);
  6091. curStart = pos;
  6092. }
  6093. }
  6094. // Compute a style array (an array starting with a mode generation
  6095. // -- for invalidation -- followed by pairs of end positions and
  6096. // style strings), which is used to highlight the tokens on the
  6097. // line.
  6098. function highlightLine(cm, line, state, forceToEnd) {
  6099. // A styles array always starts with a number identifying the
  6100. // mode/overlays that it is based on (for easy invalidation).
  6101. var st = [cm.state.modeGen], lineClasses = {};
  6102. // Compute the base array of styles
  6103. runMode(cm, line.text, cm.doc.mode, state, function (end, style) {
  6104. st.push(end, style);
  6105. }, lineClasses, forceToEnd);
  6106. // Run overlays, adjust style array.
  6107. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6108. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6109. runMode(cm, line.text, overlay.mode, true, function (end, style) {
  6110. var start = i;
  6111. // Ensure there's a token end at the current position, and that i points at it
  6112. while (at < end) {
  6113. var i_end = st[i];
  6114. if (i_end > end)
  6115. st.splice(i, 1, end, st[i + 1], i_end);
  6116. i += 2;
  6117. at = Math.min(end, i_end);
  6118. }
  6119. if (!style) return;
  6120. if (overlay.opaque) {
  6121. st.splice(start, i - start, end, "cm-overlay " + style);
  6122. i = start + 2;
  6123. } else {
  6124. for (; start < i; start += 2) {
  6125. var cur = st[start + 1];
  6126. st[start + 1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6127. }
  6128. }
  6129. }, lineClasses);
  6130. }
  6131. return { styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null };
  6132. }
  6133. function getLineStyles(cm, line, updateFrontier) {
  6134. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6135. var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  6136. line.styles = result.styles;
  6137. if (result.classes) line.styleClasses = result.classes;
  6138. else if (line.styleClasses) line.styleClasses = null;
  6139. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6140. }
  6141. return line.styles;
  6142. }
  6143. // Lightweight form of highlight -- proceed over this line and
  6144. // update state, but don't save a style array. Used for lines that
  6145. // aren't currently visible.
  6146. function processLine(cm, text, state, startAt) {
  6147. var mode = cm.doc.mode;
  6148. var stream = new StringStream(text, cm.options.tabSize);
  6149. stream.start = stream.pos = startAt || 0;
  6150. if (text == "") callBlankLine(mode, state);
  6151. while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
  6152. readToken(mode, stream, state);
  6153. stream.start = stream.pos;
  6154. }
  6155. }
  6156. // Convert a style as returned by a mode (either null, or a string
  6157. // containing one or more styles) to a CSS style. This is cached,
  6158. // and also looks for line-wide styles.
  6159. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6160. function interpretTokenStyle(style, options) {
  6161. if (!style || /^\s*$/.test(style)) return null;
  6162. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6163. return cache[style] ||
  6164. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6165. }
  6166. // Render the DOM representation of the text of a line. Also builds
  6167. // up a 'line map', which points at the DOM nodes that represent
  6168. // specific stretches of text, and is used by the measuring code.
  6169. // The returned object contains the DOM node, this map, and
  6170. // information about line-wide styles that were set by the mode.
  6171. function buildLineContent(cm, lineView) {
  6172. // The padding-right forces the element to have a 'border', which
  6173. // is needed on Webkit to be able to get line-level bounding
  6174. // rectangles for it (in measureChar).
  6175. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6176. var builder = {
  6177. pre: elt("pre", [content]), content: content,
  6178. col: 0, pos: 0, cm: cm,
  6179. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")
  6180. };
  6181. lineView.measure = {};
  6182. // Iterate over the logical lines that make up this visual line.
  6183. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6184. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6185. builder.pos = 0;
  6186. builder.addToken = buildToken;
  6187. // Optionally wire in some hacks into the token-rendering
  6188. // algorithm, to deal with browser quirks.
  6189. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6190. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6191. builder.map = [];
  6192. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6193. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6194. if (line.styleClasses) {
  6195. if (line.styleClasses.bgClass)
  6196. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6197. if (line.styleClasses.textClass)
  6198. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6199. }
  6200. // Ensure at least a single node is present, for measuring.
  6201. if (builder.map.length == 0)
  6202. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6203. // Store the map and a cache object for the current logical line
  6204. if (i == 0) {
  6205. lineView.measure.map = builder.map;
  6206. lineView.measure.cache = {};
  6207. } else {
  6208. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6209. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6210. }
  6211. }
  6212. // See issue #2901
  6213. if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
  6214. builder.content.className = "cm-tab-wrap-hack";
  6215. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6216. if (builder.pre.className)
  6217. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6218. return builder;
  6219. }
  6220. function defaultSpecialCharPlaceholder(ch) {
  6221. var token = elt("span", "\u2022", "cm-invalidchar");
  6222. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6223. token.setAttribute("aria-label", token.title);
  6224. return token;
  6225. }
  6226. // Build up the DOM representation for a single token, and add it to
  6227. // the line map. Takes care to render special characters separately.
  6228. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6229. if (!text) return;
  6230. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  6231. var special = builder.cm.state.specialChars, mustWrap = false;
  6232. if (!special.test(text)) {
  6233. builder.col += text.length;
  6234. var content = document.createTextNode(displayText);
  6235. builder.map.push(builder.pos, builder.pos + text.length, content);
  6236. if (ie && ie_version < 9) mustWrap = true;
  6237. builder.pos += text.length;
  6238. } else {
  6239. var content = document.createDocumentFragment(), pos = 0;
  6240. while (true) {
  6241. special.lastIndex = pos;
  6242. var m = special.exec(text);
  6243. var skipped = m ? m.index - pos : text.length - pos;
  6244. if (skipped) {
  6245. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  6246. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6247. else content.appendChild(txt);
  6248. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6249. builder.col += skipped;
  6250. builder.pos += skipped;
  6251. }
  6252. if (!m) break;
  6253. pos += skipped + 1;
  6254. if (m[0] == "\t") {
  6255. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6256. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6257. txt.setAttribute("role", "presentation");
  6258. txt.setAttribute("cm-text", "\t");
  6259. builder.col += tabWidth;
  6260. } else {
  6261. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6262. txt.setAttribute("cm-text", m[0]);
  6263. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6264. else content.appendChild(txt);
  6265. builder.col += 1;
  6266. }
  6267. builder.map.push(builder.pos, builder.pos + 1, txt);
  6268. builder.pos++;
  6269. }
  6270. }
  6271. if (style || startStyle || endStyle || mustWrap || css) {
  6272. var fullStyle = style || "";
  6273. if (startStyle) fullStyle += startStyle;
  6274. if (endStyle) fullStyle += endStyle;
  6275. var token = elt("span", [content], fullStyle, css);
  6276. if (title) token.title = title;
  6277. return builder.content.appendChild(token);
  6278. }
  6279. builder.content.appendChild(content);
  6280. }
  6281. function splitSpaces(old) {
  6282. var out = " ";
  6283. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  6284. out += " ";
  6285. return out;
  6286. }
  6287. // Work around nonsense dimensions being reported for stretches of
  6288. // right-to-left text.
  6289. function buildTokenBadBidi(inner, order) {
  6290. return function (builder, text, style, startStyle, endStyle, title, css) {
  6291. style = style ? style + " cm-force-border" : "cm-force-border";
  6292. var start = builder.pos, end = start + text.length;
  6293. for (; ;) {
  6294. // Find the part that overlaps with the start of this text
  6295. for (var i = 0; i < order.length; i++) {
  6296. var part = order[i];
  6297. if (part.to > start && part.from <= start) break;
  6298. }
  6299. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  6300. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  6301. startStyle = null;
  6302. text = text.slice(part.to - start);
  6303. start = part.to;
  6304. }
  6305. };
  6306. }
  6307. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6308. var widget = !ignoreWidget && marker.widgetNode;
  6309. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6310. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6311. if (!widget)
  6312. widget = builder.content.appendChild(document.createElement("span"));
  6313. widget.setAttribute("cm-marker", marker.id);
  6314. }
  6315. if (widget) {
  6316. builder.cm.display.input.setUneditable(widget);
  6317. builder.content.appendChild(widget);
  6318. }
  6319. builder.pos += size;
  6320. }
  6321. // Outputs a number of spans to make up a line, taking highlighting
  6322. // and marked text into account.
  6323. function insertLineContent(line, builder, styles) {
  6324. var spans = line.markedSpans, allText = line.text, at = 0;
  6325. if (!spans) {
  6326. for (var i = 1; i < styles.length; i += 2)
  6327. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i + 1], builder.cm.options));
  6328. return;
  6329. }
  6330. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6331. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6332. for (; ;) {
  6333. if (nextChange == pos) { // Update current marker set
  6334. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6335. collapsed = null; nextChange = Infinity;
  6336. var foundBookmarks = [];
  6337. for (var j = 0; j < spans.length; ++j) {
  6338. var sp = spans[j], m = sp.marker;
  6339. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  6340. foundBookmarks.push(m);
  6341. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  6342. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  6343. nextChange = sp.to;
  6344. spanEndStyle = "";
  6345. }
  6346. if (m.className) spanStyle += " " + m.className;
  6347. if (m.css) css = m.css;
  6348. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6349. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  6350. if (m.title && !title) title = m.title;
  6351. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6352. collapsed = sp;
  6353. } else if (sp.from > pos && nextChange > sp.from) {
  6354. nextChange = sp.from;
  6355. }
  6356. }
  6357. if (collapsed && (collapsed.from || 0) == pos) {
  6358. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6359. collapsed.marker, collapsed.from == null);
  6360. if (collapsed.to == null) return;
  6361. if (collapsed.to == pos) collapsed = false;
  6362. }
  6363. if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
  6364. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6365. }
  6366. if (pos >= len) break;
  6367. var upto = Math.min(len, nextChange);
  6368. while (true) {
  6369. if (text) {
  6370. var end = pos + text.length;
  6371. if (!collapsed) {
  6372. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6373. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6374. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6375. }
  6376. if (end >= upto) { text = text.slice(upto - pos); pos = upto; break; }
  6377. pos = end;
  6378. spanStartStyle = "";
  6379. }
  6380. text = allText.slice(at, at = styles[i++]);
  6381. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6382. }
  6383. }
  6384. }
  6385. // DOCUMENT DATA STRUCTURE
  6386. // By default, updates that start and end at the beginning of a line
  6387. // are treated specially, in order to make the association of line
  6388. // widgets and marker elements with the text behave more intuitive.
  6389. function isWholeLineUpdate(doc, change) {
  6390. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6391. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6392. }
  6393. // Perform a change on the document data structure.
  6394. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6395. function spansFor(n) { return markedSpans ? markedSpans[n] : null; }
  6396. function update(line, text, spans) {
  6397. updateLine(line, text, spans, estimateHeight);
  6398. signalLater(line, "change", line, change);
  6399. }
  6400. function linesFor(start, end) {
  6401. for (var i = start, result = []; i < end; ++i)
  6402. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6403. return result;
  6404. }
  6405. var from = change.from, to = change.to, text = change.text;
  6406. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6407. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6408. // Adjust the line structure
  6409. if (change.full) {
  6410. doc.insert(0, linesFor(0, text.length));
  6411. doc.remove(text.length, doc.size - text.length);
  6412. } else if (isWholeLineUpdate(doc, change)) {
  6413. // This is a whole-line replace. Treated specially to make
  6414. // sure line objects move the way they are supposed to.
  6415. var added = linesFor(0, text.length - 1);
  6416. update(lastLine, lastLine.text, lastSpans);
  6417. if (nlines) doc.remove(from.line, nlines);
  6418. if (added.length) doc.insert(from.line, added);
  6419. } else if (firstLine == lastLine) {
  6420. if (text.length == 1) {
  6421. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6422. } else {
  6423. var added = linesFor(1, text.length - 1);
  6424. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6425. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6426. doc.insert(from.line + 1, added);
  6427. }
  6428. } else if (text.length == 1) {
  6429. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6430. doc.remove(from.line + 1, nlines);
  6431. } else {
  6432. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6433. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6434. var added = linesFor(1, text.length - 1);
  6435. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6436. doc.insert(from.line + 1, added);
  6437. }
  6438. signalLater(doc, "change", doc, change);
  6439. }
  6440. // The document is represented as a BTree consisting of leaves, with
  6441. // chunk of lines in them, and branches, with up to ten leaves or
  6442. // other branch nodes below them. The top node is always a branch
  6443. // node, and is the document object itself (meaning it has
  6444. // additional methods and properties).
  6445. //
  6446. // All nodes have parent links. The tree is used both to go from
  6447. // line numbers to line objects, and to go from objects to numbers.
  6448. // It also indexes by height, and is used to convert between height
  6449. // and line object, and to find the total height of the document.
  6450. //
  6451. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6452. function LeafChunk(lines) {
  6453. this.lines = lines;
  6454. this.parent = null;
  6455. for (var i = 0, height = 0; i < lines.length; ++i) {
  6456. lines[i].parent = this;
  6457. height += lines[i].height;
  6458. }
  6459. this.height = height;
  6460. }
  6461. LeafChunk.prototype = {
  6462. chunkSize: function () { return this.lines.length; },
  6463. // Remove the n lines at offset 'at'.
  6464. removeInner: function (at, n) {
  6465. for (var i = at, e = at + n; i < e; ++i) {
  6466. var line = this.lines[i];
  6467. this.height -= line.height;
  6468. cleanUpLine(line);
  6469. signalLater(line, "delete");
  6470. }
  6471. this.lines.splice(at, n);
  6472. },
  6473. // Helper used to collapse a small branch into a single leaf.
  6474. collapse: function (lines) {
  6475. lines.push.apply(lines, this.lines);
  6476. },
  6477. // Insert the given array of lines at offset 'at', count them as
  6478. // having the given height.
  6479. insertInner: function (at, lines, height) {
  6480. this.height += height;
  6481. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6482. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6483. },
  6484. // Used to iterate over a part of the tree.
  6485. iterN: function (at, n, op) {
  6486. for (var e = at + n; at < e; ++at)
  6487. if (op(this.lines[at])) return true;
  6488. }
  6489. };
  6490. function BranchChunk(children) {
  6491. this.children = children;
  6492. var size = 0, height = 0;
  6493. for (var i = 0; i < children.length; ++i) {
  6494. var ch = children[i];
  6495. size += ch.chunkSize(); height += ch.height;
  6496. ch.parent = this;
  6497. }
  6498. this.size = size;
  6499. this.height = height;
  6500. this.parent = null;
  6501. }
  6502. BranchChunk.prototype = {
  6503. chunkSize: function () { return this.size; },
  6504. removeInner: function (at, n) {
  6505. this.size -= n;
  6506. for (var i = 0; i < this.children.length; ++i) {
  6507. var child = this.children[i], sz = child.chunkSize();
  6508. if (at < sz) {
  6509. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6510. child.removeInner(at, rm);
  6511. this.height -= oldHeight - child.height;
  6512. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6513. if ((n -= rm) == 0) break;
  6514. at = 0;
  6515. } else at -= sz;
  6516. }
  6517. // If the result is smaller than 25 lines, ensure that it is a
  6518. // single leaf node.
  6519. if (this.size - n < 25 &&
  6520. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6521. var lines = [];
  6522. this.collapse(lines);
  6523. this.children = [new LeafChunk(lines)];
  6524. this.children[0].parent = this;
  6525. }
  6526. },
  6527. collapse: function (lines) {
  6528. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6529. },
  6530. insertInner: function (at, lines, height) {
  6531. this.size += lines.length;
  6532. this.height += height;
  6533. for (var i = 0; i < this.children.length; ++i) {
  6534. var child = this.children[i], sz = child.chunkSize();
  6535. if (at <= sz) {
  6536. child.insertInner(at, lines, height);
  6537. if (child.lines && child.lines.length > 50) {
  6538. while (child.lines.length > 50) {
  6539. var spilled = child.lines.splice(child.lines.length - 25, 25);
  6540. var newleaf = new LeafChunk(spilled);
  6541. child.height -= newleaf.height;
  6542. this.children.splice(i + 1, 0, newleaf);
  6543. newleaf.parent = this;
  6544. }
  6545. this.maybeSpill();
  6546. }
  6547. break;
  6548. }
  6549. at -= sz;
  6550. }
  6551. },
  6552. // When a node has grown, check whether it should be split.
  6553. maybeSpill: function () {
  6554. if (this.children.length <= 10) return;
  6555. var me = this;
  6556. do {
  6557. var spilled = me.children.splice(me.children.length - 5, 5);
  6558. var sibling = new BranchChunk(spilled);
  6559. if (!me.parent) { // Become the parent node
  6560. var copy = new BranchChunk(me.children);
  6561. copy.parent = me;
  6562. me.children = [copy, sibling];
  6563. me = copy;
  6564. } else {
  6565. me.size -= sibling.size;
  6566. me.height -= sibling.height;
  6567. var myIndex = indexOf(me.parent.children, me);
  6568. me.parent.children.splice(myIndex + 1, 0, sibling);
  6569. }
  6570. sibling.parent = me.parent;
  6571. } while (me.children.length > 10);
  6572. me.parent.maybeSpill();
  6573. },
  6574. iterN: function (at, n, op) {
  6575. for (var i = 0; i < this.children.length; ++i) {
  6576. var child = this.children[i], sz = child.chunkSize();
  6577. if (at < sz) {
  6578. var used = Math.min(n, sz - at);
  6579. if (child.iterN(at, used, op)) return true;
  6580. if ((n -= used) == 0) break;
  6581. at = 0;
  6582. } else at -= sz;
  6583. }
  6584. }
  6585. };
  6586. var nextDocId = 0;
  6587. var Doc = CodeMirror.Doc = function (text, mode, firstLine) {
  6588. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  6589. if (firstLine == null) firstLine = 0;
  6590. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6591. this.first = firstLine;
  6592. this.scrollTop = this.scrollLeft = 0;
  6593. this.cantEdit = false;
  6594. this.cleanGeneration = 1;
  6595. this.frontier = firstLine;
  6596. var start = Pos(firstLine, 0);
  6597. this.sel = simpleSelection(start);
  6598. this.history = new History(null);
  6599. this.id = ++nextDocId;
  6600. this.modeOption = mode;
  6601. if (typeof text == "string") text = splitLines(text);
  6602. updateDoc(this, { from: start, to: start, text: text });
  6603. setSelection(this, simpleSelection(start), sel_dontScroll);
  6604. };
  6605. Doc.prototype = createObj(BranchChunk.prototype, {
  6606. constructor: Doc,
  6607. // Iterate over the document. Supports two forms -- with only one
  6608. // argument, it calls that for each line in the document. With
  6609. // three, it iterates over the range given by the first two (with
  6610. // the second being non-inclusive).
  6611. iter: function (from, to, op) {
  6612. if (op) this.iterN(from - this.first, to - from, op);
  6613. else this.iterN(this.first, this.first + this.size, from);
  6614. },
  6615. // Non-public interface for adding and removing lines.
  6616. insert: function (at, lines) {
  6617. var height = 0;
  6618. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6619. this.insertInner(at - this.first, lines, height);
  6620. },
  6621. remove: function (at, n) { this.removeInner(at - this.first, n); },
  6622. // From here, the methods are part of the public interface. Most
  6623. // are also available from CodeMirror (editor) instances.
  6624. getValue: function (lineSep) {
  6625. var lines = getLines(this, this.first, this.first + this.size);
  6626. if (lineSep === false) return lines;
  6627. return lines.join(lineSep || "\n");
  6628. },
  6629. setValue: docMethodOp(function (code) {
  6630. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6631. makeChange(this, {
  6632. from: top, to: Pos(last, getLine(this, last).text.length),
  6633. text: splitLines(code), origin: "setValue", full: true
  6634. }, true);
  6635. setSelection(this, simpleSelection(top));
  6636. }),
  6637. replaceRange: function (code, from, to, origin) {
  6638. from = clipPos(this, from);
  6639. to = to ? clipPos(this, to) : from;
  6640. replaceRange(this, code, from, to, origin);
  6641. },
  6642. getRange: function (from, to, lineSep) {
  6643. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6644. if (lineSep === false) return lines;
  6645. return lines.join(lineSep || "\n");
  6646. },
  6647. getLine: function (line) { var l = this.getLineHandle(line); return l && l.text; },
  6648. getLineHandle: function (line) { if (isLine(this, line)) return getLine(this, line); },
  6649. getLineNumber: function (line) { return lineNo(line); },
  6650. getLineHandleVisualStart: function (line) {
  6651. if (typeof line == "number") line = getLine(this, line);
  6652. return visualLine(line);
  6653. },
  6654. lineCount: function () { return this.size; },
  6655. firstLine: function () { return this.first; },
  6656. lastLine: function () { return this.first + this.size - 1; },
  6657. clipPos: function (pos) { return clipPos(this, pos); },
  6658. getCursor: function (start) {
  6659. var range = this.sel.primary(), pos;
  6660. if (start == null || start == "head") pos = range.head;
  6661. else if (start == "anchor") pos = range.anchor;
  6662. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6663. else pos = range.from();
  6664. return pos;
  6665. },
  6666. listSelections: function () { return this.sel.ranges; },
  6667. somethingSelected: function () { return this.sel.somethingSelected(); },
  6668. setCursor: docMethodOp(function (line, ch, options) {
  6669. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6670. }),
  6671. setSelection: docMethodOp(function (anchor, head, options) {
  6672. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6673. }),
  6674. extendSelection: docMethodOp(function (head, other, options) {
  6675. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6676. }),
  6677. extendSelections: docMethodOp(function (heads, options) {
  6678. extendSelections(this, clipPosArray(this, heads, options));
  6679. }),
  6680. extendSelectionsBy: docMethodOp(function (f, options) {
  6681. extendSelections(this, map(this.sel.ranges, f), options);
  6682. }),
  6683. setSelections: docMethodOp(function (ranges, primary, options) {
  6684. if (!ranges.length) return;
  6685. for (var i = 0, out = []; i < ranges.length; i++)
  6686. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6687. clipPos(this, ranges[i].head));
  6688. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6689. setSelection(this, normalizeSelection(out, primary), options);
  6690. }),
  6691. addSelection: docMethodOp(function (anchor, head, options) {
  6692. var ranges = this.sel.ranges.slice(0);
  6693. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6694. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6695. }),
  6696. getSelection: function (lineSep) {
  6697. var ranges = this.sel.ranges, lines;
  6698. for (var i = 0; i < ranges.length; i++) {
  6699. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6700. lines = lines ? lines.concat(sel) : sel;
  6701. }
  6702. if (lineSep === false) return lines;
  6703. else return lines.join(lineSep || "\n");
  6704. },
  6705. getSelections: function (lineSep) {
  6706. var parts = [], ranges = this.sel.ranges;
  6707. for (var i = 0; i < ranges.length; i++) {
  6708. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6709. if (lineSep !== false) sel = sel.join(lineSep || "\n");
  6710. parts[i] = sel;
  6711. }
  6712. return parts;
  6713. },
  6714. replaceSelection: function (code, collapse, origin) {
  6715. var dup = [];
  6716. for (var i = 0; i < this.sel.ranges.length; i++)
  6717. dup[i] = code;
  6718. this.replaceSelections(dup, collapse, origin || "+input");
  6719. },
  6720. replaceSelections: docMethodOp(function (code, collapse, origin) {
  6721. var changes = [], sel = this.sel;
  6722. for (var i = 0; i < sel.ranges.length; i++) {
  6723. var range = sel.ranges[i];
  6724. changes[i] = { from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin };
  6725. }
  6726. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6727. for (var i = changes.length - 1; i >= 0; i--)
  6728. makeChange(this, changes[i]);
  6729. if (newSel) setSelectionReplaceHistory(this, newSel);
  6730. else if (this.cm) ensureCursorVisible(this.cm);
  6731. }),
  6732. undo: docMethodOp(function () { makeChangeFromHistory(this, "undo"); }),
  6733. redo: docMethodOp(function () { makeChangeFromHistory(this, "redo"); }),
  6734. undoSelection: docMethodOp(function () { makeChangeFromHistory(this, "undo", true); }),
  6735. redoSelection: docMethodOp(function () { makeChangeFromHistory(this, "redo", true); }),
  6736. setExtending: function (val) { this.extend = val; },
  6737. getExtending: function () { return this.extend; },
  6738. historySize: function () {
  6739. var hist = this.history, done = 0, undone = 0;
  6740. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges)++done;
  6741. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges)++undone;
  6742. return { undo: done, redo: undone };
  6743. },
  6744. clearHistory: function () { this.history = new History(this.history.maxGeneration); },
  6745. markClean: function () {
  6746. this.cleanGeneration = this.changeGeneration(true);
  6747. },
  6748. changeGeneration: function (forceSplit) {
  6749. if (forceSplit)
  6750. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6751. return this.history.generation;
  6752. },
  6753. isClean: function (gen) {
  6754. return this.history.generation == (gen || this.cleanGeneration);
  6755. },
  6756. getHistory: function () {
  6757. return {
  6758. done: copyHistoryArray(this.history.done),
  6759. undone: copyHistoryArray(this.history.undone)
  6760. };
  6761. },
  6762. setHistory: function (histData) {
  6763. var hist = this.history = new History(this.history.maxGeneration);
  6764. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6765. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6766. },
  6767. addLineClass: docMethodOp(function (handle, where, cls) {
  6768. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  6769. var prop = where == "text" ? "textClass"
  6770. : where == "background" ? "bgClass"
  6771. : where == "gutter" ? "gutterClass" : "wrapClass";
  6772. if (!line[prop]) line[prop] = cls;
  6773. else if (classTest(cls).test(line[prop])) return false;
  6774. else line[prop] += " " + cls;
  6775. return true;
  6776. });
  6777. }),
  6778. removeLineClass: docMethodOp(function (handle, where, cls) {
  6779. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  6780. var prop = where == "text" ? "textClass"
  6781. : where == "background" ? "bgClass"
  6782. : where == "gutter" ? "gutterClass" : "wrapClass";
  6783. var cur = line[prop];
  6784. if (!cur) return false;
  6785. else if (cls == null) line[prop] = null;
  6786. else {
  6787. var found = cur.match(classTest(cls));
  6788. if (!found) return false;
  6789. var end = found.index + found[0].length;
  6790. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6791. }
  6792. return true;
  6793. });
  6794. }),
  6795. addLineWidget: docMethodOp(function (handle, node, options) {
  6796. return addLineWidget(this, handle, node, options);
  6797. }),
  6798. removeLineWidget: function (widget) { widget.clear(); },
  6799. markText: function (from, to, options) {
  6800. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  6801. },
  6802. setBookmark: function (pos, options) {
  6803. var realOpts = {
  6804. replacedWith: options && (options.nodeType == null ? options.widget : options),
  6805. insertLeft: options && options.insertLeft,
  6806. clearWhenEmpty: false, shared: options && options.shared,
  6807. handleMouseEvents: options && options.handleMouseEvents
  6808. };
  6809. pos = clipPos(this, pos);
  6810. return markText(this, pos, pos, realOpts, "bookmark");
  6811. },
  6812. findMarksAt: function (pos) {
  6813. pos = clipPos(this, pos);
  6814. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6815. if (spans) for (var i = 0; i < spans.length; ++i) {
  6816. var span = spans[i];
  6817. if ((span.from == null || span.from <= pos.ch) &&
  6818. (span.to == null || span.to >= pos.ch))
  6819. markers.push(span.marker.parent || span.marker);
  6820. }
  6821. return markers;
  6822. },
  6823. findMarks: function (from, to, filter) {
  6824. from = clipPos(this, from); to = clipPos(this, to);
  6825. var found = [], lineNo = from.line;
  6826. this.iter(from.line, to.line + 1, function (line) {
  6827. var spans = line.markedSpans;
  6828. if (spans) for (var i = 0; i < spans.length; i++) {
  6829. var span = spans[i];
  6830. if (!(lineNo == from.line && from.ch > span.to ||
  6831. span.from == null && lineNo != from.line ||
  6832. lineNo == to.line && span.from > to.ch) &&
  6833. (!filter || filter(span.marker)))
  6834. found.push(span.marker.parent || span.marker);
  6835. }
  6836. ++lineNo;
  6837. });
  6838. return found;
  6839. },
  6840. getAllMarks: function () {
  6841. var markers = [];
  6842. this.iter(function (line) {
  6843. var sps = line.markedSpans;
  6844. if (sps) for (var i = 0; i < sps.length; ++i)
  6845. if (sps[i].from != null) markers.push(sps[i].marker);
  6846. });
  6847. return markers;
  6848. },
  6849. posFromIndex: function (off) {
  6850. var ch, lineNo = this.first;
  6851. this.iter(function (line) {
  6852. var sz = line.text.length + 1;
  6853. if (sz > off) { ch = off; return true; }
  6854. off -= sz;
  6855. ++lineNo;
  6856. });
  6857. return clipPos(this, Pos(lineNo, ch));
  6858. },
  6859. indexFromPos: function (coords) {
  6860. coords = clipPos(this, coords);
  6861. var index = coords.ch;
  6862. if (coords.line < this.first || coords.ch < 0) return 0;
  6863. this.iter(this.first, coords.line, function (line) {
  6864. index += line.text.length + 1;
  6865. });
  6866. return index;
  6867. },
  6868. copy: function (copyHistory) {
  6869. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  6870. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6871. doc.sel = this.sel;
  6872. doc.extend = false;
  6873. if (copyHistory) {
  6874. doc.history.undoDepth = this.history.undoDepth;
  6875. doc.setHistory(this.getHistory());
  6876. }
  6877. return doc;
  6878. },
  6879. linkedDoc: function (options) {
  6880. if (!options) options = {};
  6881. var from = this.first, to = this.first + this.size;
  6882. if (options.from != null && options.from > from) from = options.from;
  6883. if (options.to != null && options.to < to) to = options.to;
  6884. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  6885. if (options.sharedHist) copy.history = this.history;
  6886. (this.linked || (this.linked = [])).push({ doc: copy, sharedHist: options.sharedHist });
  6887. copy.linked = [{ doc: this, isParent: true, sharedHist: options.sharedHist }];
  6888. copySharedMarkers(copy, findSharedMarkers(this));
  6889. return copy;
  6890. },
  6891. unlinkDoc: function (other) {
  6892. if (other instanceof CodeMirror) other = other.doc;
  6893. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6894. var link = this.linked[i];
  6895. if (link.doc != other) continue;
  6896. this.linked.splice(i, 1);
  6897. other.unlinkDoc(this);
  6898. detachSharedMarkers(findSharedMarkers(this));
  6899. break;
  6900. }
  6901. // If the histories were shared, split them again
  6902. if (other.history == this.history) {
  6903. var splitIds = [other.id];
  6904. linkedDocs(other, function (doc) { splitIds.push(doc.id); }, true);
  6905. other.history = new History(null);
  6906. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6907. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6908. }
  6909. },
  6910. iterLinkedDocs: function (f) { linkedDocs(this, f); },
  6911. getMode: function () { return this.mode; },
  6912. getEditor: function () { return this.cm; }
  6913. });
  6914. // Public alias.
  6915. Doc.prototype.eachLine = Doc.prototype.iter;
  6916. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  6917. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  6918. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  6919. CodeMirror.prototype[prop] = (function (method) {
  6920. return function () { return method.apply(this.doc, arguments); };
  6921. })(Doc.prototype[prop]);
  6922. eventMixin(Doc);
  6923. // Call f for all linked documents.
  6924. function linkedDocs(doc, f, sharedHistOnly) {
  6925. function propagate(doc, skip, sharedHist) {
  6926. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  6927. var rel = doc.linked[i];
  6928. if (rel.doc == skip) continue;
  6929. var shared = sharedHist && rel.sharedHist;
  6930. if (sharedHistOnly && !shared) continue;
  6931. f(rel.doc, shared);
  6932. propagate(rel.doc, doc, shared);
  6933. }
  6934. }
  6935. propagate(doc, null, true);
  6936. }
  6937. // Attach a document to an editor.
  6938. function attachDoc(cm, doc) {
  6939. if (doc.cm) throw new Error("This document is already in use.");
  6940. cm.doc = doc;
  6941. doc.cm = cm;
  6942. estimateLineHeights(cm);
  6943. loadMode(cm);
  6944. if (!cm.options.lineWrapping) findMaxLine(cm);
  6945. cm.options.mode = doc.modeOption;
  6946. regChange(cm);
  6947. }
  6948. // LINE UTILITIES
  6949. // Find the line object corresponding to the given line number.
  6950. function getLine(doc, n) {
  6951. n -= doc.first;
  6952. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  6953. for (var chunk = doc; !chunk.lines;) {
  6954. for (var i = 0; ; ++i) {
  6955. var child = chunk.children[i], sz = child.chunkSize();
  6956. if (n < sz) { chunk = child; break; }
  6957. n -= sz;
  6958. }
  6959. }
  6960. return chunk.lines[n];
  6961. }
  6962. // Get the part of a document between two positions, as an array of
  6963. // strings.
  6964. function getBetween(doc, start, end) {
  6965. var out = [], n = start.line;
  6966. doc.iter(start.line, end.line + 1, function (line) {
  6967. var text = line.text;
  6968. if (n == end.line) text = text.slice(0, end.ch);
  6969. if (n == start.line) text = text.slice(start.ch);
  6970. out.push(text);
  6971. ++n;
  6972. });
  6973. return out;
  6974. }
  6975. // Get the lines between from and to, as array of strings.
  6976. function getLines(doc, from, to) {
  6977. var out = [];
  6978. doc.iter(from, to, function (line) { out.push(line.text); });
  6979. return out;
  6980. }
  6981. // Update the height of a line, propagating the height change
  6982. // upwards to parent nodes.
  6983. function updateLineHeight(line, height) {
  6984. var diff = height - line.height;
  6985. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  6986. }
  6987. // Given a line object, find its line number by walking up through
  6988. // its parent links.
  6989. function lineNo(line) {
  6990. if (line.parent == null) return null;
  6991. var cur = line.parent, no = indexOf(cur.lines, line);
  6992. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  6993. for (var i = 0; ; ++i) {
  6994. if (chunk.children[i] == cur) break;
  6995. no += chunk.children[i].chunkSize();
  6996. }
  6997. }
  6998. return no + cur.first;
  6999. }
  7000. // Find the line at the given vertical position, using the height
  7001. // information in the document tree.
  7002. function lineAtHeight(chunk, h) {
  7003. var n = chunk.first;
  7004. outer: do {
  7005. for (var i = 0; i < chunk.children.length; ++i) {
  7006. var child = chunk.children[i], ch = child.height;
  7007. if (h < ch) { chunk = child; continue outer; }
  7008. h -= ch;
  7009. n += child.chunkSize();
  7010. }
  7011. return n;
  7012. } while (!chunk.lines);
  7013. for (var i = 0; i < chunk.lines.length; ++i) {
  7014. var line = chunk.lines[i], lh = line.height;
  7015. if (h < lh) break;
  7016. h -= lh;
  7017. }
  7018. return n + i;
  7019. }
  7020. // Find the height above the given line.
  7021. function heightAtLine(lineObj) {
  7022. lineObj = visualLine(lineObj);
  7023. var h = 0, chunk = lineObj.parent;
  7024. for (var i = 0; i < chunk.lines.length; ++i) {
  7025. var line = chunk.lines[i];
  7026. if (line == lineObj) break;
  7027. else h += line.height;
  7028. }
  7029. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  7030. for (var i = 0; i < p.children.length; ++i) {
  7031. var cur = p.children[i];
  7032. if (cur == chunk) break;
  7033. else h += cur.height;
  7034. }
  7035. }
  7036. return h;
  7037. }
  7038. // Get the bidi ordering for the given line (and cache it). Returns
  7039. // false for lines that are fully left-to-right, and an array of
  7040. // BidiSpan objects otherwise.
  7041. function getOrder(line) {
  7042. var order = line.order;
  7043. if (order == null) order = line.order = bidiOrdering(line.text);
  7044. return order;
  7045. }
  7046. // HISTORY
  7047. function History(startGen) {
  7048. // Arrays of change events and selections. Doing something adds an
  7049. // event to done and clears undo. Undoing moves events from done
  7050. // to undone, redoing moves them in the other direction.
  7051. this.done = []; this.undone = [];
  7052. this.undoDepth = Infinity;
  7053. // Used to track when changes can be merged into a single undo
  7054. // event
  7055. this.lastModTime = this.lastSelTime = 0;
  7056. this.lastOp = this.lastSelOp = null;
  7057. this.lastOrigin = this.lastSelOrigin = null;
  7058. // Used by the isClean() method
  7059. this.generation = this.maxGeneration = startGen || 1;
  7060. }
  7061. // Create a history change event from an updateDoc-style change
  7062. // object.
  7063. function historyChangeFromChange(doc, change) {
  7064. var histChange = { from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to) };
  7065. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  7066. linkedDocs(doc, function (doc) { attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  7067. return histChange;
  7068. }
  7069. // Pop all selection events off the end of a history array. Stop at
  7070. // a change event.
  7071. function clearSelectionEvents(array) {
  7072. while (array.length) {
  7073. var last = lst(array);
  7074. if (last.ranges) array.pop();
  7075. else break;
  7076. }
  7077. }
  7078. // Find the top change event in the history. Pop off selection
  7079. // events that are in the way.
  7080. function lastChangeEvent(hist, force) {
  7081. if (force) {
  7082. clearSelectionEvents(hist.done);
  7083. return lst(hist.done);
  7084. } else if (hist.done.length && !lst(hist.done).ranges) {
  7085. return lst(hist.done);
  7086. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  7087. hist.done.pop();
  7088. return lst(hist.done);
  7089. }
  7090. }
  7091. // Register a change in the history. Merges changes that are within
  7092. // a single operation, ore are close together with an origin that
  7093. // allows merging (starting with "+") into a single event.
  7094. function addChangeToHistory(doc, change, selAfter, opId) {
  7095. var hist = doc.history;
  7096. hist.undone.length = 0;
  7097. var time = +new Date, cur;
  7098. if ((hist.lastOp == opId ||
  7099. hist.lastOrigin == change.origin && change.origin &&
  7100. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  7101. change.origin.charAt(0) == "*")) &&
  7102. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  7103. // Merge this change into the last event
  7104. var last = lst(cur.changes);
  7105. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  7106. // Optimized case for simple insertion -- don't want to add
  7107. // new changesets for every character typed
  7108. last.to = changeEnd(change);
  7109. } else {
  7110. // Add new sub-event
  7111. cur.changes.push(historyChangeFromChange(doc, change));
  7112. }
  7113. } else {
  7114. // Can not be merged, start a new event.
  7115. var before = lst(hist.done);
  7116. if (!before || !before.ranges)
  7117. pushSelectionToHistory(doc.sel, hist.done);
  7118. cur = {
  7119. changes: [historyChangeFromChange(doc, change)],
  7120. generation: hist.generation
  7121. };
  7122. hist.done.push(cur);
  7123. while (hist.done.length > hist.undoDepth) {
  7124. hist.done.shift();
  7125. if (!hist.done[0].ranges) hist.done.shift();
  7126. }
  7127. }
  7128. hist.done.push(selAfter);
  7129. hist.generation = ++hist.maxGeneration;
  7130. hist.lastModTime = hist.lastSelTime = time;
  7131. hist.lastOp = hist.lastSelOp = opId;
  7132. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7133. if (!last) signal(doc, "historyAdded");
  7134. }
  7135. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7136. var ch = origin.charAt(0);
  7137. return ch == "*" ||
  7138. ch == "+" &&
  7139. prev.ranges.length == sel.ranges.length &&
  7140. prev.somethingSelected() == sel.somethingSelected() &&
  7141. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7142. }
  7143. // Called whenever the selection changes, sets the new selection as
  7144. // the pending selection in the history, and pushes the old pending
  7145. // selection into the 'done' array when it was significantly
  7146. // different (in number of selected ranges, emptiness, or time).
  7147. function addSelectionToHistory(doc, sel, opId, options) {
  7148. var hist = doc.history, origin = options && options.origin;
  7149. // A new event is started when the previous origin does not match
  7150. // the current, or the origins don't allow matching. Origins
  7151. // starting with * are always merged, those starting with + are
  7152. // merged when similar and close together in time.
  7153. if (opId == hist.lastSelOp ||
  7154. (origin && hist.lastSelOrigin == origin &&
  7155. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7156. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7157. hist.done[hist.done.length - 1] = sel;
  7158. else
  7159. pushSelectionToHistory(sel, hist.done);
  7160. hist.lastSelTime = +new Date;
  7161. hist.lastSelOrigin = origin;
  7162. hist.lastSelOp = opId;
  7163. if (options && options.clearRedo !== false)
  7164. clearSelectionEvents(hist.undone);
  7165. }
  7166. function pushSelectionToHistory(sel, dest) {
  7167. var top = lst(dest);
  7168. if (!(top && top.ranges && top.equals(sel)))
  7169. dest.push(sel);
  7170. }
  7171. // Used to store marked span information in the history.
  7172. function attachLocalSpans(doc, change, from, to) {
  7173. var existing = change["spans_" + doc.id], n = 0;
  7174. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  7175. if (line.markedSpans)
  7176. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7177. ++n;
  7178. });
  7179. }
  7180. // When un/re-doing restores text containing marked spans, those
  7181. // that have been explicitly cleared should not be restored.
  7182. function removeClearedSpans(spans) {
  7183. if (!spans) return null;
  7184. for (var i = 0, out; i < spans.length; ++i) {
  7185. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7186. else if (out) out.push(spans[i]);
  7187. }
  7188. return !out ? spans : out.length ? out : null;
  7189. }
  7190. // Retrieve and filter the old marked spans stored in a change event.
  7191. function getOldSpans(doc, change) {
  7192. var found = change["spans_" + doc.id];
  7193. if (!found) return null;
  7194. for (var i = 0, nw = []; i < change.text.length; ++i)
  7195. nw.push(removeClearedSpans(found[i]));
  7196. return nw;
  7197. }
  7198. // Used both to provide a JSON-safe object in .getHistory, and, when
  7199. // detaching a document, to split the history in two
  7200. function copyHistoryArray(events, newGroup, instantiateSel) {
  7201. for (var i = 0, copy = []; i < events.length; ++i) {
  7202. var event = events[i];
  7203. if (event.ranges) {
  7204. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7205. continue;
  7206. }
  7207. var changes = event.changes, newChanges = [];
  7208. copy.push({ changes: newChanges });
  7209. for (var j = 0; j < changes.length; ++j) {
  7210. var change = changes[j], m;
  7211. newChanges.push({ from: change.from, to: change.to, text: change.text });
  7212. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7213. if (indexOf(newGroup, Number(m[1])) > -1) {
  7214. lst(newChanges)[prop] = change[prop];
  7215. delete change[prop];
  7216. }
  7217. }
  7218. }
  7219. }
  7220. return copy;
  7221. }
  7222. // Rebasing/resetting history to deal with externally-sourced changes
  7223. function rebaseHistSelSingle(pos, from, to, diff) {
  7224. if (to < pos.line) {
  7225. pos.line += diff;
  7226. } else if (from < pos.line) {
  7227. pos.line = from;
  7228. pos.ch = 0;
  7229. }
  7230. }
  7231. // Tries to rebase an array of history events given a change in the
  7232. // document. If the change touches the same lines as the event, the
  7233. // event, and everything 'behind' it, is discarded. If the change is
  7234. // before the event, the event's positions are updated. Uses a
  7235. // copy-on-write scheme for the positions, to avoid having to
  7236. // reallocate them all on every rebase, but also avoid problems with
  7237. // shared position objects being unsafely updated.
  7238. function rebaseHistArray(array, from, to, diff) {
  7239. for (var i = 0; i < array.length; ++i) {
  7240. var sub = array[i], ok = true;
  7241. if (sub.ranges) {
  7242. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7243. for (var j = 0; j < sub.ranges.length; j++) {
  7244. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7245. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7246. }
  7247. continue;
  7248. }
  7249. for (var j = 0; j < sub.changes.length; ++j) {
  7250. var cur = sub.changes[j];
  7251. if (to < cur.from.line) {
  7252. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7253. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7254. } else if (from <= cur.to.line) {
  7255. ok = false;
  7256. break;
  7257. }
  7258. }
  7259. if (!ok) {
  7260. array.splice(0, i + 1);
  7261. i = 0;
  7262. }
  7263. }
  7264. }
  7265. function rebaseHist(hist, change) {
  7266. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7267. rebaseHistArray(hist.done, from, to, diff);
  7268. rebaseHistArray(hist.undone, from, to, diff);
  7269. }
  7270. // EVENT UTILITIES
  7271. // Due to the fact that we still support jurassic IE versions, some
  7272. // compatibility wrappers are needed.
  7273. var e_preventDefault = CodeMirror.e_preventDefault = function (e) {
  7274. if (e.preventDefault) e.preventDefault();
  7275. else e.returnValue = false;
  7276. };
  7277. var e_stopPropagation = CodeMirror.e_stopPropagation = function (e) {
  7278. if (e.stopPropagation) e.stopPropagation();
  7279. else e.cancelBubble = true;
  7280. };
  7281. function e_defaultPrevented(e) {
  7282. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7283. }
  7284. var e_stop = CodeMirror.e_stop = function (e) { e_preventDefault(e); e_stopPropagation(e); };
  7285. function e_target(e) { return e.target || e.srcElement; }
  7286. function e_button(e) {
  7287. var b = e.which;
  7288. if (b == null) {
  7289. if (e.button & 1) b = 1;
  7290. else if (e.button & 2) b = 3;
  7291. else if (e.button & 4) b = 2;
  7292. }
  7293. if (mac && e.ctrlKey && b == 1) b = 3;
  7294. return b;
  7295. }
  7296. // EVENT HANDLING
  7297. // Lightweight event framework. on/off also work on DOM nodes,
  7298. // registering native DOM handlers.
  7299. var on = CodeMirror.on = function (emitter, type, f) {
  7300. if (emitter.addEventListener)
  7301. emitter.addEventListener(type, f, false);
  7302. else if (emitter.attachEvent)
  7303. emitter.attachEvent("on" + type, f);
  7304. else {
  7305. var map = emitter._handlers || (emitter._handlers = {});
  7306. var arr = map[type] || (map[type] = []);
  7307. arr.push(f);
  7308. }
  7309. };
  7310. var off = CodeMirror.off = function (emitter, type, f) {
  7311. if (emitter.removeEventListener)
  7312. emitter.removeEventListener(type, f, false);
  7313. else if (emitter.detachEvent)
  7314. emitter.detachEvent("on" + type, f);
  7315. else {
  7316. var arr = emitter._handlers && emitter._handlers[type];
  7317. if (!arr) return;
  7318. for (var i = 0; i < arr.length; ++i)
  7319. if (arr[i] == f) { arr.splice(i, 1); break; }
  7320. }
  7321. };
  7322. var signal = CodeMirror.signal = function (emitter, type /*, values...*/) {
  7323. var arr = emitter._handlers && emitter._handlers[type];
  7324. if (!arr) return;
  7325. var args = Array.prototype.slice.call(arguments, 2);
  7326. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  7327. };
  7328. var orphanDelayedCallbacks = null;
  7329. // Often, we want to signal events at a point where we are in the
  7330. // middle of some work, but don't want the handler to start calling
  7331. // other methods on the editor, which might be in an inconsistent
  7332. // state or simply not expect any other events to happen.
  7333. // signalLater looks whether there are any handlers, and schedules
  7334. // them to be executed when the last operation ends, or, if no
  7335. // operation is active, when a timeout fires.
  7336. function signalLater(emitter, type /*, values...*/) {
  7337. var arr = emitter._handlers && emitter._handlers[type];
  7338. if (!arr) return;
  7339. var args = Array.prototype.slice.call(arguments, 2), list;
  7340. if (operationGroup) {
  7341. list = operationGroup.delayedCallbacks;
  7342. } else if (orphanDelayedCallbacks) {
  7343. list = orphanDelayedCallbacks;
  7344. } else {
  7345. list = orphanDelayedCallbacks = [];
  7346. setTimeout(fireOrphanDelayed, 0);
  7347. }
  7348. function bnd(f) { return function () { f.apply(null, args); }; };
  7349. for (var i = 0; i < arr.length; ++i)
  7350. list.push(bnd(arr[i]));
  7351. }
  7352. function fireOrphanDelayed() {
  7353. var delayed = orphanDelayedCallbacks;
  7354. orphanDelayedCallbacks = null;
  7355. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7356. }
  7357. // The DOM events that CodeMirror handles can be overridden by
  7358. // registering a (non-DOM) handler on the editor for the event name,
  7359. // and preventDefault-ing the event in that handler.
  7360. function signalDOMEvent(cm, e, override) {
  7361. if (typeof e == "string")
  7362. e = { type: e, preventDefault: function () { this.defaultPrevented = true; } };
  7363. signal(cm, override || e.type, cm, e);
  7364. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7365. }
  7366. function signalCursorActivity(cm) {
  7367. var arr = cm._handlers && cm._handlers.cursorActivity;
  7368. if (!arr) return;
  7369. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7370. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7371. set.push(arr[i]);
  7372. }
  7373. function hasHandler(emitter, type) {
  7374. var arr = emitter._handlers && emitter._handlers[type];
  7375. return arr && arr.length > 0;
  7376. }
  7377. // Add on and off methods to a constructor's prototype, to make
  7378. // registering events on such objects more convenient.
  7379. function eventMixin(ctor) {
  7380. ctor.prototype.on = function (type, f) { on(this, type, f); };
  7381. ctor.prototype.off = function (type, f) { off(this, type, f); };
  7382. }
  7383. // MISC UTILITIES
  7384. // Number of pixels added to scroller and sizer to hide scrollbar
  7385. var scrollerGap = 30;
  7386. // Returned or thrown by various protocols to signal 'I'm not
  7387. // handling this'.
  7388. var Pass = CodeMirror.Pass = { toString: function () { return "CodeMirror.Pass"; } };
  7389. // Reused option objects for setSelection & friends
  7390. var sel_dontScroll = { scroll: false }, sel_mouse = { origin: "*mouse" }, sel_move = { origin: "+move" };
  7391. function Delayed() { this.id = null; }
  7392. Delayed.prototype.set = function (ms, f) {
  7393. clearTimeout(this.id);
  7394. this.id = setTimeout(f, ms);
  7395. };
  7396. // Counts the column offset in a string, taking tabs into account.
  7397. // Used mostly to find indentation.
  7398. var countColumn = CodeMirror.countColumn = function (string, end, tabSize, startIndex, startValue) {
  7399. if (end == null) {
  7400. end = string.search(/[^\s\u00a0]/);
  7401. if (end == -1) end = string.length;
  7402. }
  7403. for (var i = startIndex || 0, n = startValue || 0; ;) {
  7404. var nextTab = string.indexOf("\t", i);
  7405. if (nextTab < 0 || nextTab >= end)
  7406. return n + (end - i);
  7407. n += nextTab - i;
  7408. n += tabSize - (n % tabSize);
  7409. i = nextTab + 1;
  7410. }
  7411. };
  7412. // The inverse of countColumn -- find the offset that corresponds to
  7413. // a particular column.
  7414. function findColumn(string, goal, tabSize) {
  7415. for (var pos = 0, col = 0; ;) {
  7416. var nextTab = string.indexOf("\t", pos);
  7417. if (nextTab == -1) nextTab = string.length;
  7418. var skipped = nextTab - pos;
  7419. if (nextTab == string.length || col + skipped >= goal)
  7420. return pos + Math.min(skipped, goal - col);
  7421. col += nextTab - pos;
  7422. col += tabSize - (col % tabSize);
  7423. pos = nextTab + 1;
  7424. if (col >= goal) return pos;
  7425. }
  7426. }
  7427. var spaceStrs = [""];
  7428. function spaceStr(n) {
  7429. while (spaceStrs.length <= n)
  7430. spaceStrs.push(lst(spaceStrs) + " ");
  7431. return spaceStrs[n];
  7432. }
  7433. function lst(arr) { return arr[arr.length - 1]; }
  7434. var selectInput = function (node) { node.select(); };
  7435. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7436. selectInput = function (node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7437. else if (ie) // Suppress mysterious IE10 errors
  7438. selectInput = function (node) { try { node.select(); } catch (_e) { } };
  7439. function indexOf(array, elt) {
  7440. for (var i = 0; i < array.length; ++i)
  7441. if (array[i] == elt) return i;
  7442. return -1;
  7443. }
  7444. function map(array, f) {
  7445. var out = [];
  7446. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7447. return out;
  7448. }
  7449. function nothing() { }
  7450. function createObj(base, props) {
  7451. var inst;
  7452. if (Object.create) {
  7453. inst = Object.create(base);
  7454. } else {
  7455. nothing.prototype = base;
  7456. inst = new nothing();
  7457. }
  7458. if (props) copyObj(props, inst);
  7459. return inst;
  7460. };
  7461. function copyObj(obj, target, overwrite) {
  7462. if (!target) target = {};
  7463. for (var prop in obj)
  7464. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7465. target[prop] = obj[prop];
  7466. return target;
  7467. }
  7468. function bind(f) {
  7469. var args = Array.prototype.slice.call(arguments, 1);
  7470. return function () { return f.apply(null, args); };
  7471. }
  7472. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7473. var isWordCharBasic = CodeMirror.isWordChar = function (ch) {
  7474. return /\w/.test(ch) || ch > "\x80" &&
  7475. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7476. };
  7477. function isWordChar(ch, helper) {
  7478. if (!helper) return isWordCharBasic(ch);
  7479. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7480. return helper.test(ch);
  7481. }
  7482. function isEmpty(obj) {
  7483. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7484. return true;
  7485. }
  7486. // Extending unicode characters. A series of a non-extending char +
  7487. // any number of extending chars is treated as a single unit as far
  7488. // as editing and measuring is concerned. This is not fully correct,
  7489. // since some scripts/fonts/browsers also treat other configurations
  7490. // of code points as a group.
  7491. 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]/;
  7492. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7493. // DOM UTILITIES
  7494. function elt(tag, content, className, style) {
  7495. var e = document.createElement(tag);
  7496. if (className) e.className = className;
  7497. if (style) e.style.cssText = style;
  7498. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7499. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7500. return e;
  7501. }
  7502. var range;
  7503. if (document.createRange) range = function (node, start, end, endNode) {
  7504. var r = document.createRange();
  7505. r.setEnd(endNode || node, end);
  7506. r.setStart(node, start);
  7507. return r;
  7508. };
  7509. else range = function (node, start, end) {
  7510. var r = document.body.createTextRange();
  7511. try { r.moveToElementText(node.parentNode); }
  7512. catch (e) { return r; }
  7513. r.collapse(true);
  7514. r.moveEnd("character", end);
  7515. r.moveStart("character", start);
  7516. return r;
  7517. };
  7518. function removeChildren(e) {
  7519. for (var count = e.childNodes.length; count > 0; --count)
  7520. e.removeChild(e.firstChild);
  7521. return e;
  7522. }
  7523. function removeChildrenAndAdd(parent, e) {
  7524. return removeChildren(parent).appendChild(e);
  7525. }
  7526. var contains = CodeMirror.contains = function (parent, child) {
  7527. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7528. child = child.parentNode;
  7529. if (parent.contains)
  7530. return parent.contains(child);
  7531. do {
  7532. if (child.nodeType == 11) child = child.host;
  7533. if (child == parent) return true;
  7534. } while (child = child.parentNode);
  7535. };
  7536. function activeElt() { return document.activeElement; }
  7537. // Older versions of IE throws unspecified error when touching
  7538. // document.activeElement in some cases (during loading, in iframe)
  7539. if (ie && ie_version < 11) activeElt = function () {
  7540. try { return document.activeElement; }
  7541. catch (e) { return document.body; }
  7542. };
  7543. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7544. var rmClass = CodeMirror.rmClass = function (node, cls) {
  7545. var current = node.className;
  7546. var match = classTest(cls).exec(current);
  7547. if (match) {
  7548. var after = current.slice(match.index + match[0].length);
  7549. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7550. }
  7551. };
  7552. var addClass = CodeMirror.addClass = function (node, cls) {
  7553. var current = node.className;
  7554. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7555. };
  7556. function joinClasses(a, b) {
  7557. var as = a.split(" ");
  7558. for (var i = 0; i < as.length; i++)
  7559. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7560. return b;
  7561. }
  7562. // WINDOW-WIDE EVENTS
  7563. // These must be handled carefully, because naively registering a
  7564. // handler for each editor will cause the editors to never be
  7565. // garbage collected.
  7566. function forEachCodeMirror(f) {
  7567. if (!document.body.getElementsByClassName) return;
  7568. var byClass = document.body.getElementsByClassName("CodeMirror");
  7569. for (var i = 0; i < byClass.length; i++) {
  7570. var cm = byClass[i].CodeMirror;
  7571. if (cm) f(cm);
  7572. }
  7573. }
  7574. var globalsRegistered = false;
  7575. function ensureGlobalHandlers() {
  7576. if (globalsRegistered) return;
  7577. registerGlobalHandlers();
  7578. globalsRegistered = true;
  7579. }
  7580. function registerGlobalHandlers() {
  7581. // When the window resizes, we need to refresh active editors.
  7582. var resizeTimer;
  7583. on(window, "resize", function () {
  7584. if (resizeTimer == null) resizeTimer = setTimeout(function () {
  7585. resizeTimer = null;
  7586. forEachCodeMirror(onResize);
  7587. }, 100);
  7588. });
  7589. // When the window loses focus, we want to show the editor as blurred
  7590. on(window, "blur", function () {
  7591. forEachCodeMirror(onBlur);
  7592. });
  7593. }
  7594. // FEATURE DETECTION
  7595. // Detect drag-and-drop
  7596. var dragAndDrop = function () {
  7597. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7598. // couldn't get it to work yet.
  7599. if (ie && ie_version < 9) return false;
  7600. var div = elt('div');
  7601. return "draggable" in div || "dragDrop" in div;
  7602. }();
  7603. var zwspSupported;
  7604. function zeroWidthElement(measure) {
  7605. if (zwspSupported == null) {
  7606. var test = elt("span", "\u200b");
  7607. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7608. if (measure.firstChild.offsetHeight != 0)
  7609. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7610. }
  7611. var node = zwspSupported ? elt("span", "\u200b") :
  7612. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7613. node.setAttribute("cm-text", "");
  7614. return node;
  7615. }
  7616. // Feature-detect IE's crummy client rect reporting for bidi text
  7617. var badBidiRects;
  7618. function hasBadBidiRects(measure) {
  7619. if (badBidiRects != null) return badBidiRects;
  7620. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7621. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7622. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7623. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7624. return badBidiRects = (r1.right - r0.right < 3);
  7625. }
  7626. // See if "".split is the broken IE version, if so, provide an
  7627. // alternative way to split lines.
  7628. var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function (string) {
  7629. var pos = 0, result = [], l = string.length;
  7630. while (pos <= l) {
  7631. var nl = string.indexOf("\n", pos);
  7632. if (nl == -1) nl = string.length;
  7633. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7634. var rt = line.indexOf("\r");
  7635. if (rt != -1) {
  7636. result.push(line.slice(0, rt));
  7637. pos += rt + 1;
  7638. } else {
  7639. result.push(line);
  7640. pos = nl + 1;
  7641. }
  7642. }
  7643. return result;
  7644. } : function (string) { return string.split(/\r\n?|\n/); };
  7645. var hasSelection = window.getSelection ? function (te) {
  7646. try { return te.selectionStart != te.selectionEnd; }
  7647. catch (e) { return false; }
  7648. } : function (te) {
  7649. try { var range = te.ownerDocument.selection.createRange(); }
  7650. catch (e) { }
  7651. if (!range || range.parentElement() != te) return false;
  7652. return range.compareEndPoints("StartToEnd", range) != 0;
  7653. };
  7654. var hasCopyEvent = (function () {
  7655. var e = elt("div");
  7656. if ("oncopy" in e) return true;
  7657. e.setAttribute("oncopy", "return;");
  7658. return typeof e.oncopy == "function";
  7659. })();
  7660. var badZoomedRects = null;
  7661. function hasBadZoomedRects(measure) {
  7662. if (badZoomedRects != null) return badZoomedRects;
  7663. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7664. var normal = node.getBoundingClientRect();
  7665. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7666. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7667. }
  7668. // KEY NAMES
  7669. var keyNames = {
  7670. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7671. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7672. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7673. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
  7674. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7675. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7676. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7677. };
  7678. CodeMirror.keyNames = keyNames;
  7679. (function () {
  7680. // Number keys
  7681. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7682. // Alphabetic keys
  7683. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7684. // Function keys
  7685. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7686. })();
  7687. // BIDI HELPERS
  7688. function iterateBidiSections(order, from, to, f) {
  7689. if (!order) return f(from, to, "ltr");
  7690. var found = false;
  7691. for (var i = 0; i < order.length; ++i) {
  7692. var part = order[i];
  7693. if (part.from < to && part.to > from || from == to && part.to == from) {
  7694. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7695. found = true;
  7696. }
  7697. }
  7698. if (!found) f(from, to, "ltr");
  7699. }
  7700. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7701. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7702. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7703. function lineRight(line) {
  7704. var order = getOrder(line);
  7705. if (!order) return line.text.length;
  7706. return bidiRight(lst(order));
  7707. }
  7708. function lineStart(cm, lineN) {
  7709. var line = getLine(cm.doc, lineN);
  7710. var visual = visualLine(line);
  7711. if (visual != line) lineN = lineNo(visual);
  7712. var order = getOrder(visual);
  7713. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7714. return Pos(lineN, ch);
  7715. }
  7716. function lineEnd(cm, lineN) {
  7717. var merged, line = getLine(cm.doc, lineN);
  7718. while (merged = collapsedSpanAtEnd(line)) {
  7719. line = merged.find(1, true).line;
  7720. lineN = null;
  7721. }
  7722. var order = getOrder(line);
  7723. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7724. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7725. }
  7726. function lineStartSmart(cm, pos) {
  7727. var start = lineStart(cm, pos.line);
  7728. var line = getLine(cm.doc, start.line);
  7729. var order = getOrder(line);
  7730. if (!order || order[0].level == 0) {
  7731. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7732. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7733. return Pos(start.line, inWS ? 0 : firstNonWS);
  7734. }
  7735. return start;
  7736. }
  7737. function compareBidiLevel(order, a, b) {
  7738. var linedir = order[0].level;
  7739. if (a == linedir) return true;
  7740. if (b == linedir) return false;
  7741. return a < b;
  7742. }
  7743. var bidiOther;
  7744. function getBidiPartAt(order, pos) {
  7745. bidiOther = null;
  7746. for (var i = 0, found; i < order.length; ++i) {
  7747. var cur = order[i];
  7748. if (cur.from < pos && cur.to > pos) return i;
  7749. if ((cur.from == pos || cur.to == pos)) {
  7750. if (found == null) {
  7751. found = i;
  7752. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7753. if (cur.from != cur.to) bidiOther = found;
  7754. return i;
  7755. } else {
  7756. if (cur.from != cur.to) bidiOther = i;
  7757. return found;
  7758. }
  7759. }
  7760. }
  7761. return found;
  7762. }
  7763. function moveInLine(line, pos, dir, byUnit) {
  7764. if (!byUnit) return pos + dir;
  7765. do pos += dir;
  7766. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7767. return pos;
  7768. }
  7769. // This is needed in order to move 'visually' through bi-directional
  7770. // text -- i.e., pressing left should make the cursor go left, even
  7771. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7772. // LTR text touch each other. This often requires the cursor offset
  7773. // to move more than one unit, in order to visually move one unit.
  7774. function moveVisually(line, start, dir, byUnit) {
  7775. var bidi = getOrder(line);
  7776. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7777. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7778. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7779. for (; ;) {
  7780. if (target > part.from && target < part.to) return target;
  7781. if (target == part.from || target == part.to) {
  7782. if (getBidiPartAt(bidi, target) == pos) return target;
  7783. part = bidi[pos += dir];
  7784. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7785. } else {
  7786. part = bidi[pos += dir];
  7787. if (!part) return null;
  7788. if ((dir > 0) == part.level % 2)
  7789. target = moveInLine(line, part.to, -1, byUnit);
  7790. else
  7791. target = moveInLine(line, part.from, 1, byUnit);
  7792. }
  7793. }
  7794. }
  7795. function moveLogically(line, start, dir, byUnit) {
  7796. var target = start + dir;
  7797. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7798. return target < 0 || target > line.text.length ? null : target;
  7799. }
  7800. // Bidirectional ordering algorithm
  7801. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7802. // that this (partially) implements.
  7803. // One-char codes used for character types:
  7804. // L (L): Left-to-Right
  7805. // R (R): Right-to-Left
  7806. // r (AL): Right-to-Left Arabic
  7807. // 1 (EN): European Number
  7808. // + (ES): European Number Separator
  7809. // % (ET): European Number Terminator
  7810. // n (AN): Arabic Number
  7811. // , (CS): Common Number Separator
  7812. // m (NSM): Non-Spacing Mark
  7813. // b (BN): Boundary Neutral
  7814. // s (B): Paragraph Separator
  7815. // t (S): Segment Separator
  7816. // w (WS): Whitespace
  7817. // N (ON): Other Neutrals
  7818. // Returns null if characters are ordered as they appear
  7819. // (left-to-right), or an array of sections ({from, to, level}
  7820. // objects) in the order in which they occur visually.
  7821. var bidiOrdering = (function () {
  7822. // Character types for codepoints 0 to 0xff
  7823. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7824. // Character types for codepoints 0x600 to 0x6ff
  7825. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7826. function charType(code) {
  7827. if (code <= 0xf7) return lowTypes.charAt(code);
  7828. else if (0x590 <= code && code <= 0x5f4) return "R";
  7829. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7830. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7831. else if (0x2000 <= code && code <= 0x200b) return "w";
  7832. else if (code == 0x200c) return "b";
  7833. else return "L";
  7834. }
  7835. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7836. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7837. // Browsers seem to always treat the boundaries of block elements as being L.
  7838. var outerType = "L";
  7839. function BidiSpan(level, from, to) {
  7840. this.level = level;
  7841. this.from = from; this.to = to;
  7842. }
  7843. return function (str) {
  7844. if (!bidiRE.test(str)) return false;
  7845. var len = str.length, types = [];
  7846. for (var i = 0, type; i < len; ++i)
  7847. types.push(type = charType(str.charCodeAt(i)));
  7848. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7849. // change the type of the NSM to the type of the previous
  7850. // character. If the NSM is at the start of the level run, it will
  7851. // get the type of sor.
  7852. for (var i = 0, prev = outerType; i < len; ++i) {
  7853. var type = types[i];
  7854. if (type == "m") types[i] = prev;
  7855. else prev = type;
  7856. }
  7857. // W2. Search backwards from each instance of a European number
  7858. // until the first strong type (R, L, AL, or sor) is found. If an
  7859. // AL is found, change the type of the European number to Arabic
  7860. // number.
  7861. // W3. Change all ALs to R.
  7862. for (var i = 0, cur = outerType; i < len; ++i) {
  7863. var type = types[i];
  7864. if (type == "1" && cur == "r") types[i] = "n";
  7865. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7866. }
  7867. // W4. A single European separator between two European numbers
  7868. // changes to a European number. A single common separator between
  7869. // two numbers of the same type changes to that type.
  7870. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7871. var type = types[i];
  7872. if (type == "+" && prev == "1" && types[i + 1] == "1") types[i] = "1";
  7873. else if (type == "," && prev == types[i + 1] &&
  7874. (prev == "1" || prev == "n")) types[i] = prev;
  7875. prev = type;
  7876. }
  7877. // W5. A sequence of European terminators adjacent to European
  7878. // numbers changes to all European numbers.
  7879. // W6. Otherwise, separators and terminators change to Other
  7880. // Neutral.
  7881. for (var i = 0; i < len; ++i) {
  7882. var type = types[i];
  7883. if (type == ",") types[i] = "N";
  7884. else if (type == "%") {
  7885. for (var end = i + 1; end < len && types[end] == "%"; ++end) { }
  7886. var replace = (i && types[i - 1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7887. for (var j = i; j < end; ++j) types[j] = replace;
  7888. i = end - 1;
  7889. }
  7890. }
  7891. // W7. Search backwards from each instance of a European number
  7892. // until the first strong type (R, L, or sor) is found. If an L is
  7893. // found, then change the type of the European number to L.
  7894. for (var i = 0, cur = outerType; i < len; ++i) {
  7895. var type = types[i];
  7896. if (cur == "L" && type == "1") types[i] = "L";
  7897. else if (isStrong.test(type)) cur = type;
  7898. }
  7899. // N1. A sequence of neutrals takes the direction of the
  7900. // surrounding strong text if the text on both sides has the same
  7901. // direction. European and Arabic numbers act as if they were R in
  7902. // terms of their influence on neutrals. Start-of-level-run (sor)
  7903. // and end-of-level-run (eor) are used at level run boundaries.
  7904. // N2. Any remaining neutrals take the embedding direction.
  7905. for (var i = 0; i < len; ++i) {
  7906. if (isNeutral.test(types[i])) {
  7907. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) { }
  7908. var before = (i ? types[i - 1] : outerType) == "L";
  7909. var after = (end < len ? types[end] : outerType) == "L";
  7910. var replace = before || after ? "L" : "R";
  7911. for (var j = i; j < end; ++j) types[j] = replace;
  7912. i = end - 1;
  7913. }
  7914. }
  7915. // Here we depart from the documented algorithm, in order to avoid
  7916. // building up an actual levels array. Since there are only three
  7917. // levels (0, 1, 2) in an implementation that doesn't take
  7918. // explicit embedding into account, we can build up the order on
  7919. // the fly, without following the level-based algorithm.
  7920. var order = [], m;
  7921. for (var i = 0; i < len;) {
  7922. if (countsAsLeft.test(types[i])) {
  7923. var start = i;
  7924. for (++i; i < len && countsAsLeft.test(types[i]); ++i) { }
  7925. order.push(new BidiSpan(0, start, i));
  7926. } else {
  7927. var pos = i, at = order.length;
  7928. for (++i; i < len && types[i] != "L"; ++i) { }
  7929. for (var j = pos; j < i;) {
  7930. if (countsAsNum.test(types[j])) {
  7931. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  7932. var nstart = j;
  7933. for (++j; j < i && countsAsNum.test(types[j]); ++j) { }
  7934. order.splice(at, 0, new BidiSpan(2, nstart, j));
  7935. pos = j;
  7936. } else ++j;
  7937. }
  7938. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  7939. }
  7940. }
  7941. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  7942. order[0].from = m[0].length;
  7943. order.unshift(new BidiSpan(0, 0, m[0].length));
  7944. }
  7945. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  7946. lst(order).to -= m[0].length;
  7947. order.push(new BidiSpan(0, len - m[0].length, len));
  7948. }
  7949. if (order[0].level == 2)
  7950. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  7951. if (order[0].level != lst(order).level)
  7952. order.push(new BidiSpan(order[0].level, len, len));
  7953. return order;
  7954. };
  7955. })();
  7956. // THE END
  7957. CodeMirror.version = "5.3.0";
  7958. return CodeMirror;
  7959. });