codemirror.js 345 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function(mod) {
  9. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10. module.exports = mod();
  11. else if (typeof define == "function" && define.amd) // AMD
  12. return define([], mod);
  13. else // Plain browser env
  14. (this || window).CodeMirror = mod();
  15. })(function() {
  16. "use strict";
  17. // BROWSER SNIFFING
  18. // Kludges for bugs and behavior differences that can't be feature
  19. // detected are enabled based on userAgent etc sniffing.
  20. var userAgent = navigator.userAgent;
  21. var platform = navigator.platform;
  22. var gecko = /gecko\/\d/i.test(userAgent);
  23. var ie_upto10 = /MSIE \d/.test(userAgent);
  24. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  25. var ie = ie_upto10 || ie_11up;
  26. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  27. var webkit = /WebKit\//.test(userAgent);
  28. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  29. var chrome = /Chrome\//.test(userAgent);
  30. var presto = /Opera\//.test(userAgent);
  31. var safari = /Apple Computer/.test(navigator.vendor);
  32. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  33. var phantom = /PhantomJS/.test(userAgent);
  34. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  35. // This is woefully incomplete. Suggestions for alternative methods welcome.
  36. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  37. var mac = ios || /Mac/.test(platform);
  38. var chromeOS = /\bCrOS\b/.test(userAgent);
  39. var windows = /win/i.test(platform);
  40. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  41. if (presto_version) presto_version = Number(presto_version[1]);
  42. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  43. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  44. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  45. var captureRightClick = gecko || (ie && ie_version >= 9);
  46. // Optimize some code when these features are not used.
  47. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  48. // EDITOR CONSTRUCTOR
  49. // A CodeMirror instance represents an editor. This is the object
  50. // that user code is usually dealing with.
  51. function CodeMirror(place, options) {
  52. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  53. this.options = options = options ? copyObj(options) : {};
  54. // Determine effective options based on given values and defaults.
  55. copyObj(defaults, options, false);
  56. setGuttersForLineNumbers(options);
  57. var doc = options.value;
  58. if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
  59. this.doc = doc;
  60. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  61. var display = this.display = new Display(place, doc, input);
  62. display.wrapper.CodeMirror = this;
  63. updateGutters(this);
  64. themeChanged(this);
  65. if (options.lineWrapping)
  66. this.display.wrapper.className += " CodeMirror-wrap";
  67. if (options.autofocus && !mobile) display.input.focus();
  68. initScrollbars(this);
  69. this.state = {
  70. keyMaps: [], // stores maps added by addKeyMap
  71. overlays: [], // highlighting overlays, as added by addOverlay
  72. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  73. overwrite: false,
  74. delayingBlurEvent: false,
  75. focused: false,
  76. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  77. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  78. selectingText: false,
  79. draggingText: false,
  80. highlight: new Delayed(), // stores highlight worker timeout
  81. keySeq: null, // Unfinished key sequence
  82. specialChars: null
  83. };
  84. var cm = this;
  85. // Override magic textarea content restore that IE sometimes does
  86. // on our hidden textarea on reload
  87. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  88. registerEventHandlers(this);
  89. ensureGlobalHandlers();
  90. startOperation(this);
  91. this.curOp.forceUpdate = true;
  92. attachDoc(this, doc);
  93. if ((options.autofocus && !mobile) || cm.hasFocus())
  94. setTimeout(bind(onFocus, this), 20);
  95. else
  96. onBlur(this);
  97. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  98. optionHandlers[opt](this, options[opt], Init);
  99. maybeUpdateLineNumberWidth(this);
  100. if (options.finishInit) options.finishInit(this);
  101. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  102. endOperation(this);
  103. // Suppress optimizelegibility in Webkit, since it breaks text
  104. // measuring on line wrapping boundaries.
  105. if (webkit && options.lineWrapping &&
  106. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  107. display.lineDiv.style.textRendering = "auto";
  108. }
  109. // DISPLAY CONSTRUCTOR
  110. // The display handles the DOM integration, both for input reading
  111. // and content drawing. It holds references to DOM nodes and
  112. // display-related state.
  113. function Display(place, doc, input) {
  114. var d = this;
  115. this.input = input;
  116. // Covers bottom-right square when both scrollbars are present.
  117. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  118. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  119. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  120. // and h scrollbar is present.
  121. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  122. d.gutterFiller.setAttribute("cm-not-content", "true");
  123. // Will contain the actual code, positioned to cover the viewport.
  124. d.lineDiv = elt("div", null, "CodeMirror-code");
  125. // Elements are added to these to represent selection and cursors.
  126. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  127. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  128. // A visibility: hidden element used to find the size of things.
  129. d.measure = elt("div", null, "CodeMirror-measure");
  130. // When lines outside of the viewport are measured, they are drawn in this.
  131. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  132. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  133. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  134. null, "position: relative; outline: none");
  135. // Moved around its parent to cover visible view.
  136. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  137. // Set to the height of the document, allowing scrolling.
  138. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  139. d.sizerWidth = null;
  140. // Behavior of elts with overflow: auto and padding is
  141. // inconsistent across browsers. This is used to ensure the
  142. // scrollable area is big enough.
  143. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  144. // Will contain the gutters, if any.
  145. d.gutters = elt("div", null, "CodeMirror-gutters");
  146. d.lineGutter = null;
  147. // Actual scrollable element.
  148. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  149. d.scroller.setAttribute("tabIndex", "-1");
  150. // The element in which the editor lives.
  151. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  152. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  153. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  154. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  155. if (place) {
  156. if (place.appendChild) place.appendChild(d.wrapper);
  157. else place(d.wrapper);
  158. }
  159. // Current rendered range (may be bigger than the view window).
  160. d.viewFrom = d.viewTo = doc.first;
  161. d.reportedViewFrom = d.reportedViewTo = doc.first;
  162. // Information about the rendered lines.
  163. d.view = [];
  164. d.renderedView = null;
  165. // Holds info about a single rendered line when it was rendered
  166. // for measurement, while not in view.
  167. d.externalMeasured = null;
  168. // Empty space (in pixels) above the view
  169. d.viewOffset = 0;
  170. d.lastWrapHeight = d.lastWrapWidth = 0;
  171. d.updateLineNumbers = null;
  172. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  173. d.scrollbarsClipped = false;
  174. // Used to only resize the line number gutter when necessary (when
  175. // the amount of lines crosses a boundary that makes its width change)
  176. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  177. // Set to true when a non-horizontal-scrolling line widget is
  178. // added. As an optimization, line widget aligning is skipped when
  179. // this is false.
  180. d.alignWidgets = false;
  181. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  182. // Tracks the maximum line length so that the horizontal scrollbar
  183. // can be kept static when scrolling.
  184. d.maxLine = null;
  185. d.maxLineLength = 0;
  186. d.maxLineChanged = false;
  187. // Used for measuring wheel scrolling granularity
  188. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  189. // True when shift is held down.
  190. d.shift = false;
  191. // Used to track whether anything happened since the context menu
  192. // was opened.
  193. d.selForContextMenu = null;
  194. d.activeTouch = null;
  195. input.init(d);
  196. }
  197. // STATE UPDATES
  198. // Used to get the editor into a consistent state again when options change.
  199. function loadMode(cm) {
  200. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  201. resetModeState(cm);
  202. }
  203. function resetModeState(cm) {
  204. cm.doc.iter(function(line) {
  205. if (line.stateAfter) line.stateAfter = null;
  206. if (line.styles) line.styles = null;
  207. });
  208. cm.doc.frontier = cm.doc.first;
  209. startWorker(cm, 100);
  210. cm.state.modeGen++;
  211. if (cm.curOp) regChange(cm);
  212. }
  213. function wrappingChanged(cm) {
  214. if (cm.options.lineWrapping) {
  215. addClass(cm.display.wrapper, "CodeMirror-wrap");
  216. cm.display.sizer.style.minWidth = "";
  217. cm.display.sizerWidth = null;
  218. } else {
  219. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  220. findMaxLine(cm);
  221. }
  222. estimateLineHeights(cm);
  223. regChange(cm);
  224. clearCaches(cm);
  225. setTimeout(function(){updateScrollbars(cm);}, 100);
  226. }
  227. // Returns a function that estimates the height of a line, to use as
  228. // first approximation until the line becomes visible (and is thus
  229. // properly measurable).
  230. function estimateHeight(cm) {
  231. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  232. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  233. return function(line) {
  234. if (lineIsHidden(cm.doc, line)) return 0;
  235. var widgetsHeight = 0;
  236. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  237. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  238. }
  239. if (wrapping)
  240. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  241. else
  242. return widgetsHeight + th;
  243. };
  244. }
  245. function estimateLineHeights(cm) {
  246. var doc = cm.doc, est = estimateHeight(cm);
  247. doc.iter(function(line) {
  248. var estHeight = est(line);
  249. if (estHeight != line.height) updateLineHeight(line, estHeight);
  250. });
  251. }
  252. function themeChanged(cm) {
  253. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  254. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  255. clearCaches(cm);
  256. }
  257. function guttersChanged(cm) {
  258. updateGutters(cm);
  259. regChange(cm);
  260. setTimeout(function(){alignHorizontally(cm);}, 20);
  261. }
  262. // Rebuild the gutter elements, ensure the margin to the left of the
  263. // code matches their width.
  264. function updateGutters(cm) {
  265. var gutters = cm.display.gutters, specs = cm.options.gutters;
  266. removeChildren(gutters);
  267. for (var i = 0; i < specs.length; ++i) {
  268. var gutterClass = specs[i];
  269. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  270. if (gutterClass == "CodeMirror-linenumbers") {
  271. cm.display.lineGutter = gElt;
  272. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  273. }
  274. }
  275. gutters.style.display = i ? "" : "none";
  276. updateGutterSpace(cm);
  277. }
  278. function updateGutterSpace(cm) {
  279. var width = cm.display.gutters.offsetWidth;
  280. cm.display.sizer.style.marginLeft = width + "px";
  281. }
  282. // Compute the character length of a line, taking into account
  283. // collapsed ranges (see markText) that might hide parts, and join
  284. // other lines onto it.
  285. function lineLength(line) {
  286. if (line.height == 0) return 0;
  287. var len = line.text.length, merged, cur = line;
  288. while (merged = collapsedSpanAtStart(cur)) {
  289. var found = merged.find(0, true);
  290. cur = found.from.line;
  291. len += found.from.ch - found.to.ch;
  292. }
  293. cur = line;
  294. while (merged = collapsedSpanAtEnd(cur)) {
  295. var found = merged.find(0, true);
  296. len -= cur.text.length - found.from.ch;
  297. cur = found.to.line;
  298. len += cur.text.length - found.to.ch;
  299. }
  300. return len;
  301. }
  302. // Find the longest line in the document.
  303. function findMaxLine(cm) {
  304. var d = cm.display, doc = cm.doc;
  305. d.maxLine = getLine(doc, doc.first);
  306. d.maxLineLength = lineLength(d.maxLine);
  307. d.maxLineChanged = true;
  308. doc.iter(function(line) {
  309. var len = lineLength(line);
  310. if (len > d.maxLineLength) {
  311. d.maxLineLength = len;
  312. d.maxLine = line;
  313. }
  314. });
  315. }
  316. // Make sure the gutters options contains the element
  317. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  318. function setGuttersForLineNumbers(options) {
  319. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  320. if (found == -1 && options.lineNumbers) {
  321. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  322. } else if (found > -1 && !options.lineNumbers) {
  323. options.gutters = options.gutters.slice(0);
  324. options.gutters.splice(found, 1);
  325. }
  326. }
  327. // SCROLLBARS
  328. // Prepare DOM reads needed to update the scrollbars. Done in one
  329. // shot to minimize update/measure roundtrips.
  330. function measureForScrollbars(cm) {
  331. var d = cm.display, gutterW = d.gutters.offsetWidth;
  332. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  333. return {
  334. clientHeight: d.scroller.clientHeight,
  335. viewHeight: d.wrapper.clientHeight,
  336. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  337. viewWidth: d.wrapper.clientWidth,
  338. barLeft: cm.options.fixedGutter ? gutterW : 0,
  339. docHeight: docH,
  340. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  341. nativeBarWidth: d.nativeBarWidth,
  342. gutterWidth: gutterW
  343. };
  344. }
  345. function NativeScrollbars(place, scroll, cm) {
  346. this.cm = cm;
  347. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  348. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  349. place(vert); place(horiz);
  350. on(vert, "scroll", function() {
  351. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  352. });
  353. on(horiz, "scroll", function() {
  354. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  355. });
  356. this.checkedZeroWidth = false;
  357. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  358. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  359. }
  360. NativeScrollbars.prototype = copyObj({
  361. update: function(measure) {
  362. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  363. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  364. var sWidth = measure.nativeBarWidth;
  365. if (needsV) {
  366. this.vert.style.display = "block";
  367. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  368. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  369. // A bug in IE8 can cause this value to be negative, so guard it.
  370. this.vert.firstChild.style.height =
  371. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  372. } else {
  373. this.vert.style.display = "";
  374. this.vert.firstChild.style.height = "0";
  375. }
  376. if (needsH) {
  377. this.horiz.style.display = "block";
  378. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  379. this.horiz.style.left = measure.barLeft + "px";
  380. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  381. this.horiz.firstChild.style.width =
  382. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  383. } else {
  384. this.horiz.style.display = "";
  385. this.horiz.firstChild.style.width = "0";
  386. }
  387. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  388. if (sWidth == 0) this.zeroWidthHack();
  389. this.checkedZeroWidth = true;
  390. }
  391. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  392. },
  393. setScrollLeft: function(pos) {
  394. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  395. if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
  396. },
  397. setScrollTop: function(pos) {
  398. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  399. if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
  400. },
  401. zeroWidthHack: function() {
  402. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  403. this.horiz.style.height = this.vert.style.width = w;
  404. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  405. this.disableHoriz = new Delayed;
  406. this.disableVert = new Delayed;
  407. },
  408. enableZeroWidthBar: function(bar, delay) {
  409. bar.style.pointerEvents = "auto";
  410. function maybeDisable() {
  411. // To find out whether the scrollbar is still visible, we
  412. // check whether the element under the pixel in the bottom
  413. // left corner of the scrollbar box is the scrollbar box
  414. // itself (when the bar is still visible) or its filler child
  415. // (when the bar is hidden). If it is still visible, we keep
  416. // it enabled, if it's hidden, we disable pointer events.
  417. var box = bar.getBoundingClientRect();
  418. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
  419. if (elt != bar) bar.style.pointerEvents = "none";
  420. else delay.set(1000, maybeDisable);
  421. }
  422. delay.set(1000, maybeDisable);
  423. },
  424. clear: function() {
  425. var parent = this.horiz.parentNode;
  426. parent.removeChild(this.horiz);
  427. parent.removeChild(this.vert);
  428. }
  429. }, NativeScrollbars.prototype);
  430. function NullScrollbars() {}
  431. NullScrollbars.prototype = copyObj({
  432. update: function() { return {bottom: 0, right: 0}; },
  433. setScrollLeft: function() {},
  434. setScrollTop: function() {},
  435. clear: function() {}
  436. }, NullScrollbars.prototype);
  437. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  438. function initScrollbars(cm) {
  439. if (cm.display.scrollbars) {
  440. cm.display.scrollbars.clear();
  441. if (cm.display.scrollbars.addClass)
  442. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  443. }
  444. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  445. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  446. // Prevent clicks in the scrollbars from killing focus
  447. on(node, "mousedown", function() {
  448. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  449. });
  450. node.setAttribute("cm-not-content", "true");
  451. }, function(pos, axis) {
  452. if (axis == "horizontal") setScrollLeft(cm, pos);
  453. else setScrollTop(cm, pos);
  454. }, cm);
  455. if (cm.display.scrollbars.addClass)
  456. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  457. }
  458. function updateScrollbars(cm, measure) {
  459. if (!measure) measure = measureForScrollbars(cm);
  460. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  461. updateScrollbarsInner(cm, measure);
  462. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  463. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  464. updateHeightsInViewport(cm);
  465. updateScrollbarsInner(cm, measureForScrollbars(cm));
  466. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  467. }
  468. }
  469. // Re-synchronize the fake scrollbars with the actual size of the
  470. // content.
  471. function updateScrollbarsInner(cm, measure) {
  472. var d = cm.display;
  473. var sizes = d.scrollbars.update(measure);
  474. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  475. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  476. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  477. if (sizes.right && sizes.bottom) {
  478. d.scrollbarFiller.style.display = "block";
  479. d.scrollbarFiller.style.height = sizes.bottom + "px";
  480. d.scrollbarFiller.style.width = sizes.right + "px";
  481. } else d.scrollbarFiller.style.display = "";
  482. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  483. d.gutterFiller.style.display = "block";
  484. d.gutterFiller.style.height = sizes.bottom + "px";
  485. d.gutterFiller.style.width = measure.gutterWidth + "px";
  486. } else d.gutterFiller.style.display = "";
  487. }
  488. // Compute the lines that are visible in a given viewport (defaults
  489. // the the current scroll position). viewport may contain top,
  490. // height, and ensure (see op.scrollToPos) properties.
  491. function visibleLines(display, doc, viewport) {
  492. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  493. top = Math.floor(top - paddingTop(display));
  494. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  495. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  496. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  497. // forces those lines into the viewport (if possible).
  498. if (viewport && viewport.ensure) {
  499. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  500. if (ensureFrom < from) {
  501. from = ensureFrom;
  502. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  503. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  504. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  505. to = ensureTo;
  506. }
  507. }
  508. return {from: from, to: Math.max(to, from + 1)};
  509. }
  510. // LINE NUMBERS
  511. // Re-align line numbers and gutter marks to compensate for
  512. // horizontal scrolling.
  513. function alignHorizontally(cm) {
  514. var display = cm.display, view = display.view;
  515. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  516. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  517. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  518. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  519. if (cm.options.fixedGutter && view[i].gutter)
  520. view[i].gutter.style.left = left;
  521. var align = view[i].alignable;
  522. if (align) for (var j = 0; j < align.length; j++)
  523. align[j].style.left = left;
  524. }
  525. if (cm.options.fixedGutter)
  526. display.gutters.style.left = (comp + gutterW) + "px";
  527. }
  528. // Used to ensure that the line number gutter is still the right
  529. // size for the current document size. Returns true when an update
  530. // is needed.
  531. function maybeUpdateLineNumberWidth(cm) {
  532. if (!cm.options.lineNumbers) return false;
  533. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  534. if (last.length != display.lineNumChars) {
  535. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  536. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  537. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  538. display.lineGutter.style.width = "";
  539. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  540. display.lineNumWidth = display.lineNumInnerWidth + padding;
  541. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  542. display.lineGutter.style.width = display.lineNumWidth + "px";
  543. updateGutterSpace(cm);
  544. return true;
  545. }
  546. return false;
  547. }
  548. function lineNumberFor(options, i) {
  549. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  550. }
  551. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  552. // but using getBoundingClientRect to get a sub-pixel-accurate
  553. // result.
  554. function compensateForHScroll(display) {
  555. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  556. }
  557. // DISPLAY DRAWING
  558. function DisplayUpdate(cm, viewport, force) {
  559. var display = cm.display;
  560. this.viewport = viewport;
  561. // Store some values that we'll need later (but don't want to force a relayout for)
  562. this.visible = visibleLines(display, cm.doc, viewport);
  563. this.editorIsHidden = !display.wrapper.offsetWidth;
  564. this.wrapperHeight = display.wrapper.clientHeight;
  565. this.wrapperWidth = display.wrapper.clientWidth;
  566. this.oldDisplayWidth = displayWidth(cm);
  567. this.force = force;
  568. this.dims = getDimensions(cm);
  569. this.events = [];
  570. }
  571. DisplayUpdate.prototype.signal = function(emitter, type) {
  572. if (hasHandler(emitter, type))
  573. this.events.push(arguments);
  574. };
  575. DisplayUpdate.prototype.finish = function() {
  576. for (var i = 0; i < this.events.length; i++)
  577. signal.apply(null, this.events[i]);
  578. };
  579. function maybeClipScrollbars(cm) {
  580. var display = cm.display;
  581. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  582. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  583. display.heightForcer.style.height = scrollGap(cm) + "px";
  584. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  585. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  586. display.scrollbarsClipped = true;
  587. }
  588. }
  589. // Does the actual updating of the line display. Bails out
  590. // (returning false) when there is nothing to be done and forced is
  591. // false.
  592. function updateDisplayIfNeeded(cm, update) {
  593. var display = cm.display, doc = cm.doc;
  594. if (update.editorIsHidden) {
  595. resetView(cm);
  596. return false;
  597. }
  598. // Bail out if the visible area is already rendered and nothing changed.
  599. if (!update.force &&
  600. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  601. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  602. display.renderedView == display.view && countDirtyView(cm) == 0)
  603. return false;
  604. if (maybeUpdateLineNumberWidth(cm)) {
  605. resetView(cm);
  606. update.dims = getDimensions(cm);
  607. }
  608. // Compute a suitable new viewport (from & to)
  609. var end = doc.first + doc.size;
  610. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  611. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  612. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  613. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  614. if (sawCollapsedSpans) {
  615. from = visualLineNo(cm.doc, from);
  616. to = visualLineEndNo(cm.doc, to);
  617. }
  618. var different = from != display.viewFrom || to != display.viewTo ||
  619. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  620. adjustView(cm, from, to);
  621. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  622. // Position the mover div to align with the current scroll position
  623. cm.display.mover.style.top = display.viewOffset + "px";
  624. var toUpdate = countDirtyView(cm);
  625. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  626. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  627. return false;
  628. // For big changes, we hide the enclosing element during the
  629. // update, since that speeds up the operations on most browsers.
  630. var focused = activeElt();
  631. if (toUpdate > 4) display.lineDiv.style.display = "none";
  632. patchDisplay(cm, display.updateLineNumbers, update.dims);
  633. if (toUpdate > 4) display.lineDiv.style.display = "";
  634. display.renderedView = display.view;
  635. // There might have been a widget with a focused element that got
  636. // hidden or updated, if so re-focus it.
  637. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  638. // Prevent selection and cursors from interfering with the scroll
  639. // width and height.
  640. removeChildren(display.cursorDiv);
  641. removeChildren(display.selectionDiv);
  642. display.gutters.style.height = display.sizer.style.minHeight = 0;
  643. if (different) {
  644. display.lastWrapHeight = update.wrapperHeight;
  645. display.lastWrapWidth = update.wrapperWidth;
  646. startWorker(cm, 400);
  647. }
  648. display.updateLineNumbers = null;
  649. return true;
  650. }
  651. function postUpdateDisplay(cm, update) {
  652. var viewport = update.viewport;
  653. for (var first = true;; first = false) {
  654. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  655. // Clip forced viewport to actual scrollable area.
  656. if (viewport && viewport.top != null)
  657. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  658. // Updated line heights might result in the drawn area not
  659. // actually covering the viewport. Keep looping until it does.
  660. update.visible = visibleLines(cm.display, cm.doc, viewport);
  661. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  662. break;
  663. }
  664. if (!updateDisplayIfNeeded(cm, update)) break;
  665. updateHeightsInViewport(cm);
  666. var barMeasure = measureForScrollbars(cm);
  667. updateSelection(cm);
  668. updateScrollbars(cm, barMeasure);
  669. setDocumentHeight(cm, barMeasure);
  670. }
  671. update.signal(cm, "update", cm);
  672. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  673. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  674. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  675. }
  676. }
  677. function updateDisplaySimple(cm, viewport) {
  678. var update = new DisplayUpdate(cm, viewport);
  679. if (updateDisplayIfNeeded(cm, update)) {
  680. updateHeightsInViewport(cm);
  681. postUpdateDisplay(cm, update);
  682. var barMeasure = measureForScrollbars(cm);
  683. updateSelection(cm);
  684. updateScrollbars(cm, barMeasure);
  685. setDocumentHeight(cm, barMeasure);
  686. update.finish();
  687. }
  688. }
  689. function setDocumentHeight(cm, measure) {
  690. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  691. cm.display.heightForcer.style.top = measure.docHeight + "px";
  692. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  693. }
  694. // Read the actual heights of the rendered lines, and update their
  695. // stored heights to match.
  696. function updateHeightsInViewport(cm) {
  697. var display = cm.display;
  698. var prevBottom = display.lineDiv.offsetTop;
  699. for (var i = 0; i < display.view.length; i++) {
  700. var cur = display.view[i], height;
  701. if (cur.hidden) continue;
  702. if (ie && ie_version < 8) {
  703. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  704. height = bot - prevBottom;
  705. prevBottom = bot;
  706. } else {
  707. var box = cur.node.getBoundingClientRect();
  708. height = box.bottom - box.top;
  709. }
  710. var diff = cur.line.height - height;
  711. if (height < 2) height = textHeight(display);
  712. if (diff > .001 || diff < -.001) {
  713. updateLineHeight(cur.line, height);
  714. updateWidgetHeight(cur.line);
  715. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  716. updateWidgetHeight(cur.rest[j]);
  717. }
  718. }
  719. }
  720. // Read and store the height of line widgets associated with the
  721. // given line.
  722. function updateWidgetHeight(line) {
  723. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  724. line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
  725. }
  726. // Do a bulk-read of the DOM positions and sizes needed to draw the
  727. // view, so that we don't interleave reading and writing to the DOM.
  728. function getDimensions(cm) {
  729. var d = cm.display, left = {}, width = {};
  730. var gutterLeft = d.gutters.clientLeft;
  731. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  732. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  733. width[cm.options.gutters[i]] = n.clientWidth;
  734. }
  735. return {fixedPos: compensateForHScroll(d),
  736. gutterTotalWidth: d.gutters.offsetWidth,
  737. gutterLeft: left,
  738. gutterWidth: width,
  739. wrapperWidth: d.wrapper.clientWidth};
  740. }
  741. // Sync the actual display DOM structure with display.view, removing
  742. // nodes for lines that are no longer in view, and creating the ones
  743. // that are not there yet, and updating the ones that are out of
  744. // date.
  745. function patchDisplay(cm, updateNumbersFrom, dims) {
  746. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  747. var container = display.lineDiv, cur = container.firstChild;
  748. function rm(node) {
  749. var next = node.nextSibling;
  750. // Works around a throw-scroll bug in OS X Webkit
  751. if (webkit && mac && cm.display.currentWheelTarget == node)
  752. node.style.display = "none";
  753. else
  754. node.parentNode.removeChild(node);
  755. return next;
  756. }
  757. var view = display.view, lineN = display.viewFrom;
  758. // Loop over the elements in the view, syncing cur (the DOM nodes
  759. // in display.lineDiv) with the view as we go.
  760. for (var i = 0; i < view.length; i++) {
  761. var lineView = view[i];
  762. if (lineView.hidden) {
  763. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  764. var node = buildLineElement(cm, lineView, lineN, dims);
  765. container.insertBefore(node, cur);
  766. } else { // Already drawn
  767. while (cur != lineView.node) cur = rm(cur);
  768. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  769. updateNumbersFrom <= lineN && lineView.lineNumber;
  770. if (lineView.changes) {
  771. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  772. updateLineForChanges(cm, lineView, lineN, dims);
  773. }
  774. if (updateNumber) {
  775. removeChildren(lineView.lineNumber);
  776. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  777. }
  778. cur = lineView.node.nextSibling;
  779. }
  780. lineN += lineView.size;
  781. }
  782. while (cur) cur = rm(cur);
  783. }
  784. // When an aspect of a line changes, a string is added to
  785. // lineView.changes. This updates the relevant part of the line's
  786. // DOM structure.
  787. function updateLineForChanges(cm, lineView, lineN, dims) {
  788. for (var j = 0; j < lineView.changes.length; j++) {
  789. var type = lineView.changes[j];
  790. if (type == "text") updateLineText(cm, lineView);
  791. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  792. else if (type == "class") updateLineClasses(lineView);
  793. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  794. }
  795. lineView.changes = null;
  796. }
  797. // Lines with gutter elements, widgets or a background class need to
  798. // be wrapped, and have the extra elements added to the wrapper div
  799. function ensureLineWrapped(lineView) {
  800. if (lineView.node == lineView.text) {
  801. lineView.node = elt("div", null, null, "position: relative");
  802. if (lineView.text.parentNode)
  803. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  804. lineView.node.appendChild(lineView.text);
  805. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  806. }
  807. return lineView.node;
  808. }
  809. function updateLineBackground(lineView) {
  810. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  811. if (cls) cls += " CodeMirror-linebackground";
  812. if (lineView.background) {
  813. if (cls) lineView.background.className = cls;
  814. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  815. } else if (cls) {
  816. var wrap = ensureLineWrapped(lineView);
  817. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  818. }
  819. }
  820. // Wrapper around buildLineContent which will reuse the structure
  821. // in display.externalMeasured when possible.
  822. function getLineContent(cm, lineView) {
  823. var ext = cm.display.externalMeasured;
  824. if (ext && ext.line == lineView.line) {
  825. cm.display.externalMeasured = null;
  826. lineView.measure = ext.measure;
  827. return ext.built;
  828. }
  829. return buildLineContent(cm, lineView);
  830. }
  831. // Redraw the line's text. Interacts with the background and text
  832. // classes because the mode may output tokens that influence these
  833. // classes.
  834. function updateLineText(cm, lineView) {
  835. var cls = lineView.text.className;
  836. var built = getLineContent(cm, lineView);
  837. if (lineView.text == lineView.node) lineView.node = built.pre;
  838. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  839. lineView.text = built.pre;
  840. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  841. lineView.bgClass = built.bgClass;
  842. lineView.textClass = built.textClass;
  843. updateLineClasses(lineView);
  844. } else if (cls) {
  845. lineView.text.className = cls;
  846. }
  847. }
  848. function updateLineClasses(lineView) {
  849. updateLineBackground(lineView);
  850. if (lineView.line.wrapClass)
  851. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  852. else if (lineView.node != lineView.text)
  853. lineView.node.className = "";
  854. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  855. lineView.text.className = textClass || "";
  856. }
  857. function updateLineGutter(cm, lineView, lineN, dims) {
  858. if (lineView.gutter) {
  859. lineView.node.removeChild(lineView.gutter);
  860. lineView.gutter = null;
  861. }
  862. if (lineView.gutterBackground) {
  863. lineView.node.removeChild(lineView.gutterBackground);
  864. lineView.gutterBackground = null;
  865. }
  866. if (lineView.line.gutterClass) {
  867. var wrap = ensureLineWrapped(lineView);
  868. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  869. "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  870. "px; width: " + dims.gutterTotalWidth + "px");
  871. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  872. }
  873. var markers = lineView.line.gutterMarkers;
  874. if (cm.options.lineNumbers || markers) {
  875. var wrap = ensureLineWrapped(lineView);
  876. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  877. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
  878. cm.display.input.setUneditable(gutterWrap);
  879. wrap.insertBefore(gutterWrap, lineView.text);
  880. if (lineView.line.gutterClass)
  881. gutterWrap.className += " " + lineView.line.gutterClass;
  882. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  883. lineView.lineNumber = gutterWrap.appendChild(
  884. elt("div", lineNumberFor(cm.options, lineN),
  885. "CodeMirror-linenumber CodeMirror-gutter-elt",
  886. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  887. + cm.display.lineNumInnerWidth + "px"));
  888. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  889. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  890. if (found)
  891. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  892. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  893. }
  894. }
  895. }
  896. function updateLineWidgets(cm, lineView, dims) {
  897. if (lineView.alignable) lineView.alignable = null;
  898. for (var node = lineView.node.firstChild, next; node; node = next) {
  899. var next = node.nextSibling;
  900. if (node.className == "CodeMirror-linewidget")
  901. lineView.node.removeChild(node);
  902. }
  903. insertLineWidgets(cm, lineView, dims);
  904. }
  905. // Build a line's DOM representation from scratch
  906. function buildLineElement(cm, lineView, lineN, dims) {
  907. var built = getLineContent(cm, lineView);
  908. lineView.text = lineView.node = built.pre;
  909. if (built.bgClass) lineView.bgClass = built.bgClass;
  910. if (built.textClass) lineView.textClass = built.textClass;
  911. updateLineClasses(lineView);
  912. updateLineGutter(cm, lineView, lineN, dims);
  913. insertLineWidgets(cm, lineView, dims);
  914. return lineView.node;
  915. }
  916. // A lineView may contain multiple logical lines (when merged by
  917. // collapsed spans). The widgets for all of them need to be drawn.
  918. function insertLineWidgets(cm, lineView, dims) {
  919. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  920. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  921. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  922. }
  923. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  924. if (!line.widgets) return;
  925. var wrap = ensureLineWrapped(lineView);
  926. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  927. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  928. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  929. positionLineWidget(widget, node, lineView, dims);
  930. cm.display.input.setUneditable(node);
  931. if (allowAbove && widget.above)
  932. wrap.insertBefore(node, lineView.gutter || lineView.text);
  933. else
  934. wrap.appendChild(node);
  935. signalLater(widget, "redraw");
  936. }
  937. }
  938. function positionLineWidget(widget, node, lineView, dims) {
  939. if (widget.noHScroll) {
  940. (lineView.alignable || (lineView.alignable = [])).push(node);
  941. var width = dims.wrapperWidth;
  942. node.style.left = dims.fixedPos + "px";
  943. if (!widget.coverGutter) {
  944. width -= dims.gutterTotalWidth;
  945. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  946. }
  947. node.style.width = width + "px";
  948. }
  949. if (widget.coverGutter) {
  950. node.style.zIndex = 5;
  951. node.style.position = "relative";
  952. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  953. }
  954. }
  955. // POSITION OBJECT
  956. // A Pos instance represents a position within the text.
  957. var Pos = CodeMirror.Pos = function(line, ch) {
  958. if (!(this instanceof Pos)) return new Pos(line, ch);
  959. this.line = line; this.ch = ch;
  960. };
  961. // Compare two positions, return 0 if they are the same, a negative
  962. // number when a is less, and a positive number otherwise.
  963. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  964. function copyPos(x) {return Pos(x.line, x.ch);}
  965. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  966. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  967. // INPUT HANDLING
  968. function ensureFocus(cm) {
  969. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  970. }
  971. // This will be set to an array of strings when copying, so that,
  972. // when pasting, we know what kind of selections the copied text
  973. // was made out of.
  974. var lastCopied = null;
  975. function applyTextInput(cm, inserted, deleted, sel, origin) {
  976. var doc = cm.doc;
  977. cm.display.shift = false;
  978. if (!sel) sel = doc.sel;
  979. var paste = cm.state.pasteIncoming || origin == "paste";
  980. var textLines = doc.splitLines(inserted), multiPaste = null;
  981. // When pasing N lines into N selections, insert one line per selection
  982. if (paste && sel.ranges.length > 1) {
  983. if (lastCopied && lastCopied.join("\n") == inserted) {
  984. if (sel.ranges.length % lastCopied.length == 0) {
  985. multiPaste = [];
  986. for (var i = 0; i < lastCopied.length; i++)
  987. multiPaste.push(doc.splitLines(lastCopied[i]));
  988. }
  989. } else if (textLines.length == sel.ranges.length) {
  990. multiPaste = map(textLines, function(l) { return [l]; });
  991. }
  992. }
  993. // Normal behavior is to insert the new text into every selection
  994. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  995. var range = sel.ranges[i];
  996. var from = range.from(), to = range.to();
  997. if (range.empty()) {
  998. if (deleted && deleted > 0) // Handle deletion
  999. from = Pos(from.line, from.ch - deleted);
  1000. else if (cm.state.overwrite && !paste) // Handle overwrite
  1001. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  1002. }
  1003. var updateInput = cm.curOp.updateInput;
  1004. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  1005. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  1006. makeChange(cm.doc, changeEvent);
  1007. signalLater(cm, "inputRead", cm, changeEvent);
  1008. }
  1009. if (inserted && !paste)
  1010. triggerElectric(cm, inserted);
  1011. ensureCursorVisible(cm);
  1012. cm.curOp.updateInput = updateInput;
  1013. cm.curOp.typing = true;
  1014. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  1015. }
  1016. function handlePaste(e, cm) {
  1017. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1018. if (pasted) {
  1019. e.preventDefault();
  1020. if (!cm.isReadOnly() && !cm.options.disableInput)
  1021. runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
  1022. return true;
  1023. }
  1024. }
  1025. function triggerElectric(cm, inserted) {
  1026. // When an 'electric' character is inserted, immediately trigger a reindent
  1027. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  1028. var sel = cm.doc.sel;
  1029. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  1030. var range = sel.ranges[i];
  1031. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  1032. var mode = cm.getModeAt(range.head);
  1033. var indented = false;
  1034. if (mode.electricChars) {
  1035. for (var j = 0; j < mode.electricChars.length; j++)
  1036. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  1037. indented = indentLine(cm, range.head.line, "smart");
  1038. break;
  1039. }
  1040. } else if (mode.electricInput) {
  1041. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  1042. indented = indentLine(cm, range.head.line, "smart");
  1043. }
  1044. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  1045. }
  1046. }
  1047. function copyableRanges(cm) {
  1048. var text = [], ranges = [];
  1049. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1050. var line = cm.doc.sel.ranges[i].head.line;
  1051. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  1052. ranges.push(lineRange);
  1053. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1054. }
  1055. return {text: text, ranges: ranges};
  1056. }
  1057. function disableBrowserMagic(field) {
  1058. field.setAttribute("autocorrect", "off");
  1059. field.setAttribute("autocapitalize", "off");
  1060. field.setAttribute("spellcheck", "false");
  1061. }
  1062. // TEXTAREA INPUT STYLE
  1063. function TextareaInput(cm) {
  1064. this.cm = cm;
  1065. // See input.poll and input.reset
  1066. this.prevInput = "";
  1067. // Flag that indicates whether we expect input to appear real soon
  1068. // now (after some event like 'keypress' or 'input') and are
  1069. // polling intensively.
  1070. this.pollingFast = false;
  1071. // Self-resetting timeout for the poller
  1072. this.polling = new Delayed();
  1073. // Tracks when input.reset has punted to just putting a short
  1074. // string into the textarea instead of the full selection.
  1075. this.inaccurateSelection = false;
  1076. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1077. this.hasSelection = false;
  1078. this.composing = null;
  1079. };
  1080. function hiddenTextarea() {
  1081. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  1082. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1083. // The textarea is kept positioned near the cursor to prevent the
  1084. // fact that it'll be scrolled into view on input from scrolling
  1085. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1086. // very slow. So make the area wide instead.
  1087. if (webkit) te.style.width = "1000px";
  1088. else te.setAttribute("wrap", "off");
  1089. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1090. if (ios) te.style.border = "1px solid black";
  1091. disableBrowserMagic(te);
  1092. return div;
  1093. }
  1094. TextareaInput.prototype = copyObj({
  1095. init: function(display) {
  1096. var input = this, cm = this.cm;
  1097. // Wraps and hides input textarea
  1098. var div = this.wrapper = hiddenTextarea();
  1099. // The semihidden textarea that is focused when the editor is
  1100. // focused, and receives input.
  1101. var te = this.textarea = div.firstChild;
  1102. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1103. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1104. if (ios) te.style.width = "0px";
  1105. on(te, "input", function() {
  1106. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1107. input.poll();
  1108. });
  1109. on(te, "paste", function(e) {
  1110. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  1111. cm.state.pasteIncoming = true;
  1112. input.fastPoll();
  1113. });
  1114. function prepareCopyCut(e) {
  1115. if (signalDOMEvent(cm, e)) return
  1116. if (cm.somethingSelected()) {
  1117. lastCopied = cm.getSelections();
  1118. if (input.inaccurateSelection) {
  1119. input.prevInput = "";
  1120. input.inaccurateSelection = false;
  1121. te.value = lastCopied.join("\n");
  1122. selectInput(te);
  1123. }
  1124. } else if (!cm.options.lineWiseCopyCut) {
  1125. return;
  1126. } else {
  1127. var ranges = copyableRanges(cm);
  1128. lastCopied = ranges.text;
  1129. if (e.type == "cut") {
  1130. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1131. } else {
  1132. input.prevInput = "";
  1133. te.value = ranges.text.join("\n");
  1134. selectInput(te);
  1135. }
  1136. }
  1137. if (e.type == "cut") cm.state.cutIncoming = true;
  1138. }
  1139. on(te, "cut", prepareCopyCut);
  1140. on(te, "copy", prepareCopyCut);
  1141. on(display.scroller, "paste", function(e) {
  1142. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
  1143. cm.state.pasteIncoming = true;
  1144. input.focus();
  1145. });
  1146. // Prevent normal selection in the editor (we handle our own)
  1147. on(display.lineSpace, "selectstart", function(e) {
  1148. if (!eventInWidget(display, e)) e_preventDefault(e);
  1149. });
  1150. on(te, "compositionstart", function() {
  1151. var start = cm.getCursor("from");
  1152. if (input.composing) input.composing.range.clear()
  1153. input.composing = {
  1154. start: start,
  1155. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  1156. };
  1157. });
  1158. on(te, "compositionend", function() {
  1159. if (input.composing) {
  1160. input.poll();
  1161. input.composing.range.clear();
  1162. input.composing = null;
  1163. }
  1164. });
  1165. },
  1166. prepareSelection: function() {
  1167. // Redraw the selection and/or cursor
  1168. var cm = this.cm, display = cm.display, doc = cm.doc;
  1169. var result = prepareSelection(cm);
  1170. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1171. if (cm.options.moveInputWithCursor) {
  1172. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1173. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1174. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1175. headPos.top + lineOff.top - wrapOff.top));
  1176. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1177. headPos.left + lineOff.left - wrapOff.left));
  1178. }
  1179. return result;
  1180. },
  1181. showSelection: function(drawn) {
  1182. var cm = this.cm, display = cm.display;
  1183. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1184. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1185. if (drawn.teTop != null) {
  1186. this.wrapper.style.top = drawn.teTop + "px";
  1187. this.wrapper.style.left = drawn.teLeft + "px";
  1188. }
  1189. },
  1190. // Reset the input to correspond to the selection (or to be empty,
  1191. // when not typing and nothing is selected)
  1192. reset: function(typing) {
  1193. if (this.contextMenuPending) return;
  1194. var minimal, selected, cm = this.cm, doc = cm.doc;
  1195. if (cm.somethingSelected()) {
  1196. this.prevInput = "";
  1197. var range = doc.sel.primary();
  1198. minimal = hasCopyEvent &&
  1199. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1200. var content = minimal ? "-" : selected || cm.getSelection();
  1201. this.textarea.value = content;
  1202. if (cm.state.focused) selectInput(this.textarea);
  1203. if (ie && ie_version >= 9) this.hasSelection = content;
  1204. } else if (!typing) {
  1205. this.prevInput = this.textarea.value = "";
  1206. if (ie && ie_version >= 9) this.hasSelection = null;
  1207. }
  1208. this.inaccurateSelection = minimal;
  1209. },
  1210. getField: function() { return this.textarea; },
  1211. supportsTouch: function() { return false; },
  1212. focus: function() {
  1213. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1214. try { this.textarea.focus(); }
  1215. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  1216. }
  1217. },
  1218. blur: function() { this.textarea.blur(); },
  1219. resetPosition: function() {
  1220. this.wrapper.style.top = this.wrapper.style.left = 0;
  1221. },
  1222. receivedFocus: function() { this.slowPoll(); },
  1223. // Poll for input changes, using the normal rate of polling. This
  1224. // runs as long as the editor is focused.
  1225. slowPoll: function() {
  1226. var input = this;
  1227. if (input.pollingFast) return;
  1228. input.polling.set(this.cm.options.pollInterval, function() {
  1229. input.poll();
  1230. if (input.cm.state.focused) input.slowPoll();
  1231. });
  1232. },
  1233. // When an event has just come in that is likely to add or change
  1234. // something in the input textarea, we poll faster, to ensure that
  1235. // the change appears on the screen quickly.
  1236. fastPoll: function() {
  1237. var missed = false, input = this;
  1238. input.pollingFast = true;
  1239. function p() {
  1240. var changed = input.poll();
  1241. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  1242. else {input.pollingFast = false; input.slowPoll();}
  1243. }
  1244. input.polling.set(20, p);
  1245. },
  1246. // Read input from the textarea, and update the document to match.
  1247. // When something is selected, it is present in the textarea, and
  1248. // selected (unless it is huge, in which case a placeholder is
  1249. // used). When nothing is selected, the cursor sits after previously
  1250. // seen text (can be empty), which is stored in prevInput (we must
  1251. // not reset the textarea when typing, because that breaks IME).
  1252. poll: function() {
  1253. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1254. // Since this is called a *lot*, try to bail out as cheaply as
  1255. // possible when it is clear that nothing happened. hasSelection
  1256. // will be the case when there is a lot of text in the textarea,
  1257. // in which case reading its value would be expensive.
  1258. if (this.contextMenuPending || !cm.state.focused ||
  1259. (hasSelection(input) && !prevInput && !this.composing) ||
  1260. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  1261. return false;
  1262. var text = input.value;
  1263. // If nothing changed, bail.
  1264. if (text == prevInput && !cm.somethingSelected()) return false;
  1265. // Work around nonsensical selection resetting in IE9/10, and
  1266. // inexplicable appearance of private area unicode characters on
  1267. // some key combos in Mac (#2689).
  1268. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1269. mac && /[\uf700-\uf7ff]/.test(text)) {
  1270. cm.display.input.reset();
  1271. return false;
  1272. }
  1273. if (cm.doc.sel == cm.display.selForContextMenu) {
  1274. var first = text.charCodeAt(0);
  1275. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  1276. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  1277. }
  1278. // Find the part of the input that is actually new
  1279. var same = 0, l = Math.min(prevInput.length, text.length);
  1280. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1281. var self = this;
  1282. runInOp(cm, function() {
  1283. applyTextInput(cm, text.slice(same), prevInput.length - same,
  1284. null, self.composing ? "*compose" : null);
  1285. // Don't leave long text in the textarea, since it makes further polling slow
  1286. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1287. else self.prevInput = text;
  1288. if (self.composing) {
  1289. self.composing.range.clear();
  1290. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  1291. {className: "CodeMirror-composing"});
  1292. }
  1293. });
  1294. return true;
  1295. },
  1296. ensurePolled: function() {
  1297. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1298. },
  1299. onKeyPress: function() {
  1300. if (ie && ie_version >= 9) this.hasSelection = null;
  1301. this.fastPoll();
  1302. },
  1303. onContextMenu: function(e) {
  1304. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1305. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1306. if (!pos || presto) return; // Opera is difficult.
  1307. // Reset the current text selection only if the click is done outside of the selection
  1308. // and 'resetSelectionOnContextMenu' option is true.
  1309. var reset = cm.options.resetSelectionOnContextMenu;
  1310. if (reset && cm.doc.sel.contains(pos) == -1)
  1311. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1312. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  1313. input.wrapper.style.cssText = "position: absolute"
  1314. var wrapperBox = input.wrapper.getBoundingClientRect()
  1315. te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
  1316. "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
  1317. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1318. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1319. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1320. display.input.focus();
  1321. if (webkit) window.scrollTo(null, oldScrollY);
  1322. display.input.reset();
  1323. // Adds "Select all" to context menu in FF
  1324. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1325. input.contextMenuPending = true;
  1326. display.selForContextMenu = cm.doc.sel;
  1327. clearTimeout(display.detectingSelectAll);
  1328. // Select-all will be greyed out if there's nothing to select, so
  1329. // this adds a zero-width space so that we can later check whether
  1330. // it got selected.
  1331. function prepareSelectAllHack() {
  1332. if (te.selectionStart != null) {
  1333. var selected = cm.somethingSelected();
  1334. var extval = "\u200b" + (selected ? te.value : "");
  1335. te.value = "\u21da"; // Used to catch context-menu undo
  1336. te.value = extval;
  1337. input.prevInput = selected ? "" : "\u200b";
  1338. te.selectionStart = 1; te.selectionEnd = extval.length;
  1339. // Re-set this, in case some other handler touched the
  1340. // selection in the meantime.
  1341. display.selForContextMenu = cm.doc.sel;
  1342. }
  1343. }
  1344. function rehide() {
  1345. input.contextMenuPending = false;
  1346. input.wrapper.style.cssText = oldWrapperCSS
  1347. te.style.cssText = oldCSS;
  1348. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1349. // Try to detect the user choosing select-all
  1350. if (te.selectionStart != null) {
  1351. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1352. var i = 0, poll = function() {
  1353. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  1354. te.selectionEnd > 0 && input.prevInput == "\u200b")
  1355. operation(cm, commands.selectAll)(cm);
  1356. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1357. else display.input.reset();
  1358. };
  1359. display.detectingSelectAll = setTimeout(poll, 200);
  1360. }
  1361. }
  1362. if (ie && ie_version >= 9) prepareSelectAllHack();
  1363. if (captureRightClick) {
  1364. e_stop(e);
  1365. var mouseup = function() {
  1366. off(window, "mouseup", mouseup);
  1367. setTimeout(rehide, 20);
  1368. };
  1369. on(window, "mouseup", mouseup);
  1370. } else {
  1371. setTimeout(rehide, 50);
  1372. }
  1373. },
  1374. readOnlyChanged: function(val) {
  1375. if (!val) this.reset();
  1376. },
  1377. setUneditable: nothing,
  1378. needsContentAttribute: false
  1379. }, TextareaInput.prototype);
  1380. // CONTENTEDITABLE INPUT STYLE
  1381. function ContentEditableInput(cm) {
  1382. this.cm = cm;
  1383. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1384. this.polling = new Delayed();
  1385. this.gracePeriod = false;
  1386. }
  1387. ContentEditableInput.prototype = copyObj({
  1388. init: function(display) {
  1389. var input = this, cm = input.cm;
  1390. var div = input.div = display.lineDiv;
  1391. disableBrowserMagic(div);
  1392. on(div, "paste", function(e) {
  1393. if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
  1394. })
  1395. on(div, "compositionstart", function(e) {
  1396. var data = e.data;
  1397. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  1398. if (!data) return;
  1399. var prim = cm.doc.sel.primary();
  1400. var line = cm.getLine(prim.head.line);
  1401. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1402. if (found > -1 && found <= prim.head.ch)
  1403. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1404. Pos(prim.head.line, found + data.length));
  1405. });
  1406. on(div, "compositionupdate", function(e) {
  1407. input.composing.data = e.data;
  1408. });
  1409. on(div, "compositionend", function(e) {
  1410. var ours = input.composing;
  1411. if (!ours) return;
  1412. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1413. ours.data = e.data;
  1414. // Need a small delay to prevent other code (input event,
  1415. // selection polling) from doing damage when fired right after
  1416. // compositionend.
  1417. setTimeout(function() {
  1418. if (!ours.handled)
  1419. input.applyComposition(ours);
  1420. if (input.composing == ours)
  1421. input.composing = null;
  1422. }, 50);
  1423. });
  1424. on(div, "touchstart", function() {
  1425. input.forceCompositionEnd();
  1426. });
  1427. on(div, "input", function() {
  1428. if (input.composing) return;
  1429. if (cm.isReadOnly() || !input.pollContent())
  1430. runInOp(input.cm, function() {regChange(cm);});
  1431. });
  1432. function onCopyCut(e) {
  1433. if (signalDOMEvent(cm, e)) return
  1434. if (cm.somethingSelected()) {
  1435. lastCopied = cm.getSelections();
  1436. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1437. } else if (!cm.options.lineWiseCopyCut) {
  1438. return;
  1439. } else {
  1440. var ranges = copyableRanges(cm);
  1441. lastCopied = ranges.text;
  1442. if (e.type == "cut") {
  1443. cm.operation(function() {
  1444. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1445. cm.replaceSelection("", null, "cut");
  1446. });
  1447. }
  1448. }
  1449. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1450. if (e.clipboardData && !ios) {
  1451. e.preventDefault();
  1452. e.clipboardData.clearData();
  1453. e.clipboardData.setData("text/plain", lastCopied.join("\n"));
  1454. } else {
  1455. // Old-fashioned briefly-focus-a-textarea hack
  1456. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1457. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1458. te.value = lastCopied.join("\n");
  1459. var hadFocus = document.activeElement;
  1460. selectInput(te);
  1461. setTimeout(function() {
  1462. cm.display.lineSpace.removeChild(kludge);
  1463. hadFocus.focus();
  1464. }, 50);
  1465. }
  1466. }
  1467. on(div, "copy", onCopyCut);
  1468. on(div, "cut", onCopyCut);
  1469. },
  1470. prepareSelection: function() {
  1471. var result = prepareSelection(this.cm, false);
  1472. result.focus = this.cm.state.focused;
  1473. return result;
  1474. },
  1475. showSelection: function(info) {
  1476. if (!info || !this.cm.display.view.length) return;
  1477. if (info.focus) this.showPrimarySelection();
  1478. this.showMultipleSelections(info);
  1479. },
  1480. showPrimarySelection: function() {
  1481. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1482. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1483. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1484. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1485. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1486. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1487. return;
  1488. var start = posToDOM(this.cm, prim.from());
  1489. var end = posToDOM(this.cm, prim.to());
  1490. if (!start && !end) return;
  1491. var view = this.cm.display.view;
  1492. var old = sel.rangeCount && sel.getRangeAt(0);
  1493. if (!start) {
  1494. start = {node: view[0].measure.map[2], offset: 0};
  1495. } else if (!end) { // FIXME dangerously hacky
  1496. var measure = view[view.length - 1].measure;
  1497. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1498. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  1499. }
  1500. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1501. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1502. if (rng) {
  1503. if (!gecko && this.cm.state.focused) {
  1504. sel.collapse(start.node, start.offset);
  1505. if (!rng.collapsed) sel.addRange(rng);
  1506. } else {
  1507. sel.removeAllRanges();
  1508. sel.addRange(rng);
  1509. }
  1510. if (old && sel.anchorNode == null) sel.addRange(old);
  1511. else if (gecko) this.startGracePeriod();
  1512. }
  1513. this.rememberSelection();
  1514. },
  1515. startGracePeriod: function() {
  1516. var input = this;
  1517. clearTimeout(this.gracePeriod);
  1518. this.gracePeriod = setTimeout(function() {
  1519. input.gracePeriod = false;
  1520. if (input.selectionChanged())
  1521. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  1522. }, 20);
  1523. },
  1524. showMultipleSelections: function(info) {
  1525. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1526. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1527. },
  1528. rememberSelection: function() {
  1529. var sel = window.getSelection();
  1530. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1531. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1532. },
  1533. selectionInEditor: function() {
  1534. var sel = window.getSelection();
  1535. if (!sel.rangeCount) return false;
  1536. var node = sel.getRangeAt(0).commonAncestorContainer;
  1537. return contains(this.div, node);
  1538. },
  1539. focus: function() {
  1540. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1541. },
  1542. blur: function() { this.div.blur(); },
  1543. getField: function() { return this.div; },
  1544. supportsTouch: function() { return true; },
  1545. receivedFocus: function() {
  1546. var input = this;
  1547. if (this.selectionInEditor())
  1548. this.pollSelection();
  1549. else
  1550. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  1551. function poll() {
  1552. if (input.cm.state.focused) {
  1553. input.pollSelection();
  1554. input.polling.set(input.cm.options.pollInterval, poll);
  1555. }
  1556. }
  1557. this.polling.set(this.cm.options.pollInterval, poll);
  1558. },
  1559. selectionChanged: function() {
  1560. var sel = window.getSelection();
  1561. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1562. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  1563. },
  1564. pollSelection: function() {
  1565. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  1566. var sel = window.getSelection(), cm = this.cm;
  1567. this.rememberSelection();
  1568. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1569. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1570. if (anchor && head) runInOp(cm, function() {
  1571. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1572. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1573. });
  1574. }
  1575. },
  1576. pollContent: function() {
  1577. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1578. var from = sel.from(), to = sel.to();
  1579. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1580. var fromIndex;
  1581. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1582. var fromLine = lineNo(display.view[0].line);
  1583. var fromNode = display.view[0].node;
  1584. } else {
  1585. var fromLine = lineNo(display.view[fromIndex].line);
  1586. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1587. }
  1588. var toIndex = findViewIndex(cm, to.line);
  1589. if (toIndex == display.view.length - 1) {
  1590. var toLine = display.viewTo - 1;
  1591. var toNode = display.lineDiv.lastChild;
  1592. } else {
  1593. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1594. var toNode = display.view[toIndex + 1].node.previousSibling;
  1595. }
  1596. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1597. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1598. while (newText.length > 1 && oldText.length > 1) {
  1599. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1600. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1601. else break;
  1602. }
  1603. var cutFront = 0, cutEnd = 0;
  1604. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1605. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1606. ++cutFront;
  1607. var newBot = lst(newText), oldBot = lst(oldText);
  1608. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1609. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1610. while (cutEnd < maxCutEnd &&
  1611. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1612. ++cutEnd;
  1613. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1614. newText[0] = newText[0].slice(cutFront);
  1615. var chFrom = Pos(fromLine, cutFront);
  1616. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1617. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1618. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1619. return true;
  1620. }
  1621. },
  1622. ensurePolled: function() {
  1623. this.forceCompositionEnd();
  1624. },
  1625. reset: function() {
  1626. this.forceCompositionEnd();
  1627. },
  1628. forceCompositionEnd: function() {
  1629. if (!this.composing || this.composing.handled) return;
  1630. this.applyComposition(this.composing);
  1631. this.composing.handled = true;
  1632. this.div.blur();
  1633. this.div.focus();
  1634. },
  1635. applyComposition: function(composing) {
  1636. if (this.cm.isReadOnly())
  1637. operation(this.cm, regChange)(this.cm)
  1638. else if (composing.data && composing.data != composing.startData)
  1639. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1640. },
  1641. setUneditable: function(node) {
  1642. node.contentEditable = "false"
  1643. },
  1644. onKeyPress: function(e) {
  1645. e.preventDefault();
  1646. if (!this.cm.isReadOnly())
  1647. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1648. },
  1649. readOnlyChanged: function(val) {
  1650. this.div.contentEditable = String(val != "nocursor")
  1651. },
  1652. onContextMenu: nothing,
  1653. resetPosition: nothing,
  1654. needsContentAttribute: true
  1655. }, ContentEditableInput.prototype);
  1656. function posToDOM(cm, pos) {
  1657. var view = findViewForLine(cm, pos.line);
  1658. if (!view || view.hidden) return null;
  1659. var line = getLine(cm.doc, pos.line);
  1660. var info = mapFromLineView(view, line, pos.line);
  1661. var order = getOrder(line), side = "left";
  1662. if (order) {
  1663. var partPos = getBidiPartAt(order, pos.ch);
  1664. side = partPos % 2 ? "right" : "left";
  1665. }
  1666. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  1667. result.offset = result.collapse == "right" ? result.end : result.start;
  1668. return result;
  1669. }
  1670. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1671. function domToPos(cm, node, offset) {
  1672. var lineNode;
  1673. if (node == cm.display.lineDiv) {
  1674. lineNode = cm.display.lineDiv.childNodes[offset];
  1675. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1676. node = null; offset = 0;
  1677. } else {
  1678. for (lineNode = node;; lineNode = lineNode.parentNode) {
  1679. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1680. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1681. }
  1682. }
  1683. for (var i = 0; i < cm.display.view.length; i++) {
  1684. var lineView = cm.display.view[i];
  1685. if (lineView.node == lineNode)
  1686. return locateNodeInLineView(lineView, node, offset);
  1687. }
  1688. }
  1689. function locateNodeInLineView(lineView, node, offset) {
  1690. var wrapper = lineView.text.firstChild, bad = false;
  1691. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1692. if (node == wrapper) {
  1693. bad = true;
  1694. node = wrapper.childNodes[offset];
  1695. offset = 0;
  1696. if (!node) {
  1697. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1698. return badPos(Pos(lineNo(line), line.text.length), bad);
  1699. }
  1700. }
  1701. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1702. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1703. textNode = node.firstChild;
  1704. if (offset) offset = textNode.nodeValue.length;
  1705. }
  1706. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1707. var measure = lineView.measure, maps = measure.maps;
  1708. function find(textNode, topNode, offset) {
  1709. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1710. var map = i < 0 ? measure.map : maps[i];
  1711. for (var j = 0; j < map.length; j += 3) {
  1712. var curNode = map[j + 2];
  1713. if (curNode == textNode || curNode == topNode) {
  1714. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1715. var ch = map[j] + offset;
  1716. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1717. return Pos(line, ch);
  1718. }
  1719. }
  1720. }
  1721. }
  1722. var found = find(textNode, topNode, offset);
  1723. if (found) return badPos(found, bad);
  1724. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1725. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1726. found = find(after, after.firstChild, 0);
  1727. if (found)
  1728. return badPos(Pos(found.line, found.ch - dist), bad);
  1729. else
  1730. dist += after.textContent.length;
  1731. }
  1732. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1733. found = find(before, before.firstChild, -1);
  1734. if (found)
  1735. return badPos(Pos(found.line, found.ch + dist), bad);
  1736. else
  1737. dist += after.textContent.length;
  1738. }
  1739. }
  1740. function domTextBetween(cm, from, to, fromLine, toLine) {
  1741. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  1742. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  1743. function walk(node) {
  1744. if (node.nodeType == 1) {
  1745. var cmText = node.getAttribute("cm-text");
  1746. if (cmText != null) {
  1747. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1748. text += cmText;
  1749. return;
  1750. }
  1751. var markerID = node.getAttribute("cm-marker"), range;
  1752. if (markerID) {
  1753. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1754. if (found.length && (range = found[0].find()))
  1755. text += getBetween(cm.doc, range.from, range.to).join(lineSep);
  1756. return;
  1757. }
  1758. if (node.getAttribute("contenteditable") == "false") return;
  1759. for (var i = 0; i < node.childNodes.length; i++)
  1760. walk(node.childNodes[i]);
  1761. if (/^(pre|div|p)$/i.test(node.nodeName))
  1762. closing = true;
  1763. } else if (node.nodeType == 3) {
  1764. var val = node.nodeValue;
  1765. if (!val) return;
  1766. if (closing) {
  1767. text += lineSep;
  1768. closing = false;
  1769. }
  1770. text += val;
  1771. }
  1772. }
  1773. for (;;) {
  1774. walk(from);
  1775. if (from == to) break;
  1776. from = from.nextSibling;
  1777. }
  1778. return text;
  1779. }
  1780. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  1781. // SELECTION / CURSOR
  1782. // Selection objects are immutable. A new one is created every time
  1783. // the selection changes. A selection is one or more non-overlapping
  1784. // (and non-touching) ranges, sorted, and an integer that indicates
  1785. // which one is the primary selection (the one that's scrolled into
  1786. // view, that getCursor returns, etc).
  1787. function Selection(ranges, primIndex) {
  1788. this.ranges = ranges;
  1789. this.primIndex = primIndex;
  1790. }
  1791. Selection.prototype = {
  1792. primary: function() { return this.ranges[this.primIndex]; },
  1793. equals: function(other) {
  1794. if (other == this) return true;
  1795. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1796. for (var i = 0; i < this.ranges.length; i++) {
  1797. var here = this.ranges[i], there = other.ranges[i];
  1798. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1799. }
  1800. return true;
  1801. },
  1802. deepCopy: function() {
  1803. for (var out = [], i = 0; i < this.ranges.length; i++)
  1804. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1805. return new Selection(out, this.primIndex);
  1806. },
  1807. somethingSelected: function() {
  1808. for (var i = 0; i < this.ranges.length; i++)
  1809. if (!this.ranges[i].empty()) return true;
  1810. return false;
  1811. },
  1812. contains: function(pos, end) {
  1813. if (!end) end = pos;
  1814. for (var i = 0; i < this.ranges.length; i++) {
  1815. var range = this.ranges[i];
  1816. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1817. return i;
  1818. }
  1819. return -1;
  1820. }
  1821. };
  1822. function Range(anchor, head) {
  1823. this.anchor = anchor; this.head = head;
  1824. }
  1825. Range.prototype = {
  1826. from: function() { return minPos(this.anchor, this.head); },
  1827. to: function() { return maxPos(this.anchor, this.head); },
  1828. empty: function() {
  1829. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1830. }
  1831. };
  1832. // Take an unsorted, potentially overlapping set of ranges, and
  1833. // build a selection out of it. 'Consumes' ranges array (modifying
  1834. // it).
  1835. function normalizeSelection(ranges, primIndex) {
  1836. var prim = ranges[primIndex];
  1837. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1838. primIndex = indexOf(ranges, prim);
  1839. for (var i = 1; i < ranges.length; i++) {
  1840. var cur = ranges[i], prev = ranges[i - 1];
  1841. if (cmp(prev.to(), cur.from()) >= 0) {
  1842. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1843. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1844. if (i <= primIndex) --primIndex;
  1845. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1846. }
  1847. }
  1848. return new Selection(ranges, primIndex);
  1849. }
  1850. function simpleSelection(anchor, head) {
  1851. return new Selection([new Range(anchor, head || anchor)], 0);
  1852. }
  1853. // Most of the external API clips given positions to make sure they
  1854. // actually exist within the document.
  1855. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1856. function clipPos(doc, pos) {
  1857. if (pos.line < doc.first) return Pos(doc.first, 0);
  1858. var last = doc.first + doc.size - 1;
  1859. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1860. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1861. }
  1862. function clipToLen(pos, linelen) {
  1863. var ch = pos.ch;
  1864. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1865. else if (ch < 0) return Pos(pos.line, 0);
  1866. else return pos;
  1867. }
  1868. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1869. function clipPosArray(doc, array) {
  1870. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1871. return out;
  1872. }
  1873. // SELECTION UPDATES
  1874. // The 'scroll' parameter given to many of these indicated whether
  1875. // the new cursor position should be scrolled into view after
  1876. // modifying the selection.
  1877. // If shift is held or the extend flag is set, extends a range to
  1878. // include a given position (and optionally a second position).
  1879. // Otherwise, simply returns the range between the given positions.
  1880. // Used for cursor motion and such.
  1881. function extendRange(doc, range, head, other) {
  1882. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1883. var anchor = range.anchor;
  1884. if (other) {
  1885. var posBefore = cmp(head, anchor) < 0;
  1886. if (posBefore != (cmp(other, anchor) < 0)) {
  1887. anchor = head;
  1888. head = other;
  1889. } else if (posBefore != (cmp(head, other) < 0)) {
  1890. head = other;
  1891. }
  1892. }
  1893. return new Range(anchor, head);
  1894. } else {
  1895. return new Range(other || head, head);
  1896. }
  1897. }
  1898. // Extend the primary selection range, discard the rest.
  1899. function extendSelection(doc, head, other, options) {
  1900. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1901. }
  1902. // Extend all selections (pos is an array of selections with length
  1903. // equal the number of selections)
  1904. function extendSelections(doc, heads, options) {
  1905. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1906. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1907. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1908. setSelection(doc, newSel, options);
  1909. }
  1910. // Updates a single range in the selection.
  1911. function replaceOneSelection(doc, i, range, options) {
  1912. var ranges = doc.sel.ranges.slice(0);
  1913. ranges[i] = range;
  1914. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1915. }
  1916. // Reset the selection to a single range.
  1917. function setSimpleSelection(doc, anchor, head, options) {
  1918. setSelection(doc, simpleSelection(anchor, head), options);
  1919. }
  1920. // Give beforeSelectionChange handlers a change to influence a
  1921. // selection update.
  1922. function filterSelectionChange(doc, sel, options) {
  1923. var obj = {
  1924. ranges: sel.ranges,
  1925. update: function(ranges) {
  1926. this.ranges = [];
  1927. for (var i = 0; i < ranges.length; i++)
  1928. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1929. clipPos(doc, ranges[i].head));
  1930. },
  1931. origin: options && options.origin
  1932. };
  1933. signal(doc, "beforeSelectionChange", doc, obj);
  1934. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1935. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1936. else return sel;
  1937. }
  1938. function setSelectionReplaceHistory(doc, sel, options) {
  1939. var done = doc.history.done, last = lst(done);
  1940. if (last && last.ranges) {
  1941. done[done.length - 1] = sel;
  1942. setSelectionNoUndo(doc, sel, options);
  1943. } else {
  1944. setSelection(doc, sel, options);
  1945. }
  1946. }
  1947. // Set a new selection.
  1948. function setSelection(doc, sel, options) {
  1949. setSelectionNoUndo(doc, sel, options);
  1950. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1951. }
  1952. function setSelectionNoUndo(doc, sel, options) {
  1953. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1954. sel = filterSelectionChange(doc, sel, options);
  1955. var bias = options && options.bias ||
  1956. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1957. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1958. if (!(options && options.scroll === false) && doc.cm)
  1959. ensureCursorVisible(doc.cm);
  1960. }
  1961. function setSelectionInner(doc, sel) {
  1962. if (sel.equals(doc.sel)) return;
  1963. doc.sel = sel;
  1964. if (doc.cm) {
  1965. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1966. signalCursorActivity(doc.cm);
  1967. }
  1968. signalLater(doc, "cursorActivity", doc);
  1969. }
  1970. // Verify that the selection does not partially select any atomic
  1971. // marked ranges.
  1972. function reCheckSelection(doc) {
  1973. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1974. }
  1975. // Return a selection that does not partially select any atomic
  1976. // ranges.
  1977. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1978. var out;
  1979. for (var i = 0; i < sel.ranges.length; i++) {
  1980. var range = sel.ranges[i];
  1981. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  1982. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  1983. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  1984. if (out || newAnchor != range.anchor || newHead != range.head) {
  1985. if (!out) out = sel.ranges.slice(0, i);
  1986. out[i] = new Range(newAnchor, newHead);
  1987. }
  1988. }
  1989. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1990. }
  1991. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  1992. var line = getLine(doc, pos.line);
  1993. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  1994. var sp = line.markedSpans[i], m = sp.marker;
  1995. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  1996. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  1997. if (mayClear) {
  1998. signal(m, "beforeCursorEnter");
  1999. if (m.explicitlyCleared) {
  2000. if (!line.markedSpans) break;
  2001. else {--i; continue;}
  2002. }
  2003. }
  2004. if (!m.atomic) continue;
  2005. if (oldPos) {
  2006. var near = m.find(dir < 0 ? 1 : -1), diff;
  2007. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  2008. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
  2009. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  2010. return skipAtomicInner(doc, near, pos, dir, mayClear);
  2011. }
  2012. var far = m.find(dir < 0 ? -1 : 1);
  2013. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  2014. far = movePos(doc, far, dir, far.line == pos.line ? line : null);
  2015. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
  2016. }
  2017. }
  2018. return pos;
  2019. }
  2020. // Ensure a given position is not inside an atomic range.
  2021. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  2022. var dir = bias || 1;
  2023. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  2024. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  2025. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  2026. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  2027. if (!found) {
  2028. doc.cantEdit = true;
  2029. return Pos(doc.first, 0);
  2030. }
  2031. return found;
  2032. }
  2033. function movePos(doc, pos, dir, line) {
  2034. if (dir < 0 && pos.ch == 0) {
  2035. if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
  2036. else return null;
  2037. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  2038. if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
  2039. else return null;
  2040. } else {
  2041. return new Pos(pos.line, pos.ch + dir);
  2042. }
  2043. }
  2044. // SELECTION DRAWING
  2045. function updateSelection(cm) {
  2046. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2047. }
  2048. function prepareSelection(cm, primary) {
  2049. var doc = cm.doc, result = {};
  2050. var curFragment = result.cursors = document.createDocumentFragment();
  2051. var selFragment = result.selection = document.createDocumentFragment();
  2052. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2053. if (primary === false && i == doc.sel.primIndex) continue;
  2054. var range = doc.sel.ranges[i];
  2055. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
  2056. var collapsed = range.empty();
  2057. if (collapsed || cm.options.showCursorWhenSelecting)
  2058. drawSelectionCursor(cm, range.head, curFragment);
  2059. if (!collapsed)
  2060. drawSelectionRange(cm, range, selFragment);
  2061. }
  2062. return result;
  2063. }
  2064. // Draws a cursor for the given range
  2065. function drawSelectionCursor(cm, head, output) {
  2066. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2067. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2068. cursor.style.left = pos.left + "px";
  2069. cursor.style.top = pos.top + "px";
  2070. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2071. if (pos.other) {
  2072. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2073. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2074. otherCursor.style.display = "";
  2075. otherCursor.style.left = pos.other.left + "px";
  2076. otherCursor.style.top = pos.other.top + "px";
  2077. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2078. }
  2079. }
  2080. // Draws the given range as a highlighted selection
  2081. function drawSelectionRange(cm, range, output) {
  2082. var display = cm.display, doc = cm.doc;
  2083. var fragment = document.createDocumentFragment();
  2084. var padding = paddingH(cm.display), leftSide = padding.left;
  2085. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2086. function add(left, top, width, bottom) {
  2087. if (top < 0) top = 0;
  2088. top = Math.round(top);
  2089. bottom = Math.round(bottom);
  2090. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  2091. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  2092. "px; height: " + (bottom - top) + "px"));
  2093. }
  2094. function drawForLine(line, fromArg, toArg) {
  2095. var lineObj = getLine(doc, line);
  2096. var lineLen = lineObj.text.length;
  2097. var start, end;
  2098. function coords(ch, bias) {
  2099. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2100. }
  2101. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  2102. var leftPos = coords(from, "left"), rightPos, left, right;
  2103. if (from == to) {
  2104. rightPos = leftPos;
  2105. left = right = leftPos.left;
  2106. } else {
  2107. rightPos = coords(to - 1, "right");
  2108. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2109. left = leftPos.left;
  2110. right = rightPos.right;
  2111. }
  2112. if (fromArg == null && from == 0) left = leftSide;
  2113. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2114. add(left, leftPos.top, null, leftPos.bottom);
  2115. left = leftSide;
  2116. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2117. }
  2118. if (toArg == null && to == lineLen) right = rightSide;
  2119. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2120. start = leftPos;
  2121. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2122. end = rightPos;
  2123. if (left < leftSide + 1) left = leftSide;
  2124. add(left, rightPos.top, right - left, rightPos.bottom);
  2125. });
  2126. return {start: start, end: end};
  2127. }
  2128. var sFrom = range.from(), sTo = range.to();
  2129. if (sFrom.line == sTo.line) {
  2130. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2131. } else {
  2132. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2133. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2134. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2135. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2136. if (singleVLine) {
  2137. if (leftEnd.top < rightStart.top - 2) {
  2138. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2139. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2140. } else {
  2141. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2142. }
  2143. }
  2144. if (leftEnd.bottom < rightStart.top)
  2145. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2146. }
  2147. output.appendChild(fragment);
  2148. }
  2149. // Cursor-blinking
  2150. function restartBlink(cm) {
  2151. if (!cm.state.focused) return;
  2152. var display = cm.display;
  2153. clearInterval(display.blinker);
  2154. var on = true;
  2155. display.cursorDiv.style.visibility = "";
  2156. if (cm.options.cursorBlinkRate > 0)
  2157. display.blinker = setInterval(function() {
  2158. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2159. }, cm.options.cursorBlinkRate);
  2160. else if (cm.options.cursorBlinkRate < 0)
  2161. display.cursorDiv.style.visibility = "hidden";
  2162. }
  2163. // HIGHLIGHT WORKER
  2164. function startWorker(cm, time) {
  2165. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2166. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2167. }
  2168. function highlightWorker(cm) {
  2169. var doc = cm.doc;
  2170. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2171. if (doc.frontier >= cm.display.viewTo) return;
  2172. var end = +new Date + cm.options.workTime;
  2173. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2174. var changedLines = [];
  2175. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  2176. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2177. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  2178. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  2179. line.styles = highlighted.styles;
  2180. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2181. if (newCls) line.styleClasses = newCls;
  2182. else if (oldCls) line.styleClasses = null;
  2183. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2184. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2185. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2186. if (ischange) changedLines.push(doc.frontier);
  2187. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  2188. } else {
  2189. if (line.text.length <= cm.options.maxHighlightLength)
  2190. processLine(cm, line.text, state);
  2191. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2192. }
  2193. ++doc.frontier;
  2194. if (+new Date > end) {
  2195. startWorker(cm, cm.options.workDelay);
  2196. return true;
  2197. }
  2198. });
  2199. if (changedLines.length) runInOp(cm, function() {
  2200. for (var i = 0; i < changedLines.length; i++)
  2201. regLineChange(cm, changedLines[i], "text");
  2202. });
  2203. }
  2204. // Finds the line to start with when starting a parse. Tries to
  2205. // find a line with a stateAfter, so that it can start with a
  2206. // valid state. If that fails, it returns the line with the
  2207. // smallest indentation, which tends to need the least context to
  2208. // parse correctly.
  2209. function findStartLine(cm, n, precise) {
  2210. var minindent, minline, doc = cm.doc;
  2211. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2212. for (var search = n; search > lim; --search) {
  2213. if (search <= doc.first) return doc.first;
  2214. var line = getLine(doc, search - 1);
  2215. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2216. var indented = countColumn(line.text, null, cm.options.tabSize);
  2217. if (minline == null || minindent > indented) {
  2218. minline = search - 1;
  2219. minindent = indented;
  2220. }
  2221. }
  2222. return minline;
  2223. }
  2224. function getStateBefore(cm, n, precise) {
  2225. var doc = cm.doc, display = cm.display;
  2226. if (!doc.mode.startState) return true;
  2227. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  2228. if (!state) state = startState(doc.mode);
  2229. else state = copyState(doc.mode, state);
  2230. doc.iter(pos, n, function(line) {
  2231. processLine(cm, line.text, state);
  2232. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2233. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2234. ++pos;
  2235. });
  2236. if (precise) doc.frontier = pos;
  2237. return state;
  2238. }
  2239. // POSITION MEASUREMENT
  2240. function paddingTop(display) {return display.lineSpace.offsetTop;}
  2241. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  2242. function paddingH(display) {
  2243. if (display.cachedPaddingH) return display.cachedPaddingH;
  2244. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2245. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2246. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2247. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2248. return data;
  2249. }
  2250. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2251. function displayWidth(cm) {
  2252. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2253. }
  2254. function displayHeight(cm) {
  2255. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2256. }
  2257. // Ensure the lineView.wrapping.heights array is populated. This is
  2258. // an array of bottom offsets for the lines that make up a drawn
  2259. // line. When lineWrapping is on, there might be more than one
  2260. // height.
  2261. function ensureLineHeights(cm, lineView, rect) {
  2262. var wrapping = cm.options.lineWrapping;
  2263. var curWidth = wrapping && displayWidth(cm);
  2264. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2265. var heights = lineView.measure.heights = [];
  2266. if (wrapping) {
  2267. lineView.measure.width = curWidth;
  2268. var rects = lineView.text.firstChild.getClientRects();
  2269. for (var i = 0; i < rects.length - 1; i++) {
  2270. var cur = rects[i], next = rects[i + 1];
  2271. if (Math.abs(cur.bottom - next.bottom) > 2)
  2272. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2273. }
  2274. }
  2275. heights.push(rect.bottom - rect.top);
  2276. }
  2277. }
  2278. // Find a line map (mapping character offsets to text nodes) and a
  2279. // measurement cache for the given line number. (A line view might
  2280. // contain multiple lines when collapsed ranges are present.)
  2281. function mapFromLineView(lineView, line, lineN) {
  2282. if (lineView.line == line)
  2283. return {map: lineView.measure.map, cache: lineView.measure.cache};
  2284. for (var i = 0; i < lineView.rest.length; i++)
  2285. if (lineView.rest[i] == line)
  2286. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  2287. for (var i = 0; i < lineView.rest.length; i++)
  2288. if (lineNo(lineView.rest[i]) > lineN)
  2289. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  2290. }
  2291. // Render a line into the hidden node display.externalMeasured. Used
  2292. // when measurement is needed for a line that's not in the viewport.
  2293. function updateExternalMeasurement(cm, line) {
  2294. line = visualLine(line);
  2295. var lineN = lineNo(line);
  2296. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2297. view.lineN = lineN;
  2298. var built = view.built = buildLineContent(cm, view);
  2299. view.text = built.pre;
  2300. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2301. return view;
  2302. }
  2303. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2304. // for a given character.
  2305. function measureChar(cm, line, ch, bias) {
  2306. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2307. }
  2308. // Find a line view that corresponds to the given line number.
  2309. function findViewForLine(cm, lineN) {
  2310. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2311. return cm.display.view[findViewIndex(cm, lineN)];
  2312. var ext = cm.display.externalMeasured;
  2313. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2314. return ext;
  2315. }
  2316. // Measurement can be split in two steps, the set-up work that
  2317. // applies to the whole line, and the measurement of the actual
  2318. // character. Functions like coordsChar, that need to do a lot of
  2319. // measurements in a row, can thus ensure that the set-up work is
  2320. // only done once.
  2321. function prepareMeasureForLine(cm, line) {
  2322. var lineN = lineNo(line);
  2323. var view = findViewForLine(cm, lineN);
  2324. if (view && !view.text) {
  2325. view = null;
  2326. } else if (view && view.changes) {
  2327. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2328. cm.curOp.forceUpdate = true;
  2329. }
  2330. if (!view)
  2331. view = updateExternalMeasurement(cm, line);
  2332. var info = mapFromLineView(view, line, lineN);
  2333. return {
  2334. line: line, view: view, rect: null,
  2335. map: info.map, cache: info.cache, before: info.before,
  2336. hasHeights: false
  2337. };
  2338. }
  2339. // Given a prepared measurement object, measures the position of an
  2340. // actual character (or fetches it from the cache).
  2341. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2342. if (prepared.before) ch = -1;
  2343. var key = ch + (bias || ""), found;
  2344. if (prepared.cache.hasOwnProperty(key)) {
  2345. found = prepared.cache[key];
  2346. } else {
  2347. if (!prepared.rect)
  2348. prepared.rect = prepared.view.text.getBoundingClientRect();
  2349. if (!prepared.hasHeights) {
  2350. ensureLineHeights(cm, prepared.view, prepared.rect);
  2351. prepared.hasHeights = true;
  2352. }
  2353. found = measureCharInner(cm, prepared, ch, bias);
  2354. if (!found.bogus) prepared.cache[key] = found;
  2355. }
  2356. return {left: found.left, right: found.right,
  2357. top: varHeight ? found.rtop : found.top,
  2358. bottom: varHeight ? found.rbottom : found.bottom};
  2359. }
  2360. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2361. function nodeAndOffsetInLineMap(map, ch, bias) {
  2362. var node, start, end, collapse;
  2363. // First, search the line map for the text node corresponding to,
  2364. // or closest to, the target character.
  2365. for (var i = 0; i < map.length; i += 3) {
  2366. var mStart = map[i], mEnd = map[i + 1];
  2367. if (ch < mStart) {
  2368. start = 0; end = 1;
  2369. collapse = "left";
  2370. } else if (ch < mEnd) {
  2371. start = ch - mStart;
  2372. end = start + 1;
  2373. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2374. end = mEnd - mStart;
  2375. start = end - 1;
  2376. if (ch >= mEnd) collapse = "right";
  2377. }
  2378. if (start != null) {
  2379. node = map[i + 2];
  2380. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2381. collapse = bias;
  2382. if (bias == "left" && start == 0)
  2383. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2384. node = map[(i -= 3) + 2];
  2385. collapse = "left";
  2386. }
  2387. if (bias == "right" && start == mEnd - mStart)
  2388. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2389. node = map[(i += 3) + 2];
  2390. collapse = "right";
  2391. }
  2392. break;
  2393. }
  2394. }
  2395. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  2396. }
  2397. function measureCharInner(cm, prepared, ch, bias) {
  2398. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2399. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2400. var rect;
  2401. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2402. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2403. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  2404. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  2405. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2406. rect = node.parentNode.getBoundingClientRect();
  2407. } else if (ie && cm.options.lineWrapping) {
  2408. var rects = range(node, start, end).getClientRects();
  2409. if (rects.length)
  2410. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2411. else
  2412. rect = nullRect;
  2413. } else {
  2414. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  2415. }
  2416. if (rect.left || rect.right || start == 0) break;
  2417. end = start;
  2418. start = start - 1;
  2419. collapse = "right";
  2420. }
  2421. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2422. } else { // If it is a widget, simply get the box for the whole widget.
  2423. if (start > 0) collapse = bias = "right";
  2424. var rects;
  2425. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2426. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2427. else
  2428. rect = node.getBoundingClientRect();
  2429. }
  2430. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2431. var rSpan = node.parentNode.getClientRects()[0];
  2432. if (rSpan)
  2433. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  2434. else
  2435. rect = nullRect;
  2436. }
  2437. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2438. var mid = (rtop + rbot) / 2;
  2439. var heights = prepared.view.measure.heights;
  2440. for (var i = 0; i < heights.length - 1; i++)
  2441. if (mid < heights[i]) break;
  2442. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2443. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2444. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2445. top: top, bottom: bot};
  2446. if (!rect.left && !rect.right) result.bogus = true;
  2447. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2448. return result;
  2449. }
  2450. // Work around problem with bounding client rects on ranges being
  2451. // returned incorrectly when zoomed on IE10 and below.
  2452. function maybeUpdateRectForZooming(measure, rect) {
  2453. if (!window.screen || screen.logicalXDPI == null ||
  2454. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2455. return rect;
  2456. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2457. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2458. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2459. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  2460. }
  2461. function clearLineMeasurementCacheFor(lineView) {
  2462. if (lineView.measure) {
  2463. lineView.measure.cache = {};
  2464. lineView.measure.heights = null;
  2465. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2466. lineView.measure.caches[i] = {};
  2467. }
  2468. }
  2469. function clearLineMeasurementCache(cm) {
  2470. cm.display.externalMeasure = null;
  2471. removeChildren(cm.display.lineMeasure);
  2472. for (var i = 0; i < cm.display.view.length; i++)
  2473. clearLineMeasurementCacheFor(cm.display.view[i]);
  2474. }
  2475. function clearCaches(cm) {
  2476. clearLineMeasurementCache(cm);
  2477. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2478. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2479. cm.display.lineNumChars = null;
  2480. }
  2481. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2482. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2483. // Converts a {top, bottom, left, right} box from line-local
  2484. // coordinates into another coordinate system. Context may be one of
  2485. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2486. // or "page".
  2487. function intoCoordSystem(cm, lineObj, rect, context) {
  2488. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2489. var size = widgetHeight(lineObj.widgets[i]);
  2490. rect.top += size; rect.bottom += size;
  2491. }
  2492. if (context == "line") return rect;
  2493. if (!context) context = "local";
  2494. var yOff = heightAtLine(lineObj);
  2495. if (context == "local") yOff += paddingTop(cm.display);
  2496. else yOff -= cm.display.viewOffset;
  2497. if (context == "page" || context == "window") {
  2498. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2499. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2500. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2501. rect.left += xOff; rect.right += xOff;
  2502. }
  2503. rect.top += yOff; rect.bottom += yOff;
  2504. return rect;
  2505. }
  2506. // Coverts a box from "div" coords to another coordinate system.
  2507. // Context may be "window", "page", "div", or "local"/null.
  2508. function fromCoordSystem(cm, coords, context) {
  2509. if (context == "div") return coords;
  2510. var left = coords.left, top = coords.top;
  2511. // First move into "page" coordinate system
  2512. if (context == "page") {
  2513. left -= pageScrollX();
  2514. top -= pageScrollY();
  2515. } else if (context == "local" || !context) {
  2516. var localBox = cm.display.sizer.getBoundingClientRect();
  2517. left += localBox.left;
  2518. top += localBox.top;
  2519. }
  2520. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2521. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  2522. }
  2523. function charCoords(cm, pos, context, lineObj, bias) {
  2524. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2525. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2526. }
  2527. // Returns a box for a given cursor position, which may have an
  2528. // 'other' property containing the position of the secondary cursor
  2529. // on a bidi boundary.
  2530. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2531. lineObj = lineObj || getLine(cm.doc, pos.line);
  2532. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2533. function get(ch, right) {
  2534. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2535. if (right) m.left = m.right; else m.right = m.left;
  2536. return intoCoordSystem(cm, lineObj, m, context);
  2537. }
  2538. function getBidi(ch, partPos) {
  2539. var part = order[partPos], right = part.level % 2;
  2540. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2541. part = order[--partPos];
  2542. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2543. right = true;
  2544. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2545. part = order[++partPos];
  2546. ch = bidiLeft(part) - part.level % 2;
  2547. right = false;
  2548. }
  2549. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2550. return get(ch, right);
  2551. }
  2552. var order = getOrder(lineObj), ch = pos.ch;
  2553. if (!order) return get(ch);
  2554. var partPos = getBidiPartAt(order, ch);
  2555. var val = getBidi(ch, partPos);
  2556. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2557. return val;
  2558. }
  2559. // Used to cheaply estimate the coordinates for a position. Used for
  2560. // intermediate scroll updates.
  2561. function estimateCoords(cm, pos) {
  2562. var left = 0, pos = clipPos(cm.doc, pos);
  2563. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2564. var lineObj = getLine(cm.doc, pos.line);
  2565. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2566. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  2567. }
  2568. // Positions returned by coordsChar contain some extra information.
  2569. // xRel is the relative x position of the input coordinates compared
  2570. // to the found position (so xRel > 0 means the coordinates are to
  2571. // the right of the character position, for example). When outside
  2572. // is true, that means the coordinates lie outside the line's
  2573. // vertical range.
  2574. function PosWithInfo(line, ch, outside, xRel) {
  2575. var pos = Pos(line, ch);
  2576. pos.xRel = xRel;
  2577. if (outside) pos.outside = true;
  2578. return pos;
  2579. }
  2580. // Compute the character position closest to the given coordinates.
  2581. // Input must be lineSpace-local ("div" coordinate system).
  2582. function coordsChar(cm, x, y) {
  2583. var doc = cm.doc;
  2584. y += cm.display.viewOffset;
  2585. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2586. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2587. if (lineN > last)
  2588. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2589. if (x < 0) x = 0;
  2590. var lineObj = getLine(doc, lineN);
  2591. for (;;) {
  2592. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2593. var merged = collapsedSpanAtEnd(lineObj);
  2594. var mergedPos = merged && merged.find(0, true);
  2595. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2596. lineN = lineNo(lineObj = mergedPos.to.line);
  2597. else
  2598. return found;
  2599. }
  2600. }
  2601. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2602. var innerOff = y - heightAtLine(lineObj);
  2603. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2604. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2605. function getX(ch) {
  2606. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2607. wrongLine = true;
  2608. if (innerOff > sp.bottom) return sp.left - adjust;
  2609. else if (innerOff < sp.top) return sp.left + adjust;
  2610. else wrongLine = false;
  2611. return sp.left;
  2612. }
  2613. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2614. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2615. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2616. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2617. // Do a binary search between these bounds.
  2618. for (;;) {
  2619. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2620. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2621. var xDiff = x - (ch == from ? fromX : toX);
  2622. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  2623. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  2624. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2625. return pos;
  2626. }
  2627. var step = Math.ceil(dist / 2), middle = from + step;
  2628. if (bidi) {
  2629. middle = from;
  2630. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2631. }
  2632. var middleX = getX(middle);
  2633. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  2634. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  2635. }
  2636. }
  2637. var measureText;
  2638. // Compute the default text height.
  2639. function textHeight(display) {
  2640. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2641. if (measureText == null) {
  2642. measureText = elt("pre");
  2643. // Measure a bunch of lines, for browsers that compute
  2644. // fractional heights.
  2645. for (var i = 0; i < 49; ++i) {
  2646. measureText.appendChild(document.createTextNode("x"));
  2647. measureText.appendChild(elt("br"));
  2648. }
  2649. measureText.appendChild(document.createTextNode("x"));
  2650. }
  2651. removeChildrenAndAdd(display.measure, measureText);
  2652. var height = measureText.offsetHeight / 50;
  2653. if (height > 3) display.cachedTextHeight = height;
  2654. removeChildren(display.measure);
  2655. return height || 1;
  2656. }
  2657. // Compute the default character width.
  2658. function charWidth(display) {
  2659. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2660. var anchor = elt("span", "xxxxxxxxxx");
  2661. var pre = elt("pre", [anchor]);
  2662. removeChildrenAndAdd(display.measure, pre);
  2663. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2664. if (width > 2) display.cachedCharWidth = width;
  2665. return width || 10;
  2666. }
  2667. // OPERATIONS
  2668. // Operations are used to wrap a series of changes to the editor
  2669. // state in such a way that each change won't have to update the
  2670. // cursor and display (which would be awkward, slow, and
  2671. // error-prone). Instead, display updates are batched and then all
  2672. // combined and executed at once.
  2673. var operationGroup = null;
  2674. var nextOpId = 0;
  2675. // Start a new operation.
  2676. function startOperation(cm) {
  2677. cm.curOp = {
  2678. cm: cm,
  2679. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2680. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2681. forceUpdate: false, // Used to force a redraw
  2682. updateInput: null, // Whether to reset the input textarea
  2683. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2684. changeObjs: null, // Accumulated changes, for firing change events
  2685. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2686. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2687. selectionChanged: false, // Whether the selection needs to be redrawn
  2688. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2689. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2690. scrollToPos: null, // Used to scroll to a specific position
  2691. focus: false,
  2692. id: ++nextOpId // Unique ID
  2693. };
  2694. if (operationGroup) {
  2695. operationGroup.ops.push(cm.curOp);
  2696. } else {
  2697. cm.curOp.ownsGroup = operationGroup = {
  2698. ops: [cm.curOp],
  2699. delayedCallbacks: []
  2700. };
  2701. }
  2702. }
  2703. function fireCallbacksForOps(group) {
  2704. // Calls delayed callbacks and cursorActivity handlers until no
  2705. // new ones appear
  2706. var callbacks = group.delayedCallbacks, i = 0;
  2707. do {
  2708. for (; i < callbacks.length; i++)
  2709. callbacks[i].call(null);
  2710. for (var j = 0; j < group.ops.length; j++) {
  2711. var op = group.ops[j];
  2712. if (op.cursorActivityHandlers)
  2713. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2714. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  2715. }
  2716. } while (i < callbacks.length);
  2717. }
  2718. // Finish an operation, updating the display and signalling delayed events
  2719. function endOperation(cm) {
  2720. var op = cm.curOp, group = op.ownsGroup;
  2721. if (!group) return;
  2722. try { fireCallbacksForOps(group); }
  2723. finally {
  2724. operationGroup = null;
  2725. for (var i = 0; i < group.ops.length; i++)
  2726. group.ops[i].cm.curOp = null;
  2727. endOperations(group);
  2728. }
  2729. }
  2730. // The DOM updates done when an operation finishes are batched so
  2731. // that the minimum number of relayouts are required.
  2732. function endOperations(group) {
  2733. var ops = group.ops;
  2734. for (var i = 0; i < ops.length; i++) // Read DOM
  2735. endOperation_R1(ops[i]);
  2736. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2737. endOperation_W1(ops[i]);
  2738. for (var i = 0; i < ops.length; i++) // Read DOM
  2739. endOperation_R2(ops[i]);
  2740. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2741. endOperation_W2(ops[i]);
  2742. for (var i = 0; i < ops.length; i++) // Read DOM
  2743. endOperation_finish(ops[i]);
  2744. }
  2745. function endOperation_R1(op) {
  2746. var cm = op.cm, display = cm.display;
  2747. maybeClipScrollbars(cm);
  2748. if (op.updateMaxLine) findMaxLine(cm);
  2749. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2750. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2751. op.scrollToPos.to.line >= display.viewTo) ||
  2752. display.maxLineChanged && cm.options.lineWrapping;
  2753. op.update = op.mustUpdate &&
  2754. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  2755. }
  2756. function endOperation_W1(op) {
  2757. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2758. }
  2759. function endOperation_R2(op) {
  2760. var cm = op.cm, display = cm.display;
  2761. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2762. op.barMeasure = measureForScrollbars(cm);
  2763. // If the max line changed since it was last measured, measure it,
  2764. // and ensure the document's width matches it.
  2765. // updateDisplay_W2 will use these properties to do the actual resizing
  2766. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2767. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2768. cm.display.sizerWidth = op.adjustWidthTo;
  2769. op.barMeasure.scrollWidth =
  2770. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2771. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2772. }
  2773. if (op.updatedDisplay || op.selectionChanged)
  2774. op.preparedSelection = display.input.prepareSelection();
  2775. }
  2776. function endOperation_W2(op) {
  2777. var cm = op.cm;
  2778. if (op.adjustWidthTo != null) {
  2779. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2780. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2781. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2782. cm.display.maxLineChanged = false;
  2783. }
  2784. if (op.preparedSelection)
  2785. cm.display.input.showSelection(op.preparedSelection);
  2786. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2787. updateScrollbars(cm, op.barMeasure);
  2788. if (op.updatedDisplay)
  2789. setDocumentHeight(cm, op.barMeasure);
  2790. if (op.selectionChanged) restartBlink(cm);
  2791. if (cm.state.focused && op.updateInput)
  2792. cm.display.input.reset(op.typing);
  2793. if (op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()))
  2794. ensureFocus(op.cm);
  2795. }
  2796. function endOperation_finish(op) {
  2797. var cm = op.cm, display = cm.display, doc = cm.doc;
  2798. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2799. // Abort mouse wheel delta measurement, when scrolling explicitly
  2800. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2801. display.wheelStartX = display.wheelStartY = null;
  2802. // Propagate the scroll position to the actual DOM scroller
  2803. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2804. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2805. display.scrollbars.setScrollTop(doc.scrollTop);
  2806. display.scroller.scrollTop = doc.scrollTop;
  2807. }
  2808. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2809. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  2810. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2811. display.scroller.scrollLeft = doc.scrollLeft;
  2812. alignHorizontally(cm);
  2813. }
  2814. // If we need to scroll a specific position into view, do so.
  2815. if (op.scrollToPos) {
  2816. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2817. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2818. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2819. }
  2820. // Fire events for markers that are hidden/unidden by editing or
  2821. // undoing
  2822. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2823. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2824. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2825. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2826. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2827. if (display.wrapper.offsetHeight)
  2828. doc.scrollTop = cm.display.scroller.scrollTop;
  2829. // Fire change events, and delayed event handlers
  2830. if (op.changeObjs)
  2831. signal(cm, "changes", cm, op.changeObjs);
  2832. if (op.update)
  2833. op.update.finish();
  2834. }
  2835. // Run the given function in an operation
  2836. function runInOp(cm, f) {
  2837. if (cm.curOp) return f();
  2838. startOperation(cm);
  2839. try { return f(); }
  2840. finally { endOperation(cm); }
  2841. }
  2842. // Wraps a function in an operation. Returns the wrapped function.
  2843. function operation(cm, f) {
  2844. return function() {
  2845. if (cm.curOp) return f.apply(cm, arguments);
  2846. startOperation(cm);
  2847. try { return f.apply(cm, arguments); }
  2848. finally { endOperation(cm); }
  2849. };
  2850. }
  2851. // Used to add methods to editor and doc instances, wrapping them in
  2852. // operations.
  2853. function methodOp(f) {
  2854. return function() {
  2855. if (this.curOp) return f.apply(this, arguments);
  2856. startOperation(this);
  2857. try { return f.apply(this, arguments); }
  2858. finally { endOperation(this); }
  2859. };
  2860. }
  2861. function docMethodOp(f) {
  2862. return function() {
  2863. var cm = this.cm;
  2864. if (!cm || cm.curOp) return f.apply(this, arguments);
  2865. startOperation(cm);
  2866. try { return f.apply(this, arguments); }
  2867. finally { endOperation(cm); }
  2868. };
  2869. }
  2870. // VIEW TRACKING
  2871. // These objects are used to represent the visible (currently drawn)
  2872. // part of the document. A LineView may correspond to multiple
  2873. // logical lines, if those are connected by collapsed ranges.
  2874. function LineView(doc, line, lineN) {
  2875. // The starting line
  2876. this.line = line;
  2877. // Continuing lines, if any
  2878. this.rest = visualLineContinued(line);
  2879. // Number of logical lines in this visual line
  2880. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2881. this.node = this.text = null;
  2882. this.hidden = lineIsHidden(doc, line);
  2883. }
  2884. // Create a range of LineView objects for the given lines.
  2885. function buildViewArray(cm, from, to) {
  2886. var array = [], nextPos;
  2887. for (var pos = from; pos < to; pos = nextPos) {
  2888. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2889. nextPos = pos + view.size;
  2890. array.push(view);
  2891. }
  2892. return array;
  2893. }
  2894. // Updates the display.view data structure for a given change to the
  2895. // document. From and to are in pre-change coordinates. Lendiff is
  2896. // the amount of lines added or subtracted by the change. This is
  2897. // used for changes that span multiple lines, or change the way
  2898. // lines are divided into visual lines. regLineChange (below)
  2899. // registers single-line changes.
  2900. function regChange(cm, from, to, lendiff) {
  2901. if (from == null) from = cm.doc.first;
  2902. if (to == null) to = cm.doc.first + cm.doc.size;
  2903. if (!lendiff) lendiff = 0;
  2904. var display = cm.display;
  2905. if (lendiff && to < display.viewTo &&
  2906. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2907. display.updateLineNumbers = from;
  2908. cm.curOp.viewChanged = true;
  2909. if (from >= display.viewTo) { // Change after
  2910. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2911. resetView(cm);
  2912. } else if (to <= display.viewFrom) { // Change before
  2913. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2914. resetView(cm);
  2915. } else {
  2916. display.viewFrom += lendiff;
  2917. display.viewTo += lendiff;
  2918. }
  2919. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2920. resetView(cm);
  2921. } else if (from <= display.viewFrom) { // Top overlap
  2922. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2923. if (cut) {
  2924. display.view = display.view.slice(cut.index);
  2925. display.viewFrom = cut.lineN;
  2926. display.viewTo += lendiff;
  2927. } else {
  2928. resetView(cm);
  2929. }
  2930. } else if (to >= display.viewTo) { // Bottom overlap
  2931. var cut = viewCuttingPoint(cm, from, from, -1);
  2932. if (cut) {
  2933. display.view = display.view.slice(0, cut.index);
  2934. display.viewTo = cut.lineN;
  2935. } else {
  2936. resetView(cm);
  2937. }
  2938. } else { // Gap in the middle
  2939. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2940. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2941. if (cutTop && cutBot) {
  2942. display.view = display.view.slice(0, cutTop.index)
  2943. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2944. .concat(display.view.slice(cutBot.index));
  2945. display.viewTo += lendiff;
  2946. } else {
  2947. resetView(cm);
  2948. }
  2949. }
  2950. var ext = display.externalMeasured;
  2951. if (ext) {
  2952. if (to < ext.lineN)
  2953. ext.lineN += lendiff;
  2954. else if (from < ext.lineN + ext.size)
  2955. display.externalMeasured = null;
  2956. }
  2957. }
  2958. // Register a change to a single line. Type must be one of "text",
  2959. // "gutter", "class", "widget"
  2960. function regLineChange(cm, line, type) {
  2961. cm.curOp.viewChanged = true;
  2962. var display = cm.display, ext = cm.display.externalMeasured;
  2963. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2964. display.externalMeasured = null;
  2965. if (line < display.viewFrom || line >= display.viewTo) return;
  2966. var lineView = display.view[findViewIndex(cm, line)];
  2967. if (lineView.node == null) return;
  2968. var arr = lineView.changes || (lineView.changes = []);
  2969. if (indexOf(arr, type) == -1) arr.push(type);
  2970. }
  2971. // Clear the view.
  2972. function resetView(cm) {
  2973. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2974. cm.display.view = [];
  2975. cm.display.viewOffset = 0;
  2976. }
  2977. // Find the view element corresponding to a given line. Return null
  2978. // when the line isn't visible.
  2979. function findViewIndex(cm, n) {
  2980. if (n >= cm.display.viewTo) return null;
  2981. n -= cm.display.viewFrom;
  2982. if (n < 0) return null;
  2983. var view = cm.display.view;
  2984. for (var i = 0; i < view.length; i++) {
  2985. n -= view[i].size;
  2986. if (n < 0) return i;
  2987. }
  2988. }
  2989. function viewCuttingPoint(cm, oldN, newN, dir) {
  2990. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2991. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2992. return {index: index, lineN: newN};
  2993. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2994. n += view[i].size;
  2995. if (n != oldN) {
  2996. if (dir > 0) {
  2997. if (index == view.length - 1) return null;
  2998. diff = (n + view[index].size) - oldN;
  2999. index++;
  3000. } else {
  3001. diff = n - oldN;
  3002. }
  3003. oldN += diff; newN += diff;
  3004. }
  3005. while (visualLineNo(cm.doc, newN) != newN) {
  3006. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  3007. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3008. index += dir;
  3009. }
  3010. return {index: index, lineN: newN};
  3011. }
  3012. // Force the view to cover a given range, adding empty view element
  3013. // or clipping off existing ones as needed.
  3014. function adjustView(cm, from, to) {
  3015. var display = cm.display, view = display.view;
  3016. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3017. display.view = buildViewArray(cm, from, to);
  3018. display.viewFrom = from;
  3019. } else {
  3020. if (display.viewFrom > from)
  3021. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  3022. else if (display.viewFrom < from)
  3023. display.view = display.view.slice(findViewIndex(cm, from));
  3024. display.viewFrom = from;
  3025. if (display.viewTo < to)
  3026. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  3027. else if (display.viewTo > to)
  3028. display.view = display.view.slice(0, findViewIndex(cm, to));
  3029. }
  3030. display.viewTo = to;
  3031. }
  3032. // Count the number of lines in the view whose DOM representation is
  3033. // out of date (or nonexistent).
  3034. function countDirtyView(cm) {
  3035. var view = cm.display.view, dirty = 0;
  3036. for (var i = 0; i < view.length; i++) {
  3037. var lineView = view[i];
  3038. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  3039. }
  3040. return dirty;
  3041. }
  3042. // EVENT HANDLERS
  3043. // Attach the necessary event handlers when initializing the editor
  3044. function registerEventHandlers(cm) {
  3045. var d = cm.display;
  3046. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  3047. // Older IE's will not fire a second mousedown for a double click
  3048. if (ie && ie_version < 11)
  3049. on(d.scroller, "dblclick", operation(cm, function(e) {
  3050. if (signalDOMEvent(cm, e)) return;
  3051. var pos = posFromMouse(cm, e);
  3052. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  3053. e_preventDefault(e);
  3054. var word = cm.findWordAt(pos);
  3055. extendSelection(cm.doc, word.anchor, word.head);
  3056. }));
  3057. else
  3058. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  3059. // Some browsers fire contextmenu *after* opening the menu, at
  3060. // which point we can't mess with it anymore. Context menu is
  3061. // handled in onMouseDown for these browsers.
  3062. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  3063. // Used to suppress mouse event handling when a touch happens
  3064. var touchFinished, prevTouch = {end: 0};
  3065. function finishTouch() {
  3066. if (d.activeTouch) {
  3067. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  3068. prevTouch = d.activeTouch;
  3069. prevTouch.end = +new Date;
  3070. }
  3071. };
  3072. function isMouseLikeTouchEvent(e) {
  3073. if (e.touches.length != 1) return false;
  3074. var touch = e.touches[0];
  3075. return touch.radiusX <= 1 && touch.radiusY <= 1;
  3076. }
  3077. function farAway(touch, other) {
  3078. if (other.left == null) return true;
  3079. var dx = other.left - touch.left, dy = other.top - touch.top;
  3080. return dx * dx + dy * dy > 20 * 20;
  3081. }
  3082. on(d.scroller, "touchstart", function(e) {
  3083. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  3084. clearTimeout(touchFinished);
  3085. var now = +new Date;
  3086. d.activeTouch = {start: now, moved: false,
  3087. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  3088. if (e.touches.length == 1) {
  3089. d.activeTouch.left = e.touches[0].pageX;
  3090. d.activeTouch.top = e.touches[0].pageY;
  3091. }
  3092. }
  3093. });
  3094. on(d.scroller, "touchmove", function() {
  3095. if (d.activeTouch) d.activeTouch.moved = true;
  3096. });
  3097. on(d.scroller, "touchend", function(e) {
  3098. var touch = d.activeTouch;
  3099. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3100. !touch.moved && new Date - touch.start < 300) {
  3101. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3102. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3103. range = new Range(pos, pos);
  3104. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3105. range = cm.findWordAt(pos);
  3106. else // Triple tap
  3107. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3108. cm.setSelection(range.anchor, range.head);
  3109. cm.focus();
  3110. e_preventDefault(e);
  3111. }
  3112. finishTouch();
  3113. });
  3114. on(d.scroller, "touchcancel", finishTouch);
  3115. // Sync scrolling between fake scrollbars and real scrollable
  3116. // area, ensure viewport is updated when scrolling.
  3117. on(d.scroller, "scroll", function() {
  3118. if (d.scroller.clientHeight) {
  3119. setScrollTop(cm, d.scroller.scrollTop);
  3120. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3121. signal(cm, "scroll", cm);
  3122. }
  3123. });
  3124. // Listen to wheel events in order to try and update the viewport on time.
  3125. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  3126. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  3127. // Prevent wrapper from ever scrolling
  3128. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3129. d.dragFunctions = {
  3130. enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  3131. over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  3132. start: function(e){onDragStart(cm, e);},
  3133. drop: operation(cm, onDrop),
  3134. leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  3135. };
  3136. var inp = d.input.getField();
  3137. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  3138. on(inp, "keydown", operation(cm, onKeyDown));
  3139. on(inp, "keypress", operation(cm, onKeyPress));
  3140. on(inp, "focus", bind(onFocus, cm));
  3141. on(inp, "blur", bind(onBlur, cm));
  3142. }
  3143. function dragDropChanged(cm, value, old) {
  3144. var wasOn = old && old != CodeMirror.Init;
  3145. if (!value != !wasOn) {
  3146. var funcs = cm.display.dragFunctions;
  3147. var toggle = value ? on : off;
  3148. toggle(cm.display.scroller, "dragstart", funcs.start);
  3149. toggle(cm.display.scroller, "dragenter", funcs.enter);
  3150. toggle(cm.display.scroller, "dragover", funcs.over);
  3151. toggle(cm.display.scroller, "dragleave", funcs.leave);
  3152. toggle(cm.display.scroller, "drop", funcs.drop);
  3153. }
  3154. }
  3155. // Called when the window resizes
  3156. function onResize(cm) {
  3157. var d = cm.display;
  3158. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3159. return;
  3160. // Might be a text scaling operation, clear size caches.
  3161. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3162. d.scrollbarsClipped = false;
  3163. cm.setSize();
  3164. }
  3165. // MOUSE EVENTS
  3166. // Return true when the given mouse event happened in a widget
  3167. function eventInWidget(display, e) {
  3168. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3169. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3170. (n.parentNode == display.sizer && n != display.mover))
  3171. return true;
  3172. }
  3173. }
  3174. // Given a mouse event, find the corresponding position. If liberal
  3175. // is false, it checks whether a gutter or scrollbar was clicked,
  3176. // and returns null if it was. forRect is used by rectangular
  3177. // selections, and tries to estimate a character position even for
  3178. // coordinates beyond the right of the text.
  3179. function posFromMouse(cm, e, liberal, forRect) {
  3180. var display = cm.display;
  3181. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3182. var x, y, space = display.lineSpace.getBoundingClientRect();
  3183. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3184. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3185. catch (e) { return null; }
  3186. var coords = coordsChar(cm, x, y), line;
  3187. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3188. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3189. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3190. }
  3191. return coords;
  3192. }
  3193. // A mouse down can be a single click, double click, triple click,
  3194. // start of selection drag, start of text drag, new cursor
  3195. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3196. // middle-click-paste. Or it might be a click on something we should
  3197. // not interfere with, such as a scrollbar or widget.
  3198. function onMouseDown(e) {
  3199. var cm = this, display = cm.display;
  3200. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
  3201. display.shift = e.shiftKey;
  3202. if (eventInWidget(display, e)) {
  3203. if (!webkit) {
  3204. // Briefly turn off draggability, to allow widgets to do
  3205. // normal dragging things.
  3206. display.scroller.draggable = false;
  3207. setTimeout(function(){display.scroller.draggable = true;}, 100);
  3208. }
  3209. return;
  3210. }
  3211. if (clickInGutter(cm, e)) return;
  3212. var start = posFromMouse(cm, e);
  3213. window.focus();
  3214. switch (e_button(e)) {
  3215. case 1:
  3216. // #3261: make sure, that we're not starting a second selection
  3217. if (cm.state.selectingText)
  3218. cm.state.selectingText(e);
  3219. else if (start)
  3220. leftButtonDown(cm, e, start);
  3221. else if (e_target(e) == display.scroller)
  3222. e_preventDefault(e);
  3223. break;
  3224. case 2:
  3225. if (webkit) cm.state.lastMiddleDown = +new Date;
  3226. if (start) extendSelection(cm.doc, start);
  3227. setTimeout(function() {display.input.focus();}, 20);
  3228. e_preventDefault(e);
  3229. break;
  3230. case 3:
  3231. if (captureRightClick) onContextMenu(cm, e);
  3232. else delayBlurEvent(cm);
  3233. break;
  3234. }
  3235. }
  3236. var lastClick, lastDoubleClick;
  3237. function leftButtonDown(cm, e, start) {
  3238. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3239. else cm.curOp.focus = activeElt();
  3240. var now = +new Date, type;
  3241. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3242. type = "triple";
  3243. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3244. type = "double";
  3245. lastDoubleClick = {time: now, pos: start};
  3246. } else {
  3247. type = "single";
  3248. lastClick = {time: now, pos: start};
  3249. }
  3250. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3251. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  3252. type == "single" && (contained = sel.contains(start)) > -1 &&
  3253. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  3254. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  3255. leftButtonStartDrag(cm, e, start, modifier);
  3256. else
  3257. leftButtonSelect(cm, e, start, type, modifier);
  3258. }
  3259. // Start a text drag. When it ends, see if any dragging actually
  3260. // happen, and treat as a click if it didn't.
  3261. function leftButtonStartDrag(cm, e, start, modifier) {
  3262. var display = cm.display, startTime = +new Date;
  3263. var dragEnd = operation(cm, function(e2) {
  3264. if (webkit) display.scroller.draggable = false;
  3265. cm.state.draggingText = false;
  3266. off(document, "mouseup", dragEnd);
  3267. off(display.scroller, "drop", dragEnd);
  3268. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3269. e_preventDefault(e2);
  3270. if (!modifier && +new Date - 200 < startTime)
  3271. extendSelection(cm.doc, start);
  3272. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  3273. if (webkit || ie && ie_version == 9)
  3274. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  3275. else
  3276. display.input.focus();
  3277. }
  3278. });
  3279. // Let the drag handler handle this.
  3280. if (webkit) display.scroller.draggable = true;
  3281. cm.state.draggingText = dragEnd;
  3282. // IE's approach to draggable
  3283. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3284. on(document, "mouseup", dragEnd);
  3285. on(display.scroller, "drop", dragEnd);
  3286. }
  3287. // Normal selection, as opposed to text dragging.
  3288. function leftButtonSelect(cm, e, start, type, addNew) {
  3289. var display = cm.display, doc = cm.doc;
  3290. e_preventDefault(e);
  3291. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3292. if (addNew && !e.shiftKey) {
  3293. ourIndex = doc.sel.contains(start);
  3294. if (ourIndex > -1)
  3295. ourRange = ranges[ourIndex];
  3296. else
  3297. ourRange = new Range(start, start);
  3298. } else {
  3299. ourRange = doc.sel.primary();
  3300. ourIndex = doc.sel.primIndex;
  3301. }
  3302. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  3303. type = "rect";
  3304. if (!addNew) ourRange = new Range(start, start);
  3305. start = posFromMouse(cm, e, true, true);
  3306. ourIndex = -1;
  3307. } else if (type == "double") {
  3308. var word = cm.findWordAt(start);
  3309. if (cm.display.shift || doc.extend)
  3310. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3311. else
  3312. ourRange = word;
  3313. } else if (type == "triple") {
  3314. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3315. if (cm.display.shift || doc.extend)
  3316. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3317. else
  3318. ourRange = line;
  3319. } else {
  3320. ourRange = extendRange(doc, ourRange, start);
  3321. }
  3322. if (!addNew) {
  3323. ourIndex = 0;
  3324. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3325. startSel = doc.sel;
  3326. } else if (ourIndex == -1) {
  3327. ourIndex = ranges.length;
  3328. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3329. {scroll: false, origin: "*mouse"});
  3330. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  3331. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  3332. {scroll: false, origin: "*mouse"});
  3333. startSel = doc.sel;
  3334. } else {
  3335. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3336. }
  3337. var lastPos = start;
  3338. function extendTo(pos) {
  3339. if (cmp(lastPos, pos) == 0) return;
  3340. lastPos = pos;
  3341. if (type == "rect") {
  3342. var ranges = [], tabSize = cm.options.tabSize;
  3343. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3344. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3345. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3346. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3347. line <= end; line++) {
  3348. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3349. if (left == right)
  3350. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3351. else if (text.length > leftPos)
  3352. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3353. }
  3354. if (!ranges.length) ranges.push(new Range(start, start));
  3355. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3356. {origin: "*mouse", scroll: false});
  3357. cm.scrollIntoView(pos);
  3358. } else {
  3359. var oldRange = ourRange;
  3360. var anchor = oldRange.anchor, head = pos;
  3361. if (type != "single") {
  3362. if (type == "double")
  3363. var range = cm.findWordAt(pos);
  3364. else
  3365. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3366. if (cmp(range.anchor, anchor) > 0) {
  3367. head = range.head;
  3368. anchor = minPos(oldRange.from(), range.anchor);
  3369. } else {
  3370. head = range.anchor;
  3371. anchor = maxPos(oldRange.to(), range.head);
  3372. }
  3373. }
  3374. var ranges = startSel.ranges.slice(0);
  3375. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3376. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3377. }
  3378. }
  3379. var editorSize = display.wrapper.getBoundingClientRect();
  3380. // Used to ensure timeout re-tries don't fire when another extend
  3381. // happened in the meantime (clearTimeout isn't reliable -- at
  3382. // least on Chrome, the timeouts still happen even when cleared,
  3383. // if the clear happens after their scheduled firing time).
  3384. var counter = 0;
  3385. function extend(e) {
  3386. var curCount = ++counter;
  3387. var cur = posFromMouse(cm, e, true, type == "rect");
  3388. if (!cur) return;
  3389. if (cmp(cur, lastPos) != 0) {
  3390. cm.curOp.focus = activeElt();
  3391. extendTo(cur);
  3392. var visible = visibleLines(display, doc);
  3393. if (cur.line >= visible.to || cur.line < visible.from)
  3394. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  3395. } else {
  3396. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3397. if (outside) setTimeout(operation(cm, function() {
  3398. if (counter != curCount) return;
  3399. display.scroller.scrollTop += outside;
  3400. extend(e);
  3401. }), 50);
  3402. }
  3403. }
  3404. function done(e) {
  3405. cm.state.selectingText = false;
  3406. counter = Infinity;
  3407. e_preventDefault(e);
  3408. display.input.focus();
  3409. off(document, "mousemove", move);
  3410. off(document, "mouseup", up);
  3411. doc.history.lastSelOrigin = null;
  3412. }
  3413. var move = operation(cm, function(e) {
  3414. if (!e_button(e)) done(e);
  3415. else extend(e);
  3416. });
  3417. var up = operation(cm, done);
  3418. cm.state.selectingText = up;
  3419. on(document, "mousemove", move);
  3420. on(document, "mouseup", up);
  3421. }
  3422. // Determines whether an event happened in the gutter, and fires the
  3423. // handlers for the corresponding event.
  3424. function gutterEvent(cm, e, type, prevent) {
  3425. try { var mX = e.clientX, mY = e.clientY; }
  3426. catch(e) { return false; }
  3427. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3428. if (prevent) e_preventDefault(e);
  3429. var display = cm.display;
  3430. var lineBox = display.lineDiv.getBoundingClientRect();
  3431. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3432. mY -= lineBox.top - display.viewOffset;
  3433. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3434. var g = display.gutters.childNodes[i];
  3435. if (g && g.getBoundingClientRect().right >= mX) {
  3436. var line = lineAtHeight(cm.doc, mY);
  3437. var gutter = cm.options.gutters[i];
  3438. signal(cm, type, cm, line, gutter, e);
  3439. return e_defaultPrevented(e);
  3440. }
  3441. }
  3442. }
  3443. function clickInGutter(cm, e) {
  3444. return gutterEvent(cm, e, "gutterClick", true);
  3445. }
  3446. // Kludge to work around strange IE behavior where it'll sometimes
  3447. // re-fire a series of drag-related events right after the drop (#1551)
  3448. var lastDrop = 0;
  3449. function onDrop(e) {
  3450. var cm = this;
  3451. clearDragCursor(cm);
  3452. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3453. return;
  3454. e_preventDefault(e);
  3455. if (ie) lastDrop = +new Date;
  3456. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3457. if (!pos || cm.isReadOnly()) return;
  3458. // Might be a file drop, in which case we simply extract the text
  3459. // and insert it.
  3460. if (files && files.length && window.FileReader && window.File) {
  3461. var n = files.length, text = Array(n), read = 0;
  3462. var loadFile = function(file, i) {
  3463. if (cm.options.allowDropFileTypes &&
  3464. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  3465. return;
  3466. var reader = new FileReader;
  3467. reader.onload = operation(cm, function() {
  3468. var content = reader.result;
  3469. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
  3470. text[i] = content;
  3471. if (++read == n) {
  3472. pos = clipPos(cm.doc, pos);
  3473. var change = {from: pos, to: pos,
  3474. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  3475. origin: "paste"};
  3476. makeChange(cm.doc, change);
  3477. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3478. }
  3479. });
  3480. reader.readAsText(file);
  3481. };
  3482. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3483. } else { // Normal drop
  3484. // Don't do a replace if the drop happened inside of the selected text.
  3485. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3486. cm.state.draggingText(e);
  3487. // Ensure the editor is re-focused
  3488. setTimeout(function() {cm.display.input.focus();}, 20);
  3489. return;
  3490. }
  3491. try {
  3492. var text = e.dataTransfer.getData("Text");
  3493. if (text) {
  3494. if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
  3495. var selected = cm.listSelections();
  3496. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3497. if (selected) for (var i = 0; i < selected.length; ++i)
  3498. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3499. cm.replaceSelection(text, "around", "paste");
  3500. cm.display.input.focus();
  3501. }
  3502. }
  3503. catch(e){}
  3504. }
  3505. }
  3506. function onDragStart(cm, e) {
  3507. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3508. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3509. e.dataTransfer.setData("Text", cm.getSelection());
  3510. e.dataTransfer.effectAllowed = "copyMove"
  3511. // Use dummy image instead of default browsers image.
  3512. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3513. if (e.dataTransfer.setDragImage && !safari) {
  3514. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3515. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3516. if (presto) {
  3517. img.width = img.height = 1;
  3518. cm.display.wrapper.appendChild(img);
  3519. // Force a relayout, or Opera won't use our image for some obscure reason
  3520. img._top = img.offsetTop;
  3521. }
  3522. e.dataTransfer.setDragImage(img, 0, 0);
  3523. if (presto) img.parentNode.removeChild(img);
  3524. }
  3525. }
  3526. function onDragOver(cm, e) {
  3527. var pos = posFromMouse(cm, e);
  3528. if (!pos) return;
  3529. var frag = document.createDocumentFragment();
  3530. drawSelectionCursor(cm, pos, frag);
  3531. if (!cm.display.dragCursor) {
  3532. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  3533. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  3534. }
  3535. removeChildrenAndAdd(cm.display.dragCursor, frag);
  3536. }
  3537. function clearDragCursor(cm) {
  3538. if (cm.display.dragCursor) {
  3539. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  3540. cm.display.dragCursor = null;
  3541. }
  3542. }
  3543. // SCROLL EVENTS
  3544. // Sync the scrollable area and scrollbars, ensure the viewport
  3545. // covers the visible area.
  3546. function setScrollTop(cm, val) {
  3547. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3548. cm.doc.scrollTop = val;
  3549. if (!gecko) updateDisplaySimple(cm, {top: val});
  3550. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3551. cm.display.scrollbars.setScrollTop(val);
  3552. if (gecko) updateDisplaySimple(cm);
  3553. startWorker(cm, 100);
  3554. }
  3555. // Sync scroller and scrollbar, ensure the gutter elements are
  3556. // aligned.
  3557. function setScrollLeft(cm, val, isScroller) {
  3558. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3559. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3560. cm.doc.scrollLeft = val;
  3561. alignHorizontally(cm);
  3562. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3563. cm.display.scrollbars.setScrollLeft(val);
  3564. }
  3565. // Since the delta values reported on mouse wheel events are
  3566. // unstandardized between browsers and even browser versions, and
  3567. // generally horribly unpredictable, this code starts by measuring
  3568. // the scroll effect that the first few mouse wheel events have,
  3569. // and, from that, detects the way it can convert deltas to pixel
  3570. // offsets afterwards.
  3571. //
  3572. // The reason we want to know the amount a wheel event will scroll
  3573. // is that it gives us a chance to update the display before the
  3574. // actual scrolling happens, reducing flickering.
  3575. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3576. // Fill in a browser-detected starting value on browsers where we
  3577. // know one. These don't have to be accurate -- the result of them
  3578. // being wrong would just be a slight flicker on the first wheel
  3579. // scroll (if it is large enough).
  3580. if (ie) wheelPixelsPerUnit = -.53;
  3581. else if (gecko) wheelPixelsPerUnit = 15;
  3582. else if (chrome) wheelPixelsPerUnit = -.7;
  3583. else if (safari) wheelPixelsPerUnit = -1/3;
  3584. var wheelEventDelta = function(e) {
  3585. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3586. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3587. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3588. else if (dy == null) dy = e.wheelDelta;
  3589. return {x: dx, y: dy};
  3590. };
  3591. CodeMirror.wheelEventPixels = function(e) {
  3592. var delta = wheelEventDelta(e);
  3593. delta.x *= wheelPixelsPerUnit;
  3594. delta.y *= wheelPixelsPerUnit;
  3595. return delta;
  3596. };
  3597. function onScrollWheel(cm, e) {
  3598. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3599. var display = cm.display, scroll = display.scroller;
  3600. // Quit if there's nothing to scroll here
  3601. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  3602. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  3603. if (!(dx && canScrollX || dy && canScrollY)) return;
  3604. // Webkit browsers on OS X abort momentum scrolls when the target
  3605. // of the scroll event is removed from the scrollable element.
  3606. // This hack (see related code in patchDisplay) makes sure the
  3607. // element is kept around.
  3608. if (dy && mac && webkit) {
  3609. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3610. for (var i = 0; i < view.length; i++) {
  3611. if (view[i].node == cur) {
  3612. cm.display.currentWheelTarget = cur;
  3613. break outer;
  3614. }
  3615. }
  3616. }
  3617. }
  3618. // On some browsers, horizontal scrolling will cause redraws to
  3619. // happen before the gutter has been realigned, causing it to
  3620. // wriggle around in a most unseemly way. When we have an
  3621. // estimated pixels/delta value, we just handle horizontal
  3622. // scrolling entirely here. It'll be slightly off from native, but
  3623. // better than glitching out.
  3624. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3625. if (dy && canScrollY)
  3626. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3627. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3628. // Only prevent default scrolling if vertical scrolling is
  3629. // actually possible. Otherwise, it causes vertical scroll
  3630. // jitter on OSX trackpads when deltaX is small and deltaY
  3631. // is large (issue #3579)
  3632. if (!dy || (dy && canScrollY))
  3633. e_preventDefault(e);
  3634. display.wheelStartX = null; // Abort measurement, if in progress
  3635. return;
  3636. }
  3637. // 'Project' the visible viewport to cover the area that is being
  3638. // scrolled into view (if we know enough to estimate it).
  3639. if (dy && wheelPixelsPerUnit != null) {
  3640. var pixels = dy * wheelPixelsPerUnit;
  3641. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3642. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3643. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3644. updateDisplaySimple(cm, {top: top, bottom: bot});
  3645. }
  3646. if (wheelSamples < 20) {
  3647. if (display.wheelStartX == null) {
  3648. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3649. display.wheelDX = dx; display.wheelDY = dy;
  3650. setTimeout(function() {
  3651. if (display.wheelStartX == null) return;
  3652. var movedX = scroll.scrollLeft - display.wheelStartX;
  3653. var movedY = scroll.scrollTop - display.wheelStartY;
  3654. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3655. (movedX && display.wheelDX && movedX / display.wheelDX);
  3656. display.wheelStartX = display.wheelStartY = null;
  3657. if (!sample) return;
  3658. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3659. ++wheelSamples;
  3660. }, 200);
  3661. } else {
  3662. display.wheelDX += dx; display.wheelDY += dy;
  3663. }
  3664. }
  3665. }
  3666. // KEY EVENTS
  3667. // Run a handler that was bound to a key.
  3668. function doHandleBinding(cm, bound, dropShift) {
  3669. if (typeof bound == "string") {
  3670. bound = commands[bound];
  3671. if (!bound) return false;
  3672. }
  3673. // Ensure previous input has been read, so that the handler sees a
  3674. // consistent view of the document
  3675. cm.display.input.ensurePolled();
  3676. var prevShift = cm.display.shift, done = false;
  3677. try {
  3678. if (cm.isReadOnly()) cm.state.suppressEdits = true;
  3679. if (dropShift) cm.display.shift = false;
  3680. done = bound(cm) != Pass;
  3681. } finally {
  3682. cm.display.shift = prevShift;
  3683. cm.state.suppressEdits = false;
  3684. }
  3685. return done;
  3686. }
  3687. function lookupKeyForEditor(cm, name, handle) {
  3688. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3689. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3690. if (result) return result;
  3691. }
  3692. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3693. || lookupKey(name, cm.options.keyMap, handle, cm);
  3694. }
  3695. var stopSeq = new Delayed;
  3696. function dispatchKey(cm, name, e, handle) {
  3697. var seq = cm.state.keySeq;
  3698. if (seq) {
  3699. if (isModifierKey(name)) return "handled";
  3700. stopSeq.set(50, function() {
  3701. if (cm.state.keySeq == seq) {
  3702. cm.state.keySeq = null;
  3703. cm.display.input.reset();
  3704. }
  3705. });
  3706. name = seq + " " + name;
  3707. }
  3708. var result = lookupKeyForEditor(cm, name, handle);
  3709. if (result == "multi")
  3710. cm.state.keySeq = name;
  3711. if (result == "handled")
  3712. signalLater(cm, "keyHandled", cm, name, e);
  3713. if (result == "handled" || result == "multi") {
  3714. e_preventDefault(e);
  3715. restartBlink(cm);
  3716. }
  3717. if (seq && !result && /\'$/.test(name)) {
  3718. e_preventDefault(e);
  3719. return true;
  3720. }
  3721. return !!result;
  3722. }
  3723. // Handle a key from the keydown event.
  3724. function handleKeyBinding(cm, e) {
  3725. var name = keyName(e, true);
  3726. if (!name) return false;
  3727. if (e.shiftKey && !cm.state.keySeq) {
  3728. // First try to resolve full name (including 'Shift-'). Failing
  3729. // that, see if there is a cursor-motion command (starting with
  3730. // 'go') bound to the keyname without 'Shift-'.
  3731. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3732. || dispatchKey(cm, name, e, function(b) {
  3733. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3734. return doHandleBinding(cm, b);
  3735. });
  3736. } else {
  3737. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3738. }
  3739. }
  3740. // Handle a key from the keypress event
  3741. function handleCharBinding(cm, e, ch) {
  3742. return dispatchKey(cm, "'" + ch + "'", e,
  3743. function(b) { return doHandleBinding(cm, b, true); });
  3744. }
  3745. var lastStoppedKey = null;
  3746. function onKeyDown(e) {
  3747. var cm = this;
  3748. cm.curOp.focus = activeElt();
  3749. if (signalDOMEvent(cm, e)) return;
  3750. // IE does strange things with escape.
  3751. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3752. var code = e.keyCode;
  3753. cm.display.shift = code == 16 || e.shiftKey;
  3754. var handled = handleKeyBinding(cm, e);
  3755. if (presto) {
  3756. lastStoppedKey = handled ? code : null;
  3757. // Opera has no cut event... we try to at least catch the key combo
  3758. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3759. cm.replaceSelection("", null, "cut");
  3760. }
  3761. // Turn mouse into crosshair when Alt is held on Mac.
  3762. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3763. showCrossHair(cm);
  3764. }
  3765. function showCrossHair(cm) {
  3766. var lineDiv = cm.display.lineDiv;
  3767. addClass(lineDiv, "CodeMirror-crosshair");
  3768. function up(e) {
  3769. if (e.keyCode == 18 || !e.altKey) {
  3770. rmClass(lineDiv, "CodeMirror-crosshair");
  3771. off(document, "keyup", up);
  3772. off(document, "mouseover", up);
  3773. }
  3774. }
  3775. on(document, "keyup", up);
  3776. on(document, "mouseover", up);
  3777. }
  3778. function onKeyUp(e) {
  3779. if (e.keyCode == 16) this.doc.sel.shift = false;
  3780. signalDOMEvent(this, e);
  3781. }
  3782. function onKeyPress(e) {
  3783. var cm = this;
  3784. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3785. var keyCode = e.keyCode, charCode = e.charCode;
  3786. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3787. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3788. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3789. if (handleCharBinding(cm, e, ch)) return;
  3790. cm.display.input.onKeyPress(e);
  3791. }
  3792. // FOCUS/BLUR EVENTS
  3793. function delayBlurEvent(cm) {
  3794. cm.state.delayingBlurEvent = true;
  3795. setTimeout(function() {
  3796. if (cm.state.delayingBlurEvent) {
  3797. cm.state.delayingBlurEvent = false;
  3798. onBlur(cm);
  3799. }
  3800. }, 100);
  3801. }
  3802. function onFocus(cm) {
  3803. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  3804. if (cm.options.readOnly == "nocursor") return;
  3805. if (!cm.state.focused) {
  3806. signal(cm, "focus", cm);
  3807. cm.state.focused = true;
  3808. addClass(cm.display.wrapper, "CodeMirror-focused");
  3809. // This test prevents this from firing when a context
  3810. // menu is closed (since the input reset would kill the
  3811. // select-all detection hack)
  3812. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3813. cm.display.input.reset();
  3814. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  3815. }
  3816. cm.display.input.receivedFocus();
  3817. }
  3818. restartBlink(cm);
  3819. }
  3820. function onBlur(cm) {
  3821. if (cm.state.delayingBlurEvent) return;
  3822. if (cm.state.focused) {
  3823. signal(cm, "blur", cm);
  3824. cm.state.focused = false;
  3825. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3826. }
  3827. clearInterval(cm.display.blinker);
  3828. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3829. }
  3830. // CONTEXT MENU HANDLING
  3831. // To make the context menu work, we need to briefly unhide the
  3832. // textarea (making it as unobtrusive as possible) to let the
  3833. // right-click take effect on it.
  3834. function onContextMenu(cm, e) {
  3835. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3836. if (signalDOMEvent(cm, e, "contextmenu")) return;
  3837. cm.display.input.onContextMenu(e);
  3838. }
  3839. function contextMenuInGutter(cm, e) {
  3840. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3841. return gutterEvent(cm, e, "gutterContextMenu", false);
  3842. }
  3843. // UPDATING
  3844. // Compute the position of the end of a change (its 'to' property
  3845. // refers to the pre-change end).
  3846. var changeEnd = CodeMirror.changeEnd = function(change) {
  3847. if (!change.text) return change.to;
  3848. return Pos(change.from.line + change.text.length - 1,
  3849. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3850. };
  3851. // Adjust a position to refer to the post-change position of the
  3852. // same text, or the end of the change if the change covers it.
  3853. function adjustForChange(pos, change) {
  3854. if (cmp(pos, change.from) < 0) return pos;
  3855. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3856. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3857. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3858. return Pos(line, ch);
  3859. }
  3860. function computeSelAfterChange(doc, change) {
  3861. var out = [];
  3862. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3863. var range = doc.sel.ranges[i];
  3864. out.push(new Range(adjustForChange(range.anchor, change),
  3865. adjustForChange(range.head, change)));
  3866. }
  3867. return normalizeSelection(out, doc.sel.primIndex);
  3868. }
  3869. function offsetPos(pos, old, nw) {
  3870. if (pos.line == old.line)
  3871. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3872. else
  3873. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3874. }
  3875. // Used by replaceSelections to allow moving the selection to the
  3876. // start or around the replaced test. Hint may be "start" or "around".
  3877. function computeReplacedSel(doc, changes, hint) {
  3878. var out = [];
  3879. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3880. for (var i = 0; i < changes.length; i++) {
  3881. var change = changes[i];
  3882. var from = offsetPos(change.from, oldPrev, newPrev);
  3883. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3884. oldPrev = change.to;
  3885. newPrev = to;
  3886. if (hint == "around") {
  3887. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3888. out[i] = new Range(inv ? to : from, inv ? from : to);
  3889. } else {
  3890. out[i] = new Range(from, from);
  3891. }
  3892. }
  3893. return new Selection(out, doc.sel.primIndex);
  3894. }
  3895. // Allow "beforeChange" event handlers to influence a change
  3896. function filterChange(doc, change, update) {
  3897. var obj = {
  3898. canceled: false,
  3899. from: change.from,
  3900. to: change.to,
  3901. text: change.text,
  3902. origin: change.origin,
  3903. cancel: function() { this.canceled = true; }
  3904. };
  3905. if (update) obj.update = function(from, to, text, origin) {
  3906. if (from) this.from = clipPos(doc, from);
  3907. if (to) this.to = clipPos(doc, to);
  3908. if (text) this.text = text;
  3909. if (origin !== undefined) this.origin = origin;
  3910. };
  3911. signal(doc, "beforeChange", doc, obj);
  3912. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3913. if (obj.canceled) return null;
  3914. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3915. }
  3916. // Apply a change to a document, and add it to the document's
  3917. // history, and propagating it to all linked documents.
  3918. function makeChange(doc, change, ignoreReadOnly) {
  3919. if (doc.cm) {
  3920. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3921. if (doc.cm.state.suppressEdits) return;
  3922. }
  3923. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3924. change = filterChange(doc, change, true);
  3925. if (!change) return;
  3926. }
  3927. // Possibly split or suppress the update based on the presence
  3928. // of read-only spans in its range.
  3929. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3930. if (split) {
  3931. for (var i = split.length - 1; i >= 0; --i)
  3932. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3933. } else {
  3934. makeChangeInner(doc, change);
  3935. }
  3936. }
  3937. function makeChangeInner(doc, change) {
  3938. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3939. var selAfter = computeSelAfterChange(doc, change);
  3940. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3941. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3942. var rebased = [];
  3943. linkedDocs(doc, function(doc, sharedHist) {
  3944. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3945. rebaseHist(doc.history, change);
  3946. rebased.push(doc.history);
  3947. }
  3948. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3949. });
  3950. }
  3951. // Revert a change stored in a document's history.
  3952. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3953. if (doc.cm && doc.cm.state.suppressEdits) return;
  3954. var hist = doc.history, event, selAfter = doc.sel;
  3955. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3956. // Verify that there is a useable event (so that ctrl-z won't
  3957. // needlessly clear selection events)
  3958. for (var i = 0; i < source.length; i++) {
  3959. event = source[i];
  3960. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3961. break;
  3962. }
  3963. if (i == source.length) return;
  3964. hist.lastOrigin = hist.lastSelOrigin = null;
  3965. for (;;) {
  3966. event = source.pop();
  3967. if (event.ranges) {
  3968. pushSelectionToHistory(event, dest);
  3969. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3970. setSelection(doc, event, {clearRedo: false});
  3971. return;
  3972. }
  3973. selAfter = event;
  3974. }
  3975. else break;
  3976. }
  3977. // Build up a reverse change object to add to the opposite history
  3978. // stack (redo when undoing, and vice versa).
  3979. var antiChanges = [];
  3980. pushSelectionToHistory(selAfter, dest);
  3981. dest.push({changes: antiChanges, generation: hist.generation});
  3982. hist.generation = event.generation || ++hist.maxGeneration;
  3983. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3984. for (var i = event.changes.length - 1; i >= 0; --i) {
  3985. var change = event.changes[i];
  3986. change.origin = type;
  3987. if (filter && !filterChange(doc, change, false)) {
  3988. source.length = 0;
  3989. return;
  3990. }
  3991. antiChanges.push(historyChangeFromChange(doc, change));
  3992. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3993. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3994. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  3995. var rebased = [];
  3996. // Propagate to the linked documents
  3997. linkedDocs(doc, function(doc, sharedHist) {
  3998. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3999. rebaseHist(doc.history, change);
  4000. rebased.push(doc.history);
  4001. }
  4002. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4003. });
  4004. }
  4005. }
  4006. // Sub-views need their line numbers shifted when text is added
  4007. // above or below them in the parent document.
  4008. function shiftDoc(doc, distance) {
  4009. if (distance == 0) return;
  4010. doc.first += distance;
  4011. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  4012. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  4013. Pos(range.head.line + distance, range.head.ch));
  4014. }), doc.sel.primIndex);
  4015. if (doc.cm) {
  4016. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4017. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4018. regLineChange(doc.cm, l, "gutter");
  4019. }
  4020. }
  4021. // More lower-level change function, handling only a single document
  4022. // (not linked ones).
  4023. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4024. if (doc.cm && !doc.cm.curOp)
  4025. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  4026. if (change.to.line < doc.first) {
  4027. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4028. return;
  4029. }
  4030. if (change.from.line > doc.lastLine()) return;
  4031. // Clip the change to the size of this doc
  4032. if (change.from.line < doc.first) {
  4033. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4034. shiftDoc(doc, shift);
  4035. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4036. text: [lst(change.text)], origin: change.origin};
  4037. }
  4038. var last = doc.lastLine();
  4039. if (change.to.line > last) {
  4040. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4041. text: [change.text[0]], origin: change.origin};
  4042. }
  4043. change.removed = getBetween(doc, change.from, change.to);
  4044. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  4045. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  4046. else updateDoc(doc, change, spans);
  4047. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4048. }
  4049. // Handle the interaction of a change to a document with the editor
  4050. // that this document is part of.
  4051. function makeChangeSingleDocInEditor(cm, change, spans) {
  4052. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4053. var recomputeMaxLength = false, checkWidthStart = from.line;
  4054. if (!cm.options.lineWrapping) {
  4055. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4056. doc.iter(checkWidthStart, to.line + 1, function(line) {
  4057. if (line == display.maxLine) {
  4058. recomputeMaxLength = true;
  4059. return true;
  4060. }
  4061. });
  4062. }
  4063. if (doc.sel.contains(change.from, change.to) > -1)
  4064. signalCursorActivity(cm);
  4065. updateDoc(doc, change, spans, estimateHeight(cm));
  4066. if (!cm.options.lineWrapping) {
  4067. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  4068. var len = lineLength(line);
  4069. if (len > display.maxLineLength) {
  4070. display.maxLine = line;
  4071. display.maxLineLength = len;
  4072. display.maxLineChanged = true;
  4073. recomputeMaxLength = false;
  4074. }
  4075. });
  4076. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  4077. }
  4078. // Adjust frontier, schedule worker
  4079. doc.frontier = Math.min(doc.frontier, from.line);
  4080. startWorker(cm, 400);
  4081. var lendiff = change.text.length - (to.line - from.line) - 1;
  4082. // Remember that these lines changed, for updating the display
  4083. if (change.full)
  4084. regChange(cm);
  4085. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4086. regLineChange(cm, from.line, "text");
  4087. else
  4088. regChange(cm, from.line, to.line + 1, lendiff);
  4089. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4090. if (changeHandler || changesHandler) {
  4091. var obj = {
  4092. from: from, to: to,
  4093. text: change.text,
  4094. removed: change.removed,
  4095. origin: change.origin
  4096. };
  4097. if (changeHandler) signalLater(cm, "change", cm, obj);
  4098. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  4099. }
  4100. cm.display.selForContextMenu = null;
  4101. }
  4102. function replaceRange(doc, code, from, to, origin) {
  4103. if (!to) to = from;
  4104. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  4105. if (typeof code == "string") code = doc.splitLines(code);
  4106. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4107. }
  4108. // SCROLLING THINGS INTO VIEW
  4109. // If an editor sits on the top or bottom of the window, partially
  4110. // scrolled out of view, this ensures that the cursor is visible.
  4111. function maybeScrollWindow(cm, coords) {
  4112. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  4113. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4114. if (coords.top + box.top < 0) doScroll = true;
  4115. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  4116. if (doScroll != null && !phantom) {
  4117. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  4118. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  4119. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  4120. coords.left + "px; width: 2px;");
  4121. cm.display.lineSpace.appendChild(scrollNode);
  4122. scrollNode.scrollIntoView(doScroll);
  4123. cm.display.lineSpace.removeChild(scrollNode);
  4124. }
  4125. }
  4126. // Scroll a given position into view (immediately), verifying that
  4127. // it actually became visible (as line heights are accurately
  4128. // measured, the position of something may 'drift' during drawing).
  4129. function scrollPosIntoView(cm, pos, end, margin) {
  4130. if (margin == null) margin = 0;
  4131. for (var limit = 0; limit < 5; limit++) {
  4132. var changed = false, coords = cursorCoords(cm, pos);
  4133. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4134. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  4135. Math.min(coords.top, endCoords.top) - margin,
  4136. Math.max(coords.left, endCoords.left),
  4137. Math.max(coords.bottom, endCoords.bottom) + margin);
  4138. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4139. if (scrollPos.scrollTop != null) {
  4140. setScrollTop(cm, scrollPos.scrollTop);
  4141. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  4142. }
  4143. if (scrollPos.scrollLeft != null) {
  4144. setScrollLeft(cm, scrollPos.scrollLeft);
  4145. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  4146. }
  4147. if (!changed) break;
  4148. }
  4149. return coords;
  4150. }
  4151. // Scroll a given set of coordinates into view (immediately).
  4152. function scrollIntoView(cm, x1, y1, x2, y2) {
  4153. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  4154. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  4155. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  4156. }
  4157. // Calculate a new scroll position needed to scroll the given
  4158. // rectangle into view. Returns an object with scrollTop and
  4159. // scrollLeft properties. When these are undefined, the
  4160. // vertical/horizontal position does not need to be adjusted.
  4161. function calculateScrollPos(cm, x1, y1, x2, y2) {
  4162. var display = cm.display, snapMargin = textHeight(cm.display);
  4163. if (y1 < 0) y1 = 0;
  4164. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4165. var screen = displayHeight(cm), result = {};
  4166. if (y2 - y1 > screen) y2 = y1 + screen;
  4167. var docBottom = cm.doc.height + paddingVert(display);
  4168. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4169. if (y1 < screentop) {
  4170. result.scrollTop = atTop ? 0 : y1;
  4171. } else if (y2 > screentop + screen) {
  4172. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4173. if (newTop != screentop) result.scrollTop = newTop;
  4174. }
  4175. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4176. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4177. var tooWide = x2 - x1 > screenw;
  4178. if (tooWide) x2 = x1 + screenw;
  4179. if (x1 < 10)
  4180. result.scrollLeft = 0;
  4181. else if (x1 < screenleft)
  4182. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4183. else if (x2 > screenw + screenleft - 3)
  4184. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4185. return result;
  4186. }
  4187. // Store a relative adjustment to the scroll position in the current
  4188. // operation (to be applied when the operation finishes).
  4189. function addToScrollPos(cm, left, top) {
  4190. if (left != null || top != null) resolveScrollToPos(cm);
  4191. if (left != null)
  4192. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4193. if (top != null)
  4194. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4195. }
  4196. // Make sure that at the end of the operation the current cursor is
  4197. // shown.
  4198. function ensureCursorVisible(cm) {
  4199. resolveScrollToPos(cm);
  4200. var cur = cm.getCursor(), from = cur, to = cur;
  4201. if (!cm.options.lineWrapping) {
  4202. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4203. to = Pos(cur.line, cur.ch + 1);
  4204. }
  4205. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  4206. }
  4207. // When an operation has its scrollToPos property set, and another
  4208. // scroll action is applied before the end of the operation, this
  4209. // 'simulates' scrolling that position into view in a cheap way, so
  4210. // that the effect of intermediate scroll commands is not ignored.
  4211. function resolveScrollToPos(cm) {
  4212. var range = cm.curOp.scrollToPos;
  4213. if (range) {
  4214. cm.curOp.scrollToPos = null;
  4215. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4216. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4217. Math.min(from.top, to.top) - range.margin,
  4218. Math.max(from.right, to.right),
  4219. Math.max(from.bottom, to.bottom) + range.margin);
  4220. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4221. }
  4222. }
  4223. // API UTILITIES
  4224. // Indent the given line. The how parameter can be "smart",
  4225. // "add"/null, "subtract", or "prev". When aggressive is false
  4226. // (typically set to true for forced single-line indents), empty
  4227. // lines are not indented, and places where the mode returns Pass
  4228. // are left alone.
  4229. function indentLine(cm, n, how, aggressive) {
  4230. var doc = cm.doc, state;
  4231. if (how == null) how = "add";
  4232. if (how == "smart") {
  4233. // Fall back to "prev" when the mode doesn't have an indentation
  4234. // method.
  4235. if (!doc.mode.indent) how = "prev";
  4236. else state = getStateBefore(cm, n);
  4237. }
  4238. var tabSize = cm.options.tabSize;
  4239. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4240. if (line.stateAfter) line.stateAfter = null;
  4241. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4242. if (!aggressive && !/\S/.test(line.text)) {
  4243. indentation = 0;
  4244. how = "not";
  4245. } else if (how == "smart") {
  4246. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4247. if (indentation == Pass || indentation > 150) {
  4248. if (!aggressive) return;
  4249. how = "prev";
  4250. }
  4251. }
  4252. if (how == "prev") {
  4253. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  4254. else indentation = 0;
  4255. } else if (how == "add") {
  4256. indentation = curSpace + cm.options.indentUnit;
  4257. } else if (how == "subtract") {
  4258. indentation = curSpace - cm.options.indentUnit;
  4259. } else if (typeof how == "number") {
  4260. indentation = curSpace + how;
  4261. }
  4262. indentation = Math.max(0, indentation);
  4263. var indentString = "", pos = 0;
  4264. if (cm.options.indentWithTabs)
  4265. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  4266. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4267. if (indentString != curSpaceString) {
  4268. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4269. line.stateAfter = null;
  4270. return true;
  4271. } else {
  4272. // Ensure that, if the cursor was in the whitespace at the start
  4273. // of the line, it is moved to the end of that space.
  4274. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4275. var range = doc.sel.ranges[i];
  4276. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4277. var pos = Pos(n, curSpaceString.length);
  4278. replaceOneSelection(doc, i, new Range(pos, pos));
  4279. break;
  4280. }
  4281. }
  4282. }
  4283. }
  4284. // Utility for applying a change to a line by handle or number,
  4285. // returning the number and optionally registering the line as
  4286. // changed.
  4287. function changeLine(doc, handle, changeType, op) {
  4288. var no = handle, line = handle;
  4289. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4290. else no = lineNo(handle);
  4291. if (no == null) return null;
  4292. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4293. return line;
  4294. }
  4295. // Helper for deleting text near the selection(s), used to implement
  4296. // backspace, delete, and similar functionality.
  4297. function deleteNearSelection(cm, compute) {
  4298. var ranges = cm.doc.sel.ranges, kill = [];
  4299. // Build up a set of ranges to kill first, merging overlapping
  4300. // ranges.
  4301. for (var i = 0; i < ranges.length; i++) {
  4302. var toKill = compute(ranges[i]);
  4303. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4304. var replaced = kill.pop();
  4305. if (cmp(replaced.from, toKill.from) < 0) {
  4306. toKill.from = replaced.from;
  4307. break;
  4308. }
  4309. }
  4310. kill.push(toKill);
  4311. }
  4312. // Next, remove those actual ranges.
  4313. runInOp(cm, function() {
  4314. for (var i = kill.length - 1; i >= 0; i--)
  4315. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4316. ensureCursorVisible(cm);
  4317. });
  4318. }
  4319. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4320. // right), unit can be "char", "column" (like char, but doesn't
  4321. // cross line boundaries), "word" (across next word), or "group" (to
  4322. // the start of next group of word or non-word-non-whitespace
  4323. // chars). The visually param controls whether, in right-to-left
  4324. // text, direction 1 means to move towards the next index in the
  4325. // string, or towards the character to the right of the current
  4326. // position. The resulting position will have a hitSide=true
  4327. // property if it reached the end of the document.
  4328. function findPosH(doc, pos, dir, unit, visually) {
  4329. var line = pos.line, ch = pos.ch, origDir = dir;
  4330. var lineObj = getLine(doc, line);
  4331. function findNextLine() {
  4332. var l = line + dir;
  4333. if (l < doc.first || l >= doc.first + doc.size) return false
  4334. line = l;
  4335. return lineObj = getLine(doc, l);
  4336. }
  4337. function moveOnce(boundToLine) {
  4338. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4339. if (next == null) {
  4340. if (!boundToLine && findNextLine()) {
  4341. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4342. else ch = dir < 0 ? lineObj.text.length : 0;
  4343. } else return false
  4344. } else ch = next;
  4345. return true;
  4346. }
  4347. if (unit == "char") {
  4348. moveOnce()
  4349. } else if (unit == "column") {
  4350. moveOnce(true)
  4351. } else if (unit == "word" || unit == "group") {
  4352. var sawType = null, group = unit == "group";
  4353. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4354. for (var first = true;; first = false) {
  4355. if (dir < 0 && !moveOnce(!first)) break;
  4356. var cur = lineObj.text.charAt(ch) || "\n";
  4357. var type = isWordChar(cur, helper) ? "w"
  4358. : group && cur == "\n" ? "n"
  4359. : !group || /\s/.test(cur) ? null
  4360. : "p";
  4361. if (group && !first && !type) type = "s";
  4362. if (sawType && sawType != type) {
  4363. if (dir < 0) {dir = 1; moveOnce();}
  4364. break;
  4365. }
  4366. if (type) sawType = type;
  4367. if (dir > 0 && !moveOnce(!first)) break;
  4368. }
  4369. }
  4370. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
  4371. if (!cmp(pos, result)) result.hitSide = true;
  4372. return result;
  4373. }
  4374. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4375. // "page" or "line". The resulting position will have a hitSide=true
  4376. // property if it reached the end of the document.
  4377. function findPosV(cm, pos, dir, unit) {
  4378. var doc = cm.doc, x = pos.left, y;
  4379. if (unit == "page") {
  4380. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4381. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4382. } else if (unit == "line") {
  4383. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4384. }
  4385. for (;;) {
  4386. var target = coordsChar(cm, x, y);
  4387. if (!target.outside) break;
  4388. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4389. y += dir * 5;
  4390. }
  4391. return target;
  4392. }
  4393. // EDITOR METHODS
  4394. // The publicly visible API. Note that methodOp(f) means
  4395. // 'wrap f in an operation, performed on its `this` parameter'.
  4396. // This is not the complete set of editor methods. Most of the
  4397. // methods defined on the Doc type are also injected into
  4398. // CodeMirror.prototype, for backwards compatibility and
  4399. // convenience.
  4400. CodeMirror.prototype = {
  4401. constructor: CodeMirror,
  4402. focus: function(){window.focus(); this.display.input.focus();},
  4403. setOption: function(option, value) {
  4404. var options = this.options, old = options[option];
  4405. if (options[option] == value && option != "mode") return;
  4406. options[option] = value;
  4407. if (optionHandlers.hasOwnProperty(option))
  4408. operation(this, optionHandlers[option])(this, value, old);
  4409. },
  4410. getOption: function(option) {return this.options[option];},
  4411. getDoc: function() {return this.doc;},
  4412. addKeyMap: function(map, bottom) {
  4413. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4414. },
  4415. removeKeyMap: function(map) {
  4416. var maps = this.state.keyMaps;
  4417. for (var i = 0; i < maps.length; ++i)
  4418. if (maps[i] == map || maps[i].name == map) {
  4419. maps.splice(i, 1);
  4420. return true;
  4421. }
  4422. },
  4423. addOverlay: methodOp(function(spec, options) {
  4424. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4425. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4426. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  4427. this.state.modeGen++;
  4428. regChange(this);
  4429. }),
  4430. removeOverlay: methodOp(function(spec) {
  4431. var overlays = this.state.overlays;
  4432. for (var i = 0; i < overlays.length; ++i) {
  4433. var cur = overlays[i].modeSpec;
  4434. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4435. overlays.splice(i, 1);
  4436. this.state.modeGen++;
  4437. regChange(this);
  4438. return;
  4439. }
  4440. }
  4441. }),
  4442. indentLine: methodOp(function(n, dir, aggressive) {
  4443. if (typeof dir != "string" && typeof dir != "number") {
  4444. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4445. else dir = dir ? "add" : "subtract";
  4446. }
  4447. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4448. }),
  4449. indentSelection: methodOp(function(how) {
  4450. var ranges = this.doc.sel.ranges, end = -1;
  4451. for (var i = 0; i < ranges.length; i++) {
  4452. var range = ranges[i];
  4453. if (!range.empty()) {
  4454. var from = range.from(), to = range.to();
  4455. var start = Math.max(end, from.line);
  4456. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4457. for (var j = start; j < end; ++j)
  4458. indentLine(this, j, how);
  4459. var newRanges = this.doc.sel.ranges;
  4460. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4461. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4462. } else if (range.head.line > end) {
  4463. indentLine(this, range.head.line, how, true);
  4464. end = range.head.line;
  4465. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4466. }
  4467. }
  4468. }),
  4469. // Fetch the parser token for a given character. Useful for hacks
  4470. // that want to inspect the mode state (say, for completion).
  4471. getTokenAt: function(pos, precise) {
  4472. return takeToken(this, pos, precise);
  4473. },
  4474. getLineTokens: function(line, precise) {
  4475. return takeToken(this, Pos(line), precise, true);
  4476. },
  4477. getTokenTypeAt: function(pos) {
  4478. pos = clipPos(this.doc, pos);
  4479. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4480. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4481. var type;
  4482. if (ch == 0) type = styles[2];
  4483. else for (;;) {
  4484. var mid = (before + after) >> 1;
  4485. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4486. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4487. else { type = styles[mid * 2 + 2]; break; }
  4488. }
  4489. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4490. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4491. },
  4492. getModeAt: function(pos) {
  4493. var mode = this.doc.mode;
  4494. if (!mode.innerMode) return mode;
  4495. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4496. },
  4497. getHelper: function(pos, type) {
  4498. return this.getHelpers(pos, type)[0];
  4499. },
  4500. getHelpers: function(pos, type) {
  4501. var found = [];
  4502. if (!helpers.hasOwnProperty(type)) return found;
  4503. var help = helpers[type], mode = this.getModeAt(pos);
  4504. if (typeof mode[type] == "string") {
  4505. if (help[mode[type]]) found.push(help[mode[type]]);
  4506. } else if (mode[type]) {
  4507. for (var i = 0; i < mode[type].length; i++) {
  4508. var val = help[mode[type][i]];
  4509. if (val) found.push(val);
  4510. }
  4511. } else if (mode.helperType && help[mode.helperType]) {
  4512. found.push(help[mode.helperType]);
  4513. } else if (help[mode.name]) {
  4514. found.push(help[mode.name]);
  4515. }
  4516. for (var i = 0; i < help._global.length; i++) {
  4517. var cur = help._global[i];
  4518. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4519. found.push(cur.val);
  4520. }
  4521. return found;
  4522. },
  4523. getStateAfter: function(line, precise) {
  4524. var doc = this.doc;
  4525. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  4526. return getStateBefore(this, line + 1, precise);
  4527. },
  4528. cursorCoords: function(start, mode) {
  4529. var pos, range = this.doc.sel.primary();
  4530. if (start == null) pos = range.head;
  4531. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4532. else pos = start ? range.from() : range.to();
  4533. return cursorCoords(this, pos, mode || "page");
  4534. },
  4535. charCoords: function(pos, mode) {
  4536. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4537. },
  4538. coordsChar: function(coords, mode) {
  4539. coords = fromCoordSystem(this, coords, mode || "page");
  4540. return coordsChar(this, coords.left, coords.top);
  4541. },
  4542. lineAtHeight: function(height, mode) {
  4543. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  4544. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4545. },
  4546. heightAtLine: function(line, mode) {
  4547. var end = false, lineObj;
  4548. if (typeof line == "number") {
  4549. var last = this.doc.first + this.doc.size - 1;
  4550. if (line < this.doc.first) line = this.doc.first;
  4551. else if (line > last) { line = last; end = true; }
  4552. lineObj = getLine(this.doc, line);
  4553. } else {
  4554. lineObj = line;
  4555. }
  4556. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  4557. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4558. },
  4559. defaultTextHeight: function() { return textHeight(this.display); },
  4560. defaultCharWidth: function() { return charWidth(this.display); },
  4561. setGutterMarker: methodOp(function(line, gutterID, value) {
  4562. return changeLine(this.doc, line, "gutter", function(line) {
  4563. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4564. markers[gutterID] = value;
  4565. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4566. return true;
  4567. });
  4568. }),
  4569. clearGutter: methodOp(function(gutterID) {
  4570. var cm = this, doc = cm.doc, i = doc.first;
  4571. doc.iter(function(line) {
  4572. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4573. line.gutterMarkers[gutterID] = null;
  4574. regLineChange(cm, i, "gutter");
  4575. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4576. }
  4577. ++i;
  4578. });
  4579. }),
  4580. lineInfo: function(line) {
  4581. if (typeof line == "number") {
  4582. if (!isLine(this.doc, line)) return null;
  4583. var n = line;
  4584. line = getLine(this.doc, line);
  4585. if (!line) return null;
  4586. } else {
  4587. var n = lineNo(line);
  4588. if (n == null) return null;
  4589. }
  4590. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4591. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4592. widgets: line.widgets};
  4593. },
  4594. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  4595. addWidget: function(pos, node, scroll, vert, horiz) {
  4596. var display = this.display;
  4597. pos = cursorCoords(this, clipPos(this.doc, pos));
  4598. var top = pos.bottom, left = pos.left;
  4599. node.style.position = "absolute";
  4600. node.setAttribute("cm-ignore-events", "true");
  4601. this.display.input.setUneditable(node);
  4602. display.sizer.appendChild(node);
  4603. if (vert == "over") {
  4604. top = pos.top;
  4605. } else if (vert == "above" || vert == "near") {
  4606. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4607. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4608. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4609. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4610. top = pos.top - node.offsetHeight;
  4611. else if (pos.bottom + node.offsetHeight <= vspace)
  4612. top = pos.bottom;
  4613. if (left + node.offsetWidth > hspace)
  4614. left = hspace - node.offsetWidth;
  4615. }
  4616. node.style.top = top + "px";
  4617. node.style.left = node.style.right = "";
  4618. if (horiz == "right") {
  4619. left = display.sizer.clientWidth - node.offsetWidth;
  4620. node.style.right = "0px";
  4621. } else {
  4622. if (horiz == "left") left = 0;
  4623. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4624. node.style.left = left + "px";
  4625. }
  4626. if (scroll)
  4627. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4628. },
  4629. triggerOnKeyDown: methodOp(onKeyDown),
  4630. triggerOnKeyPress: methodOp(onKeyPress),
  4631. triggerOnKeyUp: onKeyUp,
  4632. execCommand: function(cmd) {
  4633. if (commands.hasOwnProperty(cmd))
  4634. return commands[cmd].call(null, this);
  4635. },
  4636. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  4637. findPosH: function(from, amount, unit, visually) {
  4638. var dir = 1;
  4639. if (amount < 0) { dir = -1; amount = -amount; }
  4640. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4641. cur = findPosH(this.doc, cur, dir, unit, visually);
  4642. if (cur.hitSide) break;
  4643. }
  4644. return cur;
  4645. },
  4646. moveH: methodOp(function(dir, unit) {
  4647. var cm = this;
  4648. cm.extendSelectionsBy(function(range) {
  4649. if (cm.display.shift || cm.doc.extend || range.empty())
  4650. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4651. else
  4652. return dir < 0 ? range.from() : range.to();
  4653. }, sel_move);
  4654. }),
  4655. deleteH: methodOp(function(dir, unit) {
  4656. var sel = this.doc.sel, doc = this.doc;
  4657. if (sel.somethingSelected())
  4658. doc.replaceSelection("", null, "+delete");
  4659. else
  4660. deleteNearSelection(this, function(range) {
  4661. var other = findPosH(doc, range.head, dir, unit, false);
  4662. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4663. });
  4664. }),
  4665. findPosV: function(from, amount, unit, goalColumn) {
  4666. var dir = 1, x = goalColumn;
  4667. if (amount < 0) { dir = -1; amount = -amount; }
  4668. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4669. var coords = cursorCoords(this, cur, "div");
  4670. if (x == null) x = coords.left;
  4671. else coords.left = x;
  4672. cur = findPosV(this, coords, dir, unit);
  4673. if (cur.hitSide) break;
  4674. }
  4675. return cur;
  4676. },
  4677. moveV: methodOp(function(dir, unit) {
  4678. var cm = this, doc = this.doc, goals = [];
  4679. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4680. doc.extendSelectionsBy(function(range) {
  4681. if (collapse)
  4682. return dir < 0 ? range.from() : range.to();
  4683. var headPos = cursorCoords(cm, range.head, "div");
  4684. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4685. goals.push(headPos.left);
  4686. var pos = findPosV(cm, headPos, dir, unit);
  4687. if (unit == "page" && range == doc.sel.primary())
  4688. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4689. return pos;
  4690. }, sel_move);
  4691. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4692. doc.sel.ranges[i].goalColumn = goals[i];
  4693. }),
  4694. // Find the word at the given position (as returned by coordsChar).
  4695. findWordAt: function(pos) {
  4696. var doc = this.doc, line = getLine(doc, pos.line).text;
  4697. var start = pos.ch, end = pos.ch;
  4698. if (line) {
  4699. var helper = this.getHelper(pos, "wordChars");
  4700. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4701. var startChar = line.charAt(start);
  4702. var check = isWordChar(startChar, helper)
  4703. ? function(ch) { return isWordChar(ch, helper); }
  4704. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4705. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4706. while (start > 0 && check(line.charAt(start - 1))) --start;
  4707. while (end < line.length && check(line.charAt(end))) ++end;
  4708. }
  4709. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4710. },
  4711. toggleOverwrite: function(value) {
  4712. if (value != null && value == this.state.overwrite) return;
  4713. if (this.state.overwrite = !this.state.overwrite)
  4714. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4715. else
  4716. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4717. signal(this, "overwriteToggle", this, this.state.overwrite);
  4718. },
  4719. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  4720. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  4721. scrollTo: methodOp(function(x, y) {
  4722. if (x != null || y != null) resolveScrollToPos(this);
  4723. if (x != null) this.curOp.scrollLeft = x;
  4724. if (y != null) this.curOp.scrollTop = y;
  4725. }),
  4726. getScrollInfo: function() {
  4727. var scroller = this.display.scroller;
  4728. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4729. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4730. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4731. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4732. },
  4733. scrollIntoView: methodOp(function(range, margin) {
  4734. if (range == null) {
  4735. range = {from: this.doc.sel.primary().head, to: null};
  4736. if (margin == null) margin = this.options.cursorScrollMargin;
  4737. } else if (typeof range == "number") {
  4738. range = {from: Pos(range, 0), to: null};
  4739. } else if (range.from == null) {
  4740. range = {from: range, to: null};
  4741. }
  4742. if (!range.to) range.to = range.from;
  4743. range.margin = margin || 0;
  4744. if (range.from.line != null) {
  4745. resolveScrollToPos(this);
  4746. this.curOp.scrollToPos = range;
  4747. } else {
  4748. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4749. Math.min(range.from.top, range.to.top) - range.margin,
  4750. Math.max(range.from.right, range.to.right),
  4751. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4752. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4753. }
  4754. }),
  4755. setSize: methodOp(function(width, height) {
  4756. var cm = this;
  4757. function interpret(val) {
  4758. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4759. }
  4760. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4761. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4762. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4763. var lineNo = cm.display.viewFrom;
  4764. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4765. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4766. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4767. ++lineNo;
  4768. });
  4769. cm.curOp.forceUpdate = true;
  4770. signal(cm, "refresh", this);
  4771. }),
  4772. operation: function(f){return runInOp(this, f);},
  4773. refresh: methodOp(function() {
  4774. var oldHeight = this.display.cachedTextHeight;
  4775. regChange(this);
  4776. this.curOp.forceUpdate = true;
  4777. clearCaches(this);
  4778. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4779. updateGutterSpace(this);
  4780. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4781. estimateLineHeights(this);
  4782. signal(this, "refresh", this);
  4783. }),
  4784. swapDoc: methodOp(function(doc) {
  4785. var old = this.doc;
  4786. old.cm = null;
  4787. attachDoc(this, doc);
  4788. clearCaches(this);
  4789. this.display.input.reset();
  4790. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4791. this.curOp.forceScroll = true;
  4792. signalLater(this, "swapDoc", this, old);
  4793. return old;
  4794. }),
  4795. getInputField: function(){return this.display.input.getField();},
  4796. getWrapperElement: function(){return this.display.wrapper;},
  4797. getScrollerElement: function(){return this.display.scroller;},
  4798. getGutterElement: function(){return this.display.gutters;}
  4799. };
  4800. eventMixin(CodeMirror);
  4801. // OPTION DEFAULTS
  4802. // The default configuration options.
  4803. var defaults = CodeMirror.defaults = {};
  4804. // Functions to run when options are changed.
  4805. var optionHandlers = CodeMirror.optionHandlers = {};
  4806. function option(name, deflt, handle, notOnInit) {
  4807. CodeMirror.defaults[name] = deflt;
  4808. if (handle) optionHandlers[name] =
  4809. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4810. }
  4811. // Passed to option handlers when there is no old value.
  4812. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4813. // These two are, on init, called from the constructor because they
  4814. // have to be initialized before the editor can start at all.
  4815. option("value", "", function(cm, val) {
  4816. cm.setValue(val);
  4817. }, true);
  4818. option("mode", null, function(cm, val) {
  4819. cm.doc.modeOption = val;
  4820. loadMode(cm);
  4821. }, true);
  4822. option("indentUnit", 2, loadMode, true);
  4823. option("indentWithTabs", false);
  4824. option("smartIndent", true);
  4825. option("tabSize", 4, function(cm) {
  4826. resetModeState(cm);
  4827. clearCaches(cm);
  4828. regChange(cm);
  4829. }, true);
  4830. option("lineSeparator", null, function(cm, val) {
  4831. cm.doc.lineSep = val;
  4832. if (!val) return;
  4833. var newBreaks = [], lineNo = cm.doc.first;
  4834. cm.doc.iter(function(line) {
  4835. for (var pos = 0;;) {
  4836. var found = line.text.indexOf(val, pos);
  4837. if (found == -1) break;
  4838. pos = found + val.length;
  4839. newBreaks.push(Pos(lineNo, found));
  4840. }
  4841. lineNo++;
  4842. });
  4843. for (var i = newBreaks.length - 1; i >= 0; i--)
  4844. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  4845. });
  4846. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  4847. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4848. if (old != CodeMirror.Init) cm.refresh();
  4849. });
  4850. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4851. option("electricChars", true);
  4852. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  4853. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4854. }, true);
  4855. option("rtlMoveVisually", !windows);
  4856. option("wholeLineUpdateBefore", true);
  4857. option("theme", "default", function(cm) {
  4858. themeChanged(cm);
  4859. guttersChanged(cm);
  4860. }, true);
  4861. option("keyMap", "default", function(cm, val, old) {
  4862. var next = getKeyMap(val);
  4863. var prev = old != CodeMirror.Init && getKeyMap(old);
  4864. if (prev && prev.detach) prev.detach(cm, next);
  4865. if (next.attach) next.attach(cm, prev || null);
  4866. });
  4867. option("extraKeys", null);
  4868. option("lineWrapping", false, wrappingChanged, true);
  4869. option("gutters", [], function(cm) {
  4870. setGuttersForLineNumbers(cm.options);
  4871. guttersChanged(cm);
  4872. }, true);
  4873. option("fixedGutter", true, function(cm, val) {
  4874. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4875. cm.refresh();
  4876. }, true);
  4877. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4878. option("scrollbarStyle", "native", function(cm) {
  4879. initScrollbars(cm);
  4880. updateScrollbars(cm);
  4881. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4882. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4883. }, true);
  4884. option("lineNumbers", false, function(cm) {
  4885. setGuttersForLineNumbers(cm.options);
  4886. guttersChanged(cm);
  4887. }, true);
  4888. option("firstLineNumber", 1, guttersChanged, true);
  4889. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4890. option("showCursorWhenSelecting", false, updateSelection, true);
  4891. option("resetSelectionOnContextMenu", true);
  4892. option("lineWiseCopyCut", true);
  4893. option("readOnly", false, function(cm, val) {
  4894. if (val == "nocursor") {
  4895. onBlur(cm);
  4896. cm.display.input.blur();
  4897. cm.display.disabled = true;
  4898. } else {
  4899. cm.display.disabled = false;
  4900. }
  4901. cm.display.input.readOnlyChanged(val)
  4902. });
  4903. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  4904. option("dragDrop", true, dragDropChanged);
  4905. option("allowDropFileTypes", null);
  4906. option("cursorBlinkRate", 530);
  4907. option("cursorScrollMargin", 0);
  4908. option("cursorHeight", 1, updateSelection, true);
  4909. option("singleCursorHeightPerLine", true, updateSelection, true);
  4910. option("workTime", 100);
  4911. option("workDelay", 100);
  4912. option("flattenSpans", true, resetModeState, true);
  4913. option("addModeClass", false, resetModeState, true);
  4914. option("pollInterval", 100);
  4915. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4916. option("historyEventDelay", 1250);
  4917. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4918. option("maxHighlightLength", 10000, resetModeState, true);
  4919. option("moveInputWithCursor", true, function(cm, val) {
  4920. if (!val) cm.display.input.resetPosition();
  4921. });
  4922. option("tabindex", null, function(cm, val) {
  4923. cm.display.input.getField().tabIndex = val || "";
  4924. });
  4925. option("autofocus", null);
  4926. // MODE DEFINITION AND QUERYING
  4927. // Known modes, by name and by MIME
  4928. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4929. // Extra arguments are stored as the mode's dependencies, which is
  4930. // used by (legacy) mechanisms like loadmode.js to automatically
  4931. // load a mode. (Preferred mechanism is the require/define calls.)
  4932. CodeMirror.defineMode = function(name, mode) {
  4933. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4934. if (arguments.length > 2)
  4935. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4936. modes[name] = mode;
  4937. };
  4938. CodeMirror.defineMIME = function(mime, spec) {
  4939. mimeModes[mime] = spec;
  4940. };
  4941. // Given a MIME type, a {name, ...options} config object, or a name
  4942. // string, return a mode config object.
  4943. CodeMirror.resolveMode = function(spec) {
  4944. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4945. spec = mimeModes[spec];
  4946. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4947. var found = mimeModes[spec.name];
  4948. if (typeof found == "string") found = {name: found};
  4949. spec = createObj(found, spec);
  4950. spec.name = found.name;
  4951. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4952. return CodeMirror.resolveMode("application/xml");
  4953. }
  4954. if (typeof spec == "string") return {name: spec};
  4955. else return spec || {name: "null"};
  4956. };
  4957. // Given a mode spec (anything that resolveMode accepts), find and
  4958. // initialize an actual mode object.
  4959. CodeMirror.getMode = function(options, spec) {
  4960. var spec = CodeMirror.resolveMode(spec);
  4961. var mfactory = modes[spec.name];
  4962. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4963. var modeObj = mfactory(options, spec);
  4964. if (modeExtensions.hasOwnProperty(spec.name)) {
  4965. var exts = modeExtensions[spec.name];
  4966. for (var prop in exts) {
  4967. if (!exts.hasOwnProperty(prop)) continue;
  4968. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4969. modeObj[prop] = exts[prop];
  4970. }
  4971. }
  4972. modeObj.name = spec.name;
  4973. if (spec.helperType) modeObj.helperType = spec.helperType;
  4974. if (spec.modeProps) for (var prop in spec.modeProps)
  4975. modeObj[prop] = spec.modeProps[prop];
  4976. return modeObj;
  4977. };
  4978. // Minimal default mode.
  4979. CodeMirror.defineMode("null", function() {
  4980. return {token: function(stream) {stream.skipToEnd();}};
  4981. });
  4982. CodeMirror.defineMIME("text/plain", "null");
  4983. // This can be used to attach properties to mode objects from
  4984. // outside the actual mode definition.
  4985. var modeExtensions = CodeMirror.modeExtensions = {};
  4986. CodeMirror.extendMode = function(mode, properties) {
  4987. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4988. copyObj(properties, exts);
  4989. };
  4990. // EXTENSIONS
  4991. CodeMirror.defineExtension = function(name, func) {
  4992. CodeMirror.prototype[name] = func;
  4993. };
  4994. CodeMirror.defineDocExtension = function(name, func) {
  4995. Doc.prototype[name] = func;
  4996. };
  4997. CodeMirror.defineOption = option;
  4998. var initHooks = [];
  4999. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  5000. var helpers = CodeMirror.helpers = {};
  5001. CodeMirror.registerHelper = function(type, name, value) {
  5002. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  5003. helpers[type][name] = value;
  5004. };
  5005. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  5006. CodeMirror.registerHelper(type, name, value);
  5007. helpers[type]._global.push({pred: predicate, val: value});
  5008. };
  5009. // MODE STATE HANDLING
  5010. // Utility functions for working with state. Exported because nested
  5011. // modes need to do this for their inner modes.
  5012. var copyState = CodeMirror.copyState = function(mode, state) {
  5013. if (state === true) return state;
  5014. if (mode.copyState) return mode.copyState(state);
  5015. var nstate = {};
  5016. for (var n in state) {
  5017. var val = state[n];
  5018. if (val instanceof Array) val = val.concat([]);
  5019. nstate[n] = val;
  5020. }
  5021. return nstate;
  5022. };
  5023. var startState = CodeMirror.startState = function(mode, a1, a2) {
  5024. return mode.startState ? mode.startState(a1, a2) : true;
  5025. };
  5026. // Given a mode and a state (for that mode), find the inner mode and
  5027. // state at the position that the state refers to.
  5028. CodeMirror.innerMode = function(mode, state) {
  5029. while (mode.innerMode) {
  5030. var info = mode.innerMode(state);
  5031. if (!info || info.mode == mode) break;
  5032. state = info.state;
  5033. mode = info.mode;
  5034. }
  5035. return info || {mode: mode, state: state};
  5036. };
  5037. // STANDARD COMMANDS
  5038. // Commands are parameter-less actions that can be performed on an
  5039. // editor, mostly used for keybindings.
  5040. var commands = CodeMirror.commands = {
  5041. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  5042. singleSelection: function(cm) {
  5043. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  5044. },
  5045. killLine: function(cm) {
  5046. deleteNearSelection(cm, function(range) {
  5047. if (range.empty()) {
  5048. var len = getLine(cm.doc, range.head.line).text.length;
  5049. if (range.head.ch == len && range.head.line < cm.lastLine())
  5050. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  5051. else
  5052. return {from: range.head, to: Pos(range.head.line, len)};
  5053. } else {
  5054. return {from: range.from(), to: range.to()};
  5055. }
  5056. });
  5057. },
  5058. deleteLine: function(cm) {
  5059. deleteNearSelection(cm, function(range) {
  5060. return {from: Pos(range.from().line, 0),
  5061. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  5062. });
  5063. },
  5064. delLineLeft: function(cm) {
  5065. deleteNearSelection(cm, function(range) {
  5066. return {from: Pos(range.from().line, 0), to: range.from()};
  5067. });
  5068. },
  5069. delWrappedLineLeft: function(cm) {
  5070. deleteNearSelection(cm, function(range) {
  5071. var top = cm.charCoords(range.head, "div").top + 5;
  5072. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  5073. return {from: leftPos, to: range.from()};
  5074. });
  5075. },
  5076. delWrappedLineRight: function(cm) {
  5077. deleteNearSelection(cm, function(range) {
  5078. var top = cm.charCoords(range.head, "div").top + 5;
  5079. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5080. return {from: range.from(), to: rightPos };
  5081. });
  5082. },
  5083. undo: function(cm) {cm.undo();},
  5084. redo: function(cm) {cm.redo();},
  5085. undoSelection: function(cm) {cm.undoSelection();},
  5086. redoSelection: function(cm) {cm.redoSelection();},
  5087. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  5088. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  5089. goLineStart: function(cm) {
  5090. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  5091. {origin: "+move", bias: 1});
  5092. },
  5093. goLineStartSmart: function(cm) {
  5094. cm.extendSelectionsBy(function(range) {
  5095. return lineStartSmart(cm, range.head);
  5096. }, {origin: "+move", bias: 1});
  5097. },
  5098. goLineEnd: function(cm) {
  5099. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  5100. {origin: "+move", bias: -1});
  5101. },
  5102. goLineRight: function(cm) {
  5103. cm.extendSelectionsBy(function(range) {
  5104. var top = cm.charCoords(range.head, "div").top + 5;
  5105. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5106. }, sel_move);
  5107. },
  5108. goLineLeft: function(cm) {
  5109. cm.extendSelectionsBy(function(range) {
  5110. var top = cm.charCoords(range.head, "div").top + 5;
  5111. return cm.coordsChar({left: 0, top: top}, "div");
  5112. }, sel_move);
  5113. },
  5114. goLineLeftSmart: function(cm) {
  5115. cm.extendSelectionsBy(function(range) {
  5116. var top = cm.charCoords(range.head, "div").top + 5;
  5117. var pos = cm.coordsChar({left: 0, top: top}, "div");
  5118. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  5119. return pos;
  5120. }, sel_move);
  5121. },
  5122. goLineUp: function(cm) {cm.moveV(-1, "line");},
  5123. goLineDown: function(cm) {cm.moveV(1, "line");},
  5124. goPageUp: function(cm) {cm.moveV(-1, "page");},
  5125. goPageDown: function(cm) {cm.moveV(1, "page");},
  5126. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  5127. goCharRight: function(cm) {cm.moveH(1, "char");},
  5128. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  5129. goColumnRight: function(cm) {cm.moveH(1, "column");},
  5130. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  5131. goGroupRight: function(cm) {cm.moveH(1, "group");},
  5132. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  5133. goWordRight: function(cm) {cm.moveH(1, "word");},
  5134. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  5135. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  5136. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  5137. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  5138. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  5139. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  5140. indentAuto: function(cm) {cm.indentSelection("smart");},
  5141. indentMore: function(cm) {cm.indentSelection("add");},
  5142. indentLess: function(cm) {cm.indentSelection("subtract");},
  5143. insertTab: function(cm) {cm.replaceSelection("\t");},
  5144. insertSoftTab: function(cm) {
  5145. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  5146. for (var i = 0; i < ranges.length; i++) {
  5147. var pos = ranges[i].from();
  5148. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  5149. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  5150. }
  5151. cm.replaceSelections(spaces);
  5152. },
  5153. defaultTab: function(cm) {
  5154. if (cm.somethingSelected()) cm.indentSelection("add");
  5155. else cm.execCommand("insertTab");
  5156. },
  5157. transposeChars: function(cm) {
  5158. runInOp(cm, function() {
  5159. var ranges = cm.listSelections(), newSel = [];
  5160. for (var i = 0; i < ranges.length; i++) {
  5161. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  5162. if (line) {
  5163. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  5164. if (cur.ch > 0) {
  5165. cur = new Pos(cur.line, cur.ch + 1);
  5166. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5167. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  5168. } else if (cur.line > cm.doc.first) {
  5169. var prev = getLine(cm.doc, cur.line - 1).text;
  5170. if (prev)
  5171. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  5172. prev.charAt(prev.length - 1),
  5173. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  5174. }
  5175. }
  5176. newSel.push(new Range(cur, cur));
  5177. }
  5178. cm.setSelections(newSel);
  5179. });
  5180. },
  5181. newlineAndIndent: function(cm) {
  5182. runInOp(cm, function() {
  5183. var len = cm.listSelections().length;
  5184. for (var i = 0; i < len; i++) {
  5185. var range = cm.listSelections()[i];
  5186. cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
  5187. cm.indentLine(range.from().line + 1, null, true);
  5188. }
  5189. ensureCursorVisible(cm);
  5190. });
  5191. },
  5192. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  5193. };
  5194. // STANDARD KEYMAPS
  5195. var keyMap = CodeMirror.keyMap = {};
  5196. keyMap.basic = {
  5197. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5198. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5199. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5200. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5201. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5202. "Esc": "singleSelection"
  5203. };
  5204. // Note that the save and find-related commands aren't defined by
  5205. // default. User code or addons can define them. Unknown commands
  5206. // are simply ignored.
  5207. keyMap.pcDefault = {
  5208. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5209. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5210. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5211. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5212. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5213. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5214. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5215. fallthrough: "basic"
  5216. };
  5217. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5218. keyMap.emacsy = {
  5219. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5220. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5221. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5222. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  5223. };
  5224. keyMap.macDefault = {
  5225. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5226. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5227. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5228. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5229. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5230. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5231. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5232. fallthrough: ["basic", "emacsy"]
  5233. };
  5234. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5235. // KEYMAP DISPATCH
  5236. function normalizeKeyName(name) {
  5237. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5238. var alt, ctrl, shift, cmd;
  5239. for (var i = 0; i < parts.length - 1; i++) {
  5240. var mod = parts[i];
  5241. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5242. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5243. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5244. else if (/^s(hift)$/i.test(mod)) shift = true;
  5245. else throw new Error("Unrecognized modifier name: " + mod);
  5246. }
  5247. if (alt) name = "Alt-" + name;
  5248. if (ctrl) name = "Ctrl-" + name;
  5249. if (cmd) name = "Cmd-" + name;
  5250. if (shift) name = "Shift-" + name;
  5251. return name;
  5252. }
  5253. // This is a kludge to keep keymaps mostly working as raw objects
  5254. // (backwards compatibility) while at the same time support features
  5255. // like normalization and multi-stroke key bindings. It compiles a
  5256. // new normalized keymap, and then updates the old object to reflect
  5257. // this.
  5258. CodeMirror.normalizeKeyMap = function(keymap) {
  5259. var copy = {};
  5260. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5261. var value = keymap[keyname];
  5262. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5263. if (value == "...") { delete keymap[keyname]; continue; }
  5264. var keys = map(keyname.split(" "), normalizeKeyName);
  5265. for (var i = 0; i < keys.length; i++) {
  5266. var val, name;
  5267. if (i == keys.length - 1) {
  5268. name = keys.join(" ");
  5269. val = value;
  5270. } else {
  5271. name = keys.slice(0, i + 1).join(" ");
  5272. val = "...";
  5273. }
  5274. var prev = copy[name];
  5275. if (!prev) copy[name] = val;
  5276. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5277. }
  5278. delete keymap[keyname];
  5279. }
  5280. for (var prop in copy) keymap[prop] = copy[prop];
  5281. return keymap;
  5282. };
  5283. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  5284. map = getKeyMap(map);
  5285. var found = map.call ? map.call(key, context) : map[key];
  5286. if (found === false) return "nothing";
  5287. if (found === "...") return "multi";
  5288. if (found != null && handle(found)) return "handled";
  5289. if (map.fallthrough) {
  5290. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5291. return lookupKey(key, map.fallthrough, handle, context);
  5292. for (var i = 0; i < map.fallthrough.length; i++) {
  5293. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5294. if (result) return result;
  5295. }
  5296. }
  5297. };
  5298. // Modifier key presses don't count as 'real' key presses for the
  5299. // purpose of keymap fallthrough.
  5300. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  5301. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5302. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5303. };
  5304. // Look up the name of a key as indicated by an event object.
  5305. var keyName = CodeMirror.keyName = function(event, noShift) {
  5306. if (presto && event.keyCode == 34 && event["char"]) return false;
  5307. var base = keyNames[event.keyCode], name = base;
  5308. if (name == null || event.altGraphKey) return false;
  5309. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5310. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5311. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5312. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5313. return name;
  5314. };
  5315. function getKeyMap(val) {
  5316. return typeof val == "string" ? keyMap[val] : val;
  5317. }
  5318. // FROMTEXTAREA
  5319. CodeMirror.fromTextArea = function(textarea, options) {
  5320. options = options ? copyObj(options) : {};
  5321. options.value = textarea.value;
  5322. if (!options.tabindex && textarea.tabIndex)
  5323. options.tabindex = textarea.tabIndex;
  5324. if (!options.placeholder && textarea.placeholder)
  5325. options.placeholder = textarea.placeholder;
  5326. // Set autofocus to true if this textarea is focused, or if it has
  5327. // autofocus and no other element is focused.
  5328. if (options.autofocus == null) {
  5329. var hasFocus = activeElt();
  5330. options.autofocus = hasFocus == textarea ||
  5331. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5332. }
  5333. function save() {textarea.value = cm.getValue();}
  5334. if (textarea.form) {
  5335. on(textarea.form, "submit", save);
  5336. // Deplorable hack to make the submit method do the right thing.
  5337. if (!options.leaveSubmitMethodAlone) {
  5338. var form = textarea.form, realSubmit = form.submit;
  5339. try {
  5340. var wrappedSubmit = form.submit = function() {
  5341. save();
  5342. form.submit = realSubmit;
  5343. form.submit();
  5344. form.submit = wrappedSubmit;
  5345. };
  5346. } catch(e) {}
  5347. }
  5348. }
  5349. options.finishInit = function(cm) {
  5350. cm.save = save;
  5351. cm.getTextArea = function() { return textarea; };
  5352. cm.toTextArea = function() {
  5353. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5354. save();
  5355. textarea.parentNode.removeChild(cm.getWrapperElement());
  5356. textarea.style.display = "";
  5357. if (textarea.form) {
  5358. off(textarea.form, "submit", save);
  5359. if (typeof textarea.form.submit == "function")
  5360. textarea.form.submit = realSubmit;
  5361. }
  5362. };
  5363. };
  5364. textarea.style.display = "none";
  5365. var cm = CodeMirror(function(node) {
  5366. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5367. }, options);
  5368. return cm;
  5369. };
  5370. // STRING STREAM
  5371. // Fed to the mode parsers, provides helper functions to make
  5372. // parsers more succinct.
  5373. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  5374. this.pos = this.start = 0;
  5375. this.string = string;
  5376. this.tabSize = tabSize || 8;
  5377. this.lastColumnPos = this.lastColumnValue = 0;
  5378. this.lineStart = 0;
  5379. };
  5380. StringStream.prototype = {
  5381. eol: function() {return this.pos >= this.string.length;},
  5382. sol: function() {return this.pos == this.lineStart;},
  5383. peek: function() {return this.string.charAt(this.pos) || undefined;},
  5384. next: function() {
  5385. if (this.pos < this.string.length)
  5386. return this.string.charAt(this.pos++);
  5387. },
  5388. eat: function(match) {
  5389. var ch = this.string.charAt(this.pos);
  5390. if (typeof match == "string") var ok = ch == match;
  5391. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5392. if (ok) {++this.pos; return ch;}
  5393. },
  5394. eatWhile: function(match) {
  5395. var start = this.pos;
  5396. while (this.eat(match)){}
  5397. return this.pos > start;
  5398. },
  5399. eatSpace: function() {
  5400. var start = this.pos;
  5401. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  5402. return this.pos > start;
  5403. },
  5404. skipToEnd: function() {this.pos = this.string.length;},
  5405. skipTo: function(ch) {
  5406. var found = this.string.indexOf(ch, this.pos);
  5407. if (found > -1) {this.pos = found; return true;}
  5408. },
  5409. backUp: function(n) {this.pos -= n;},
  5410. column: function() {
  5411. if (this.lastColumnPos < this.start) {
  5412. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5413. this.lastColumnPos = this.start;
  5414. }
  5415. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5416. },
  5417. indentation: function() {
  5418. return countColumn(this.string, null, this.tabSize) -
  5419. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5420. },
  5421. match: function(pattern, consume, caseInsensitive) {
  5422. if (typeof pattern == "string") {
  5423. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  5424. var substr = this.string.substr(this.pos, pattern.length);
  5425. if (cased(substr) == cased(pattern)) {
  5426. if (consume !== false) this.pos += pattern.length;
  5427. return true;
  5428. }
  5429. } else {
  5430. var match = this.string.slice(this.pos).match(pattern);
  5431. if (match && match.index > 0) return null;
  5432. if (match && consume !== false) this.pos += match[0].length;
  5433. return match;
  5434. }
  5435. },
  5436. current: function(){return this.string.slice(this.start, this.pos);},
  5437. hideFirstChars: function(n, inner) {
  5438. this.lineStart += n;
  5439. try { return inner(); }
  5440. finally { this.lineStart -= n; }
  5441. }
  5442. };
  5443. // TEXTMARKERS
  5444. // Created with markText and setBookmark methods. A TextMarker is a
  5445. // handle that can be used to clear or find a marked position in the
  5446. // document. Line objects hold arrays (markedSpans) containing
  5447. // {from, to, marker} object pointing to such marker objects, and
  5448. // indicating that such a marker is present on that line. Multiple
  5449. // lines may point to the same marker when it spans across lines.
  5450. // The spans will have null for their from/to properties when the
  5451. // marker continues beyond the start/end of the line. Markers have
  5452. // links back to the lines they currently touch.
  5453. var nextMarkerId = 0;
  5454. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  5455. this.lines = [];
  5456. this.type = type;
  5457. this.doc = doc;
  5458. this.id = ++nextMarkerId;
  5459. };
  5460. eventMixin(TextMarker);
  5461. // Clear the marker.
  5462. TextMarker.prototype.clear = function() {
  5463. if (this.explicitlyCleared) return;
  5464. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5465. if (withOp) startOperation(cm);
  5466. if (hasHandler(this, "clear")) {
  5467. var found = this.find();
  5468. if (found) signalLater(this, "clear", found.from, found.to);
  5469. }
  5470. var min = null, max = null;
  5471. for (var i = 0; i < this.lines.length; ++i) {
  5472. var line = this.lines[i];
  5473. var span = getMarkedSpanFor(line.markedSpans, this);
  5474. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5475. else if (cm) {
  5476. if (span.to != null) max = lineNo(line);
  5477. if (span.from != null) min = lineNo(line);
  5478. }
  5479. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5480. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5481. updateLineHeight(line, textHeight(cm.display));
  5482. }
  5483. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5484. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5485. if (len > cm.display.maxLineLength) {
  5486. cm.display.maxLine = visual;
  5487. cm.display.maxLineLength = len;
  5488. cm.display.maxLineChanged = true;
  5489. }
  5490. }
  5491. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5492. this.lines.length = 0;
  5493. this.explicitlyCleared = true;
  5494. if (this.atomic && this.doc.cantEdit) {
  5495. this.doc.cantEdit = false;
  5496. if (cm) reCheckSelection(cm.doc);
  5497. }
  5498. if (cm) signalLater(cm, "markerCleared", cm, this);
  5499. if (withOp) endOperation(cm);
  5500. if (this.parent) this.parent.clear();
  5501. };
  5502. // Find the position of the marker in the document. Returns a {from,
  5503. // to} object by default. Side can be passed to get a specific side
  5504. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5505. // Pos objects returned contain a line object, rather than a line
  5506. // number (used to prevent looking up the same line twice).
  5507. TextMarker.prototype.find = function(side, lineObj) {
  5508. if (side == null && this.type == "bookmark") side = 1;
  5509. var from, to;
  5510. for (var i = 0; i < this.lines.length; ++i) {
  5511. var line = this.lines[i];
  5512. var span = getMarkedSpanFor(line.markedSpans, this);
  5513. if (span.from != null) {
  5514. from = Pos(lineObj ? line : lineNo(line), span.from);
  5515. if (side == -1) return from;
  5516. }
  5517. if (span.to != null) {
  5518. to = Pos(lineObj ? line : lineNo(line), span.to);
  5519. if (side == 1) return to;
  5520. }
  5521. }
  5522. return from && {from: from, to: to};
  5523. };
  5524. // Signals that the marker's widget changed, and surrounding layout
  5525. // should be recomputed.
  5526. TextMarker.prototype.changed = function() {
  5527. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5528. if (!pos || !cm) return;
  5529. runInOp(cm, function() {
  5530. var line = pos.line, lineN = lineNo(pos.line);
  5531. var view = findViewForLine(cm, lineN);
  5532. if (view) {
  5533. clearLineMeasurementCacheFor(view);
  5534. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5535. }
  5536. cm.curOp.updateMaxLine = true;
  5537. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5538. var oldHeight = widget.height;
  5539. widget.height = null;
  5540. var dHeight = widgetHeight(widget) - oldHeight;
  5541. if (dHeight)
  5542. updateLineHeight(line, line.height + dHeight);
  5543. }
  5544. });
  5545. };
  5546. TextMarker.prototype.attachLine = function(line) {
  5547. if (!this.lines.length && this.doc.cm) {
  5548. var op = this.doc.cm.curOp;
  5549. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5550. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5551. }
  5552. this.lines.push(line);
  5553. };
  5554. TextMarker.prototype.detachLine = function(line) {
  5555. this.lines.splice(indexOf(this.lines, line), 1);
  5556. if (!this.lines.length && this.doc.cm) {
  5557. var op = this.doc.cm.curOp;
  5558. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5559. }
  5560. };
  5561. // Collapsed markers have unique ids, in order to be able to order
  5562. // them, which is needed for uniquely determining an outer marker
  5563. // when they overlap (they may nest, but not partially overlap).
  5564. var nextMarkerId = 0;
  5565. // Create a marker, wire it up to the right lines, and
  5566. function markText(doc, from, to, options, type) {
  5567. // Shared markers (across linked documents) are handled separately
  5568. // (markTextShared will call out to this again, once per
  5569. // document).
  5570. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5571. // Ensure we are in an operation.
  5572. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5573. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5574. if (options) copyObj(options, marker, false);
  5575. // Don't connect empty markers unless clearWhenEmpty is false
  5576. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5577. return marker;
  5578. if (marker.replacedWith) {
  5579. // Showing up as a widget implies collapsed (widget replaces text)
  5580. marker.collapsed = true;
  5581. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5582. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5583. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5584. }
  5585. if (marker.collapsed) {
  5586. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5587. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5588. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5589. sawCollapsedSpans = true;
  5590. }
  5591. if (marker.addToHistory)
  5592. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  5593. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5594. doc.iter(curLine, to.line + 1, function(line) {
  5595. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5596. updateMaxLine = true;
  5597. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5598. addMarkedSpan(line, new MarkedSpan(marker,
  5599. curLine == from.line ? from.ch : null,
  5600. curLine == to.line ? to.ch : null));
  5601. ++curLine;
  5602. });
  5603. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5604. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  5605. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5606. });
  5607. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  5608. if (marker.readOnly) {
  5609. sawReadOnlySpans = true;
  5610. if (doc.history.done.length || doc.history.undone.length)
  5611. doc.clearHistory();
  5612. }
  5613. if (marker.collapsed) {
  5614. marker.id = ++nextMarkerId;
  5615. marker.atomic = true;
  5616. }
  5617. if (cm) {
  5618. // Sync editor state
  5619. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5620. if (marker.collapsed)
  5621. regChange(cm, from.line, to.line + 1);
  5622. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5623. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5624. if (marker.atomic) reCheckSelection(cm.doc);
  5625. signalLater(cm, "markerAdded", cm, marker);
  5626. }
  5627. return marker;
  5628. }
  5629. // SHARED TEXTMARKERS
  5630. // A shared marker spans multiple linked documents. It is
  5631. // implemented as a meta-marker-object controlling multiple normal
  5632. // markers.
  5633. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  5634. this.markers = markers;
  5635. this.primary = primary;
  5636. for (var i = 0; i < markers.length; ++i)
  5637. markers[i].parent = this;
  5638. };
  5639. eventMixin(SharedTextMarker);
  5640. SharedTextMarker.prototype.clear = function() {
  5641. if (this.explicitlyCleared) return;
  5642. this.explicitlyCleared = true;
  5643. for (var i = 0; i < this.markers.length; ++i)
  5644. this.markers[i].clear();
  5645. signalLater(this, "clear");
  5646. };
  5647. SharedTextMarker.prototype.find = function(side, lineObj) {
  5648. return this.primary.find(side, lineObj);
  5649. };
  5650. function markTextShared(doc, from, to, options, type) {
  5651. options = copyObj(options);
  5652. options.shared = false;
  5653. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5654. var widget = options.widgetNode;
  5655. linkedDocs(doc, function(doc) {
  5656. if (widget) options.widgetNode = widget.cloneNode(true);
  5657. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5658. for (var i = 0; i < doc.linked.length; ++i)
  5659. if (doc.linked[i].isParent) return;
  5660. primary = lst(markers);
  5661. });
  5662. return new SharedTextMarker(markers, primary);
  5663. }
  5664. function findSharedMarkers(doc) {
  5665. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5666. function(m) { return m.parent; });
  5667. }
  5668. function copySharedMarkers(doc, markers) {
  5669. for (var i = 0; i < markers.length; i++) {
  5670. var marker = markers[i], pos = marker.find();
  5671. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5672. if (cmp(mFrom, mTo)) {
  5673. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5674. marker.markers.push(subMark);
  5675. subMark.parent = marker;
  5676. }
  5677. }
  5678. }
  5679. function detachSharedMarkers(markers) {
  5680. for (var i = 0; i < markers.length; i++) {
  5681. var marker = markers[i], linked = [marker.primary.doc];;
  5682. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5683. for (var j = 0; j < marker.markers.length; j++) {
  5684. var subMarker = marker.markers[j];
  5685. if (indexOf(linked, subMarker.doc) == -1) {
  5686. subMarker.parent = null;
  5687. marker.markers.splice(j--, 1);
  5688. }
  5689. }
  5690. }
  5691. }
  5692. // TEXTMARKER SPANS
  5693. function MarkedSpan(marker, from, to) {
  5694. this.marker = marker;
  5695. this.from = from; this.to = to;
  5696. }
  5697. // Search an array of spans for a span matching the given marker.
  5698. function getMarkedSpanFor(spans, marker) {
  5699. if (spans) for (var i = 0; i < spans.length; ++i) {
  5700. var span = spans[i];
  5701. if (span.marker == marker) return span;
  5702. }
  5703. }
  5704. // Remove a span from an array, returning undefined if no spans are
  5705. // left (we don't store arrays for lines without spans).
  5706. function removeMarkedSpan(spans, span) {
  5707. for (var r, i = 0; i < spans.length; ++i)
  5708. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5709. return r;
  5710. }
  5711. // Add a span to a line.
  5712. function addMarkedSpan(line, span) {
  5713. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5714. span.marker.attachLine(line);
  5715. }
  5716. // Used for the algorithm that adjusts markers for a change in the
  5717. // document. These functions cut an array of spans at a given
  5718. // character position, returning an array of remaining chunks (or
  5719. // undefined if nothing remains).
  5720. function markedSpansBefore(old, startCh, isInsert) {
  5721. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5722. var span = old[i], marker = span.marker;
  5723. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5724. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5725. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5726. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5727. }
  5728. }
  5729. return nw;
  5730. }
  5731. function markedSpansAfter(old, endCh, isInsert) {
  5732. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5733. var span = old[i], marker = span.marker;
  5734. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5735. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5736. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5737. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5738. span.to == null ? null : span.to - endCh));
  5739. }
  5740. }
  5741. return nw;
  5742. }
  5743. // Given a change object, compute the new set of marker spans that
  5744. // cover the line in which the change took place. Removes spans
  5745. // entirely within the change, reconnects spans belonging to the
  5746. // same marker that appear on both sides of the change, and cuts off
  5747. // spans partially within the change. Returns an array of span
  5748. // arrays with one element for each line in (after) the change.
  5749. function stretchSpansOverChange(doc, change) {
  5750. if (change.full) return null;
  5751. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5752. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5753. if (!oldFirst && !oldLast) return null;
  5754. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5755. // Get the spans that 'stick out' on both sides
  5756. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5757. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5758. // Next, merge those two ends
  5759. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5760. if (first) {
  5761. // Fix up .to properties of first
  5762. for (var i = 0; i < first.length; ++i) {
  5763. var span = first[i];
  5764. if (span.to == null) {
  5765. var found = getMarkedSpanFor(last, span.marker);
  5766. if (!found) span.to = startCh;
  5767. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5768. }
  5769. }
  5770. }
  5771. if (last) {
  5772. // Fix up .from in last (or move them into first in case of sameLine)
  5773. for (var i = 0; i < last.length; ++i) {
  5774. var span = last[i];
  5775. if (span.to != null) span.to += offset;
  5776. if (span.from == null) {
  5777. var found = getMarkedSpanFor(first, span.marker);
  5778. if (!found) {
  5779. span.from = offset;
  5780. if (sameLine) (first || (first = [])).push(span);
  5781. }
  5782. } else {
  5783. span.from += offset;
  5784. if (sameLine) (first || (first = [])).push(span);
  5785. }
  5786. }
  5787. }
  5788. // Make sure we didn't create any zero-length spans
  5789. if (first) first = clearEmptySpans(first);
  5790. if (last && last != first) last = clearEmptySpans(last);
  5791. var newMarkers = [first];
  5792. if (!sameLine) {
  5793. // Fill gap with whole-line-spans
  5794. var gap = change.text.length - 2, gapMarkers;
  5795. if (gap > 0 && first)
  5796. for (var i = 0; i < first.length; ++i)
  5797. if (first[i].to == null)
  5798. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5799. for (var i = 0; i < gap; ++i)
  5800. newMarkers.push(gapMarkers);
  5801. newMarkers.push(last);
  5802. }
  5803. return newMarkers;
  5804. }
  5805. // Remove spans that are empty and don't have a clearWhenEmpty
  5806. // option of false.
  5807. function clearEmptySpans(spans) {
  5808. for (var i = 0; i < spans.length; ++i) {
  5809. var span = spans[i];
  5810. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5811. spans.splice(i--, 1);
  5812. }
  5813. if (!spans.length) return null;
  5814. return spans;
  5815. }
  5816. // Used for un/re-doing changes from the history. Combines the
  5817. // result of computing the existing spans with the set of spans that
  5818. // existed in the history (so that deleting around a span and then
  5819. // undoing brings back the span).
  5820. function mergeOldSpans(doc, change) {
  5821. var old = getOldSpans(doc, change);
  5822. var stretched = stretchSpansOverChange(doc, change);
  5823. if (!old) return stretched;
  5824. if (!stretched) return old;
  5825. for (var i = 0; i < old.length; ++i) {
  5826. var oldCur = old[i], stretchCur = stretched[i];
  5827. if (oldCur && stretchCur) {
  5828. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5829. var span = stretchCur[j];
  5830. for (var k = 0; k < oldCur.length; ++k)
  5831. if (oldCur[k].marker == span.marker) continue spans;
  5832. oldCur.push(span);
  5833. }
  5834. } else if (stretchCur) {
  5835. old[i] = stretchCur;
  5836. }
  5837. }
  5838. return old;
  5839. }
  5840. // Used to 'clip' out readOnly ranges when making a change.
  5841. function removeReadOnlyRanges(doc, from, to) {
  5842. var markers = null;
  5843. doc.iter(from.line, to.line + 1, function(line) {
  5844. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5845. var mark = line.markedSpans[i].marker;
  5846. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5847. (markers || (markers = [])).push(mark);
  5848. }
  5849. });
  5850. if (!markers) return null;
  5851. var parts = [{from: from, to: to}];
  5852. for (var i = 0; i < markers.length; ++i) {
  5853. var mk = markers[i], m = mk.find(0);
  5854. for (var j = 0; j < parts.length; ++j) {
  5855. var p = parts[j];
  5856. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5857. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5858. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5859. newParts.push({from: p.from, to: m.from});
  5860. if (dto > 0 || !mk.inclusiveRight && !dto)
  5861. newParts.push({from: m.to, to: p.to});
  5862. parts.splice.apply(parts, newParts);
  5863. j += newParts.length - 1;
  5864. }
  5865. }
  5866. return parts;
  5867. }
  5868. // Connect or disconnect spans from a line.
  5869. function detachMarkedSpans(line) {
  5870. var spans = line.markedSpans;
  5871. if (!spans) return;
  5872. for (var i = 0; i < spans.length; ++i)
  5873. spans[i].marker.detachLine(line);
  5874. line.markedSpans = null;
  5875. }
  5876. function attachMarkedSpans(line, spans) {
  5877. if (!spans) return;
  5878. for (var i = 0; i < spans.length; ++i)
  5879. spans[i].marker.attachLine(line);
  5880. line.markedSpans = spans;
  5881. }
  5882. // Helpers used when computing which overlapping collapsed span
  5883. // counts as the larger one.
  5884. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5885. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5886. // Returns a number indicating which of two overlapping collapsed
  5887. // spans is larger (and thus includes the other). Falls back to
  5888. // comparing ids when the spans cover exactly the same range.
  5889. function compareCollapsedMarkers(a, b) {
  5890. var lenDiff = a.lines.length - b.lines.length;
  5891. if (lenDiff != 0) return lenDiff;
  5892. var aPos = a.find(), bPos = b.find();
  5893. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5894. if (fromCmp) return -fromCmp;
  5895. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5896. if (toCmp) return toCmp;
  5897. return b.id - a.id;
  5898. }
  5899. // Find out whether a line ends or starts in a collapsed span. If
  5900. // so, return the marker for that span.
  5901. function collapsedSpanAtSide(line, start) {
  5902. var sps = sawCollapsedSpans && line.markedSpans, found;
  5903. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5904. sp = sps[i];
  5905. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5906. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5907. found = sp.marker;
  5908. }
  5909. return found;
  5910. }
  5911. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5912. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5913. // Test whether there exists a collapsed span that partially
  5914. // overlaps (covers the start or end, but not both) of a new span.
  5915. // Such overlap is not allowed.
  5916. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5917. var line = getLine(doc, lineNo);
  5918. var sps = sawCollapsedSpans && line.markedSpans;
  5919. if (sps) for (var i = 0; i < sps.length; ++i) {
  5920. var sp = sps[i];
  5921. if (!sp.marker.collapsed) continue;
  5922. var found = sp.marker.find(0);
  5923. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5924. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5925. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5926. if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
  5927. fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
  5928. return true;
  5929. }
  5930. }
  5931. // A visual line is a line as drawn on the screen. Folding, for
  5932. // example, can cause multiple logical lines to appear on the same
  5933. // visual line. This finds the start of the visual line that the
  5934. // given line is part of (usually that is the line itself).
  5935. function visualLine(line) {
  5936. var merged;
  5937. while (merged = collapsedSpanAtStart(line))
  5938. line = merged.find(-1, true).line;
  5939. return line;
  5940. }
  5941. // Returns an array of logical lines that continue the visual line
  5942. // started by the argument, or undefined if there are no such lines.
  5943. function visualLineContinued(line) {
  5944. var merged, lines;
  5945. while (merged = collapsedSpanAtEnd(line)) {
  5946. line = merged.find(1, true).line;
  5947. (lines || (lines = [])).push(line);
  5948. }
  5949. return lines;
  5950. }
  5951. // Get the line number of the start of the visual line that the
  5952. // given line number is part of.
  5953. function visualLineNo(doc, lineN) {
  5954. var line = getLine(doc, lineN), vis = visualLine(line);
  5955. if (line == vis) return lineN;
  5956. return lineNo(vis);
  5957. }
  5958. // Get the line number of the start of the next visual line after
  5959. // the given line.
  5960. function visualLineEndNo(doc, lineN) {
  5961. if (lineN > doc.lastLine()) return lineN;
  5962. var line = getLine(doc, lineN), merged;
  5963. if (!lineIsHidden(doc, line)) return lineN;
  5964. while (merged = collapsedSpanAtEnd(line))
  5965. line = merged.find(1, true).line;
  5966. return lineNo(line) + 1;
  5967. }
  5968. // Compute whether a line is hidden. Lines count as hidden when they
  5969. // are part of a visual line that starts with another line, or when
  5970. // they are entirely covered by collapsed, non-widget span.
  5971. function lineIsHidden(doc, line) {
  5972. var sps = sawCollapsedSpans && line.markedSpans;
  5973. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5974. sp = sps[i];
  5975. if (!sp.marker.collapsed) continue;
  5976. if (sp.from == null) return true;
  5977. if (sp.marker.widgetNode) continue;
  5978. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5979. return true;
  5980. }
  5981. }
  5982. function lineIsHiddenInner(doc, line, span) {
  5983. if (span.to == null) {
  5984. var end = span.marker.find(1, true);
  5985. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5986. }
  5987. if (span.marker.inclusiveRight && span.to == line.text.length)
  5988. return true;
  5989. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5990. sp = line.markedSpans[i];
  5991. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5992. (sp.to == null || sp.to != span.from) &&
  5993. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5994. lineIsHiddenInner(doc, line, sp)) return true;
  5995. }
  5996. }
  5997. // LINE WIDGETS
  5998. // Line widgets are block elements displayed above or below a line.
  5999. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  6000. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  6001. this[opt] = options[opt];
  6002. this.doc = doc;
  6003. this.node = node;
  6004. };
  6005. eventMixin(LineWidget);
  6006. function adjustScrollWhenAboveVisible(cm, line, diff) {
  6007. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  6008. addToScrollPos(cm, null, diff);
  6009. }
  6010. LineWidget.prototype.clear = function() {
  6011. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  6012. if (no == null || !ws) return;
  6013. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  6014. if (!ws.length) line.widgets = null;
  6015. var height = widgetHeight(this);
  6016. updateLineHeight(line, Math.max(0, line.height - height));
  6017. if (cm) runInOp(cm, function() {
  6018. adjustScrollWhenAboveVisible(cm, line, -height);
  6019. regLineChange(cm, no, "widget");
  6020. });
  6021. };
  6022. LineWidget.prototype.changed = function() {
  6023. var oldH = this.height, cm = this.doc.cm, line = this.line;
  6024. this.height = null;
  6025. var diff = widgetHeight(this) - oldH;
  6026. if (!diff) return;
  6027. updateLineHeight(line, line.height + diff);
  6028. if (cm) runInOp(cm, function() {
  6029. cm.curOp.forceUpdate = true;
  6030. adjustScrollWhenAboveVisible(cm, line, diff);
  6031. });
  6032. };
  6033. function widgetHeight(widget) {
  6034. if (widget.height != null) return widget.height;
  6035. var cm = widget.doc.cm;
  6036. if (!cm) return 0;
  6037. if (!contains(document.body, widget.node)) {
  6038. var parentStyle = "position: relative;";
  6039. if (widget.coverGutter)
  6040. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  6041. if (widget.noHScroll)
  6042. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  6043. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  6044. }
  6045. return widget.height = widget.node.parentNode.offsetHeight;
  6046. }
  6047. function addLineWidget(doc, handle, node, options) {
  6048. var widget = new LineWidget(doc, node, options);
  6049. var cm = doc.cm;
  6050. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  6051. changeLine(doc, handle, "widget", function(line) {
  6052. var widgets = line.widgets || (line.widgets = []);
  6053. if (widget.insertAt == null) widgets.push(widget);
  6054. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  6055. widget.line = line;
  6056. if (cm && !lineIsHidden(doc, line)) {
  6057. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  6058. updateLineHeight(line, line.height + widgetHeight(widget));
  6059. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  6060. cm.curOp.forceUpdate = true;
  6061. }
  6062. return true;
  6063. });
  6064. return widget;
  6065. }
  6066. // LINE DATA STRUCTURE
  6067. // Line objects. These hold state related to a line, including
  6068. // highlighting info (the styles array).
  6069. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  6070. this.text = text;
  6071. attachMarkedSpans(this, markedSpans);
  6072. this.height = estimateHeight ? estimateHeight(this) : 1;
  6073. };
  6074. eventMixin(Line);
  6075. Line.prototype.lineNo = function() { return lineNo(this); };
  6076. // Change the content (text, markers) of a line. Automatically
  6077. // invalidates cached information and tries to re-estimate the
  6078. // line's height.
  6079. function updateLine(line, text, markedSpans, estimateHeight) {
  6080. line.text = text;
  6081. if (line.stateAfter) line.stateAfter = null;
  6082. if (line.styles) line.styles = null;
  6083. if (line.order != null) line.order = null;
  6084. detachMarkedSpans(line);
  6085. attachMarkedSpans(line, markedSpans);
  6086. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  6087. if (estHeight != line.height) updateLineHeight(line, estHeight);
  6088. }
  6089. // Detach a line from the document tree and its markers.
  6090. function cleanUpLine(line) {
  6091. line.parent = null;
  6092. detachMarkedSpans(line);
  6093. }
  6094. function extractLineClasses(type, output) {
  6095. if (type) for (;;) {
  6096. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  6097. if (!lineClass) break;
  6098. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  6099. var prop = lineClass[1] ? "bgClass" : "textClass";
  6100. if (output[prop] == null)
  6101. output[prop] = lineClass[2];
  6102. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  6103. output[prop] += " " + lineClass[2];
  6104. }
  6105. return type;
  6106. }
  6107. function callBlankLine(mode, state) {
  6108. if (mode.blankLine) return mode.blankLine(state);
  6109. if (!mode.innerMode) return;
  6110. var inner = CodeMirror.innerMode(mode, state);
  6111. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  6112. }
  6113. function readToken(mode, stream, state, inner) {
  6114. for (var i = 0; i < 10; i++) {
  6115. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  6116. var style = mode.token(stream, state);
  6117. if (stream.pos > stream.start) return style;
  6118. }
  6119. throw new Error("Mode " + mode.name + " failed to advance stream.");
  6120. }
  6121. // Utility for getTokenAt and getLineTokens
  6122. function takeToken(cm, pos, precise, asArray) {
  6123. function getObj(copy) {
  6124. return {start: stream.start, end: stream.pos,
  6125. string: stream.current(),
  6126. type: style || null,
  6127. state: copy ? copyState(doc.mode, state) : state};
  6128. }
  6129. var doc = cm.doc, mode = doc.mode, style;
  6130. pos = clipPos(doc, pos);
  6131. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  6132. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  6133. if (asArray) tokens = [];
  6134. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  6135. stream.start = stream.pos;
  6136. style = readToken(mode, stream, state);
  6137. if (asArray) tokens.push(getObj(true));
  6138. }
  6139. return asArray ? tokens : getObj();
  6140. }
  6141. // Run the given mode's parser over a line, calling f for each token.
  6142. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  6143. var flattenSpans = mode.flattenSpans;
  6144. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  6145. var curStart = 0, curStyle = null;
  6146. var stream = new StringStream(text, cm.options.tabSize), style;
  6147. var inner = cm.options.addModeClass && [null];
  6148. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  6149. while (!stream.eol()) {
  6150. if (stream.pos > cm.options.maxHighlightLength) {
  6151. flattenSpans = false;
  6152. if (forceToEnd) processLine(cm, text, state, stream.pos);
  6153. stream.pos = text.length;
  6154. style = null;
  6155. } else {
  6156. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  6157. }
  6158. if (inner) {
  6159. var mName = inner[0].name;
  6160. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  6161. }
  6162. if (!flattenSpans || curStyle != style) {
  6163. while (curStart < stream.start) {
  6164. curStart = Math.min(stream.start, curStart + 50000);
  6165. f(curStart, curStyle);
  6166. }
  6167. curStyle = style;
  6168. }
  6169. stream.start = stream.pos;
  6170. }
  6171. while (curStart < stream.pos) {
  6172. // Webkit seems to refuse to render text nodes longer than 57444 characters
  6173. var pos = Math.min(stream.pos, curStart + 50000);
  6174. f(pos, curStyle);
  6175. curStart = pos;
  6176. }
  6177. }
  6178. // Compute a style array (an array starting with a mode generation
  6179. // -- for invalidation -- followed by pairs of end positions and
  6180. // style strings), which is used to highlight the tokens on the
  6181. // line.
  6182. function highlightLine(cm, line, state, forceToEnd) {
  6183. // A styles array always starts with a number identifying the
  6184. // mode/overlays that it is based on (for easy invalidation).
  6185. var st = [cm.state.modeGen], lineClasses = {};
  6186. // Compute the base array of styles
  6187. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  6188. st.push(end, style);
  6189. }, lineClasses, forceToEnd);
  6190. // Run overlays, adjust style array.
  6191. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6192. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6193. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  6194. var start = i;
  6195. // Ensure there's a token end at the current position, and that i points at it
  6196. while (at < end) {
  6197. var i_end = st[i];
  6198. if (i_end > end)
  6199. st.splice(i, 1, end, st[i+1], i_end);
  6200. i += 2;
  6201. at = Math.min(end, i_end);
  6202. }
  6203. if (!style) return;
  6204. if (overlay.opaque) {
  6205. st.splice(start, i - start, end, "cm-overlay " + style);
  6206. i = start + 2;
  6207. } else {
  6208. for (; start < i; start += 2) {
  6209. var cur = st[start+1];
  6210. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6211. }
  6212. }
  6213. }, lineClasses);
  6214. }
  6215. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  6216. }
  6217. function getLineStyles(cm, line, updateFrontier) {
  6218. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6219. var state = getStateBefore(cm, lineNo(line));
  6220. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  6221. line.stateAfter = state;
  6222. line.styles = result.styles;
  6223. if (result.classes) line.styleClasses = result.classes;
  6224. else if (line.styleClasses) line.styleClasses = null;
  6225. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6226. }
  6227. return line.styles;
  6228. }
  6229. // Lightweight form of highlight -- proceed over this line and
  6230. // update state, but don't save a style array. Used for lines that
  6231. // aren't currently visible.
  6232. function processLine(cm, text, state, startAt) {
  6233. var mode = cm.doc.mode;
  6234. var stream = new StringStream(text, cm.options.tabSize);
  6235. stream.start = stream.pos = startAt || 0;
  6236. if (text == "") callBlankLine(mode, state);
  6237. while (!stream.eol()) {
  6238. readToken(mode, stream, state);
  6239. stream.start = stream.pos;
  6240. }
  6241. }
  6242. // Convert a style as returned by a mode (either null, or a string
  6243. // containing one or more styles) to a CSS style. This is cached,
  6244. // and also looks for line-wide styles.
  6245. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6246. function interpretTokenStyle(style, options) {
  6247. if (!style || /^\s*$/.test(style)) return null;
  6248. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6249. return cache[style] ||
  6250. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6251. }
  6252. // Render the DOM representation of the text of a line. Also builds
  6253. // up a 'line map', which points at the DOM nodes that represent
  6254. // specific stretches of text, and is used by the measuring code.
  6255. // The returned object contains the DOM node, this map, and
  6256. // information about line-wide styles that were set by the mode.
  6257. function buildLineContent(cm, lineView) {
  6258. // The padding-right forces the element to have a 'border', which
  6259. // is needed on Webkit to be able to get line-level bounding
  6260. // rectangles for it (in measureChar).
  6261. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6262. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  6263. col: 0, pos: 0, cm: cm,
  6264. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  6265. lineView.measure = {};
  6266. // Iterate over the logical lines that make up this visual line.
  6267. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6268. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6269. builder.pos = 0;
  6270. builder.addToken = buildToken;
  6271. // Optionally wire in some hacks into the token-rendering
  6272. // algorithm, to deal with browser quirks.
  6273. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6274. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6275. builder.map = [];
  6276. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6277. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6278. if (line.styleClasses) {
  6279. if (line.styleClasses.bgClass)
  6280. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6281. if (line.styleClasses.textClass)
  6282. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6283. }
  6284. // Ensure at least a single node is present, for measuring.
  6285. if (builder.map.length == 0)
  6286. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6287. // Store the map and a cache object for the current logical line
  6288. if (i == 0) {
  6289. lineView.measure.map = builder.map;
  6290. lineView.measure.cache = {};
  6291. } else {
  6292. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6293. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6294. }
  6295. }
  6296. // See issue #2901
  6297. if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
  6298. builder.content.className = "cm-tab-wrap-hack";
  6299. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6300. if (builder.pre.className)
  6301. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6302. return builder;
  6303. }
  6304. function defaultSpecialCharPlaceholder(ch) {
  6305. var token = elt("span", "\u2022", "cm-invalidchar");
  6306. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6307. token.setAttribute("aria-label", token.title);
  6308. return token;
  6309. }
  6310. // Build up the DOM representation for a single token, and add it to
  6311. // the line map. Takes care to render special characters separately.
  6312. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6313. if (!text) return;
  6314. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  6315. var special = builder.cm.state.specialChars, mustWrap = false;
  6316. if (!special.test(text)) {
  6317. builder.col += text.length;
  6318. var content = document.createTextNode(displayText);
  6319. builder.map.push(builder.pos, builder.pos + text.length, content);
  6320. if (ie && ie_version < 9) mustWrap = true;
  6321. builder.pos += text.length;
  6322. } else {
  6323. var content = document.createDocumentFragment(), pos = 0;
  6324. while (true) {
  6325. special.lastIndex = pos;
  6326. var m = special.exec(text);
  6327. var skipped = m ? m.index - pos : text.length - pos;
  6328. if (skipped) {
  6329. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  6330. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6331. else content.appendChild(txt);
  6332. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6333. builder.col += skipped;
  6334. builder.pos += skipped;
  6335. }
  6336. if (!m) break;
  6337. pos += skipped + 1;
  6338. if (m[0] == "\t") {
  6339. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6340. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6341. txt.setAttribute("role", "presentation");
  6342. txt.setAttribute("cm-text", "\t");
  6343. builder.col += tabWidth;
  6344. } else if (m[0] == "\r" || m[0] == "\n") {
  6345. var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  6346. txt.setAttribute("cm-text", m[0]);
  6347. builder.col += 1;
  6348. } else {
  6349. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6350. txt.setAttribute("cm-text", m[0]);
  6351. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6352. else content.appendChild(txt);
  6353. builder.col += 1;
  6354. }
  6355. builder.map.push(builder.pos, builder.pos + 1, txt);
  6356. builder.pos++;
  6357. }
  6358. }
  6359. if (style || startStyle || endStyle || mustWrap || css) {
  6360. var fullStyle = style || "";
  6361. if (startStyle) fullStyle += startStyle;
  6362. if (endStyle) fullStyle += endStyle;
  6363. var token = elt("span", [content], fullStyle, css);
  6364. if (title) token.title = title;
  6365. return builder.content.appendChild(token);
  6366. }
  6367. builder.content.appendChild(content);
  6368. }
  6369. function splitSpaces(old) {
  6370. var out = " ";
  6371. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  6372. out += " ";
  6373. return out;
  6374. }
  6375. // Work around nonsense dimensions being reported for stretches of
  6376. // right-to-left text.
  6377. function buildTokenBadBidi(inner, order) {
  6378. return function(builder, text, style, startStyle, endStyle, title, css) {
  6379. style = style ? style + " cm-force-border" : "cm-force-border";
  6380. var start = builder.pos, end = start + text.length;
  6381. for (;;) {
  6382. // Find the part that overlaps with the start of this text
  6383. for (var i = 0; i < order.length; i++) {
  6384. var part = order[i];
  6385. if (part.to > start && part.from <= start) break;
  6386. }
  6387. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  6388. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  6389. startStyle = null;
  6390. text = text.slice(part.to - start);
  6391. start = part.to;
  6392. }
  6393. };
  6394. }
  6395. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6396. var widget = !ignoreWidget && marker.widgetNode;
  6397. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6398. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6399. if (!widget)
  6400. widget = builder.content.appendChild(document.createElement("span"));
  6401. widget.setAttribute("cm-marker", marker.id);
  6402. }
  6403. if (widget) {
  6404. builder.cm.display.input.setUneditable(widget);
  6405. builder.content.appendChild(widget);
  6406. }
  6407. builder.pos += size;
  6408. }
  6409. // Outputs a number of spans to make up a line, taking highlighting
  6410. // and marked text into account.
  6411. function insertLineContent(line, builder, styles) {
  6412. var spans = line.markedSpans, allText = line.text, at = 0;
  6413. if (!spans) {
  6414. for (var i = 1; i < styles.length; i+=2)
  6415. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  6416. return;
  6417. }
  6418. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6419. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6420. for (;;) {
  6421. if (nextChange == pos) { // Update current marker set
  6422. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6423. collapsed = null; nextChange = Infinity;
  6424. var foundBookmarks = [], endStyles
  6425. for (var j = 0; j < spans.length; ++j) {
  6426. var sp = spans[j], m = sp.marker;
  6427. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  6428. foundBookmarks.push(m);
  6429. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  6430. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  6431. nextChange = sp.to;
  6432. spanEndStyle = "";
  6433. }
  6434. if (m.className) spanStyle += " " + m.className;
  6435. if (m.css) css = (css ? css + ";" : "") + m.css;
  6436. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6437. if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  6438. if (m.title && !title) title = m.title;
  6439. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6440. collapsed = sp;
  6441. } else if (sp.from > pos && nextChange > sp.from) {
  6442. nextChange = sp.from;
  6443. }
  6444. }
  6445. if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
  6446. if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  6447. if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
  6448. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6449. if (collapsed && (collapsed.from || 0) == pos) {
  6450. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6451. collapsed.marker, collapsed.from == null);
  6452. if (collapsed.to == null) return;
  6453. if (collapsed.to == pos) collapsed = false;
  6454. }
  6455. }
  6456. if (pos >= len) break;
  6457. var upto = Math.min(len, nextChange);
  6458. while (true) {
  6459. if (text) {
  6460. var end = pos + text.length;
  6461. if (!collapsed) {
  6462. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6463. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6464. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6465. }
  6466. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  6467. pos = end;
  6468. spanStartStyle = "";
  6469. }
  6470. text = allText.slice(at, at = styles[i++]);
  6471. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6472. }
  6473. }
  6474. }
  6475. // DOCUMENT DATA STRUCTURE
  6476. // By default, updates that start and end at the beginning of a line
  6477. // are treated specially, in order to make the association of line
  6478. // widgets and marker elements with the text behave more intuitive.
  6479. function isWholeLineUpdate(doc, change) {
  6480. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6481. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6482. }
  6483. // Perform a change on the document data structure.
  6484. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6485. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  6486. function update(line, text, spans) {
  6487. updateLine(line, text, spans, estimateHeight);
  6488. signalLater(line, "change", line, change);
  6489. }
  6490. function linesFor(start, end) {
  6491. for (var i = start, result = []; i < end; ++i)
  6492. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6493. return result;
  6494. }
  6495. var from = change.from, to = change.to, text = change.text;
  6496. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6497. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6498. // Adjust the line structure
  6499. if (change.full) {
  6500. doc.insert(0, linesFor(0, text.length));
  6501. doc.remove(text.length, doc.size - text.length);
  6502. } else if (isWholeLineUpdate(doc, change)) {
  6503. // This is a whole-line replace. Treated specially to make
  6504. // sure line objects move the way they are supposed to.
  6505. var added = linesFor(0, text.length - 1);
  6506. update(lastLine, lastLine.text, lastSpans);
  6507. if (nlines) doc.remove(from.line, nlines);
  6508. if (added.length) doc.insert(from.line, added);
  6509. } else if (firstLine == lastLine) {
  6510. if (text.length == 1) {
  6511. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6512. } else {
  6513. var added = linesFor(1, text.length - 1);
  6514. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6515. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6516. doc.insert(from.line + 1, added);
  6517. }
  6518. } else if (text.length == 1) {
  6519. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6520. doc.remove(from.line + 1, nlines);
  6521. } else {
  6522. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6523. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6524. var added = linesFor(1, text.length - 1);
  6525. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6526. doc.insert(from.line + 1, added);
  6527. }
  6528. signalLater(doc, "change", doc, change);
  6529. }
  6530. // The document is represented as a BTree consisting of leaves, with
  6531. // chunk of lines in them, and branches, with up to ten leaves or
  6532. // other branch nodes below them. The top node is always a branch
  6533. // node, and is the document object itself (meaning it has
  6534. // additional methods and properties).
  6535. //
  6536. // All nodes have parent links. The tree is used both to go from
  6537. // line numbers to line objects, and to go from objects to numbers.
  6538. // It also indexes by height, and is used to convert between height
  6539. // and line object, and to find the total height of the document.
  6540. //
  6541. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6542. function LeafChunk(lines) {
  6543. this.lines = lines;
  6544. this.parent = null;
  6545. for (var i = 0, height = 0; i < lines.length; ++i) {
  6546. lines[i].parent = this;
  6547. height += lines[i].height;
  6548. }
  6549. this.height = height;
  6550. }
  6551. LeafChunk.prototype = {
  6552. chunkSize: function() { return this.lines.length; },
  6553. // Remove the n lines at offset 'at'.
  6554. removeInner: function(at, n) {
  6555. for (var i = at, e = at + n; i < e; ++i) {
  6556. var line = this.lines[i];
  6557. this.height -= line.height;
  6558. cleanUpLine(line);
  6559. signalLater(line, "delete");
  6560. }
  6561. this.lines.splice(at, n);
  6562. },
  6563. // Helper used to collapse a small branch into a single leaf.
  6564. collapse: function(lines) {
  6565. lines.push.apply(lines, this.lines);
  6566. },
  6567. // Insert the given array of lines at offset 'at', count them as
  6568. // having the given height.
  6569. insertInner: function(at, lines, height) {
  6570. this.height += height;
  6571. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6572. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6573. },
  6574. // Used to iterate over a part of the tree.
  6575. iterN: function(at, n, op) {
  6576. for (var e = at + n; at < e; ++at)
  6577. if (op(this.lines[at])) return true;
  6578. }
  6579. };
  6580. function BranchChunk(children) {
  6581. this.children = children;
  6582. var size = 0, height = 0;
  6583. for (var i = 0; i < children.length; ++i) {
  6584. var ch = children[i];
  6585. size += ch.chunkSize(); height += ch.height;
  6586. ch.parent = this;
  6587. }
  6588. this.size = size;
  6589. this.height = height;
  6590. this.parent = null;
  6591. }
  6592. BranchChunk.prototype = {
  6593. chunkSize: function() { return this.size; },
  6594. removeInner: function(at, n) {
  6595. this.size -= n;
  6596. for (var i = 0; i < this.children.length; ++i) {
  6597. var child = this.children[i], sz = child.chunkSize();
  6598. if (at < sz) {
  6599. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6600. child.removeInner(at, rm);
  6601. this.height -= oldHeight - child.height;
  6602. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6603. if ((n -= rm) == 0) break;
  6604. at = 0;
  6605. } else at -= sz;
  6606. }
  6607. // If the result is smaller than 25 lines, ensure that it is a
  6608. // single leaf node.
  6609. if (this.size - n < 25 &&
  6610. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6611. var lines = [];
  6612. this.collapse(lines);
  6613. this.children = [new LeafChunk(lines)];
  6614. this.children[0].parent = this;
  6615. }
  6616. },
  6617. collapse: function(lines) {
  6618. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6619. },
  6620. insertInner: function(at, lines, height) {
  6621. this.size += lines.length;
  6622. this.height += height;
  6623. for (var i = 0; i < this.children.length; ++i) {
  6624. var child = this.children[i], sz = child.chunkSize();
  6625. if (at <= sz) {
  6626. child.insertInner(at, lines, height);
  6627. if (child.lines && child.lines.length > 50) {
  6628. while (child.lines.length > 50) {
  6629. var spilled = child.lines.splice(child.lines.length - 25, 25);
  6630. var newleaf = new LeafChunk(spilled);
  6631. child.height -= newleaf.height;
  6632. this.children.splice(i + 1, 0, newleaf);
  6633. newleaf.parent = this;
  6634. }
  6635. this.maybeSpill();
  6636. }
  6637. break;
  6638. }
  6639. at -= sz;
  6640. }
  6641. },
  6642. // When a node has grown, check whether it should be split.
  6643. maybeSpill: function() {
  6644. if (this.children.length <= 10) return;
  6645. var me = this;
  6646. do {
  6647. var spilled = me.children.splice(me.children.length - 5, 5);
  6648. var sibling = new BranchChunk(spilled);
  6649. if (!me.parent) { // Become the parent node
  6650. var copy = new BranchChunk(me.children);
  6651. copy.parent = me;
  6652. me.children = [copy, sibling];
  6653. me = copy;
  6654. } else {
  6655. me.size -= sibling.size;
  6656. me.height -= sibling.height;
  6657. var myIndex = indexOf(me.parent.children, me);
  6658. me.parent.children.splice(myIndex + 1, 0, sibling);
  6659. }
  6660. sibling.parent = me.parent;
  6661. } while (me.children.length > 10);
  6662. me.parent.maybeSpill();
  6663. },
  6664. iterN: function(at, n, op) {
  6665. for (var i = 0; i < this.children.length; ++i) {
  6666. var child = this.children[i], sz = child.chunkSize();
  6667. if (at < sz) {
  6668. var used = Math.min(n, sz - at);
  6669. if (child.iterN(at, used, op)) return true;
  6670. if ((n -= used) == 0) break;
  6671. at = 0;
  6672. } else at -= sz;
  6673. }
  6674. }
  6675. };
  6676. var nextDocId = 0;
  6677. var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
  6678. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
  6679. if (firstLine == null) firstLine = 0;
  6680. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6681. this.first = firstLine;
  6682. this.scrollTop = this.scrollLeft = 0;
  6683. this.cantEdit = false;
  6684. this.cleanGeneration = 1;
  6685. this.frontier = firstLine;
  6686. var start = Pos(firstLine, 0);
  6687. this.sel = simpleSelection(start);
  6688. this.history = new History(null);
  6689. this.id = ++nextDocId;
  6690. this.modeOption = mode;
  6691. this.lineSep = lineSep;
  6692. this.extend = false;
  6693. if (typeof text == "string") text = this.splitLines(text);
  6694. updateDoc(this, {from: start, to: start, text: text});
  6695. setSelection(this, simpleSelection(start), sel_dontScroll);
  6696. };
  6697. Doc.prototype = createObj(BranchChunk.prototype, {
  6698. constructor: Doc,
  6699. // Iterate over the document. Supports two forms -- with only one
  6700. // argument, it calls that for each line in the document. With
  6701. // three, it iterates over the range given by the first two (with
  6702. // the second being non-inclusive).
  6703. iter: function(from, to, op) {
  6704. if (op) this.iterN(from - this.first, to - from, op);
  6705. else this.iterN(this.first, this.first + this.size, from);
  6706. },
  6707. // Non-public interface for adding and removing lines.
  6708. insert: function(at, lines) {
  6709. var height = 0;
  6710. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6711. this.insertInner(at - this.first, lines, height);
  6712. },
  6713. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6714. // From here, the methods are part of the public interface. Most
  6715. // are also available from CodeMirror (editor) instances.
  6716. getValue: function(lineSep) {
  6717. var lines = getLines(this, this.first, this.first + this.size);
  6718. if (lineSep === false) return lines;
  6719. return lines.join(lineSep || this.lineSeparator());
  6720. },
  6721. setValue: docMethodOp(function(code) {
  6722. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6723. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6724. text: this.splitLines(code), origin: "setValue", full: true}, true);
  6725. setSelection(this, simpleSelection(top));
  6726. }),
  6727. replaceRange: function(code, from, to, origin) {
  6728. from = clipPos(this, from);
  6729. to = to ? clipPos(this, to) : from;
  6730. replaceRange(this, code, from, to, origin);
  6731. },
  6732. getRange: function(from, to, lineSep) {
  6733. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6734. if (lineSep === false) return lines;
  6735. return lines.join(lineSep || this.lineSeparator());
  6736. },
  6737. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6738. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6739. getLineNumber: function(line) {return lineNo(line);},
  6740. getLineHandleVisualStart: function(line) {
  6741. if (typeof line == "number") line = getLine(this, line);
  6742. return visualLine(line);
  6743. },
  6744. lineCount: function() {return this.size;},
  6745. firstLine: function() {return this.first;},
  6746. lastLine: function() {return this.first + this.size - 1;},
  6747. clipPos: function(pos) {return clipPos(this, pos);},
  6748. getCursor: function(start) {
  6749. var range = this.sel.primary(), pos;
  6750. if (start == null || start == "head") pos = range.head;
  6751. else if (start == "anchor") pos = range.anchor;
  6752. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6753. else pos = range.from();
  6754. return pos;
  6755. },
  6756. listSelections: function() { return this.sel.ranges; },
  6757. somethingSelected: function() {return this.sel.somethingSelected();},
  6758. setCursor: docMethodOp(function(line, ch, options) {
  6759. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6760. }),
  6761. setSelection: docMethodOp(function(anchor, head, options) {
  6762. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6763. }),
  6764. extendSelection: docMethodOp(function(head, other, options) {
  6765. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6766. }),
  6767. extendSelections: docMethodOp(function(heads, options) {
  6768. extendSelections(this, clipPosArray(this, heads), options);
  6769. }),
  6770. extendSelectionsBy: docMethodOp(function(f, options) {
  6771. var heads = map(this.sel.ranges, f);
  6772. extendSelections(this, clipPosArray(this, heads), options);
  6773. }),
  6774. setSelections: docMethodOp(function(ranges, primary, options) {
  6775. if (!ranges.length) return;
  6776. for (var i = 0, out = []; i < ranges.length; i++)
  6777. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6778. clipPos(this, ranges[i].head));
  6779. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6780. setSelection(this, normalizeSelection(out, primary), options);
  6781. }),
  6782. addSelection: docMethodOp(function(anchor, head, options) {
  6783. var ranges = this.sel.ranges.slice(0);
  6784. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6785. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6786. }),
  6787. getSelection: function(lineSep) {
  6788. var ranges = this.sel.ranges, lines;
  6789. for (var i = 0; i < ranges.length; i++) {
  6790. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6791. lines = lines ? lines.concat(sel) : sel;
  6792. }
  6793. if (lineSep === false) return lines;
  6794. else return lines.join(lineSep || this.lineSeparator());
  6795. },
  6796. getSelections: function(lineSep) {
  6797. var parts = [], ranges = this.sel.ranges;
  6798. for (var i = 0; i < ranges.length; i++) {
  6799. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6800. if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
  6801. parts[i] = sel;
  6802. }
  6803. return parts;
  6804. },
  6805. replaceSelection: function(code, collapse, origin) {
  6806. var dup = [];
  6807. for (var i = 0; i < this.sel.ranges.length; i++)
  6808. dup[i] = code;
  6809. this.replaceSelections(dup, collapse, origin || "+input");
  6810. },
  6811. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6812. var changes = [], sel = this.sel;
  6813. for (var i = 0; i < sel.ranges.length; i++) {
  6814. var range = sel.ranges[i];
  6815. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  6816. }
  6817. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6818. for (var i = changes.length - 1; i >= 0; i--)
  6819. makeChange(this, changes[i]);
  6820. if (newSel) setSelectionReplaceHistory(this, newSel);
  6821. else if (this.cm) ensureCursorVisible(this.cm);
  6822. }),
  6823. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6824. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6825. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6826. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6827. setExtending: function(val) {this.extend = val;},
  6828. getExtending: function() {return this.extend;},
  6829. historySize: function() {
  6830. var hist = this.history, done = 0, undone = 0;
  6831. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6832. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6833. return {undo: done, redo: undone};
  6834. },
  6835. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6836. markClean: function() {
  6837. this.cleanGeneration = this.changeGeneration(true);
  6838. },
  6839. changeGeneration: function(forceSplit) {
  6840. if (forceSplit)
  6841. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6842. return this.history.generation;
  6843. },
  6844. isClean: function (gen) {
  6845. return this.history.generation == (gen || this.cleanGeneration);
  6846. },
  6847. getHistory: function() {
  6848. return {done: copyHistoryArray(this.history.done),
  6849. undone: copyHistoryArray(this.history.undone)};
  6850. },
  6851. setHistory: function(histData) {
  6852. var hist = this.history = new History(this.history.maxGeneration);
  6853. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6854. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6855. },
  6856. addLineClass: docMethodOp(function(handle, where, cls) {
  6857. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6858. var prop = where == "text" ? "textClass"
  6859. : where == "background" ? "bgClass"
  6860. : where == "gutter" ? "gutterClass" : "wrapClass";
  6861. if (!line[prop]) line[prop] = cls;
  6862. else if (classTest(cls).test(line[prop])) return false;
  6863. else line[prop] += " " + cls;
  6864. return true;
  6865. });
  6866. }),
  6867. removeLineClass: docMethodOp(function(handle, where, cls) {
  6868. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6869. var prop = where == "text" ? "textClass"
  6870. : where == "background" ? "bgClass"
  6871. : where == "gutter" ? "gutterClass" : "wrapClass";
  6872. var cur = line[prop];
  6873. if (!cur) return false;
  6874. else if (cls == null) line[prop] = null;
  6875. else {
  6876. var found = cur.match(classTest(cls));
  6877. if (!found) return false;
  6878. var end = found.index + found[0].length;
  6879. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6880. }
  6881. return true;
  6882. });
  6883. }),
  6884. addLineWidget: docMethodOp(function(handle, node, options) {
  6885. return addLineWidget(this, handle, node, options);
  6886. }),
  6887. removeLineWidget: function(widget) { widget.clear(); },
  6888. markText: function(from, to, options) {
  6889. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
  6890. },
  6891. setBookmark: function(pos, options) {
  6892. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6893. insertLeft: options && options.insertLeft,
  6894. clearWhenEmpty: false, shared: options && options.shared,
  6895. handleMouseEvents: options && options.handleMouseEvents};
  6896. pos = clipPos(this, pos);
  6897. return markText(this, pos, pos, realOpts, "bookmark");
  6898. },
  6899. findMarksAt: function(pos) {
  6900. pos = clipPos(this, pos);
  6901. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6902. if (spans) for (var i = 0; i < spans.length; ++i) {
  6903. var span = spans[i];
  6904. if ((span.from == null || span.from <= pos.ch) &&
  6905. (span.to == null || span.to >= pos.ch))
  6906. markers.push(span.marker.parent || span.marker);
  6907. }
  6908. return markers;
  6909. },
  6910. findMarks: function(from, to, filter) {
  6911. from = clipPos(this, from); to = clipPos(this, to);
  6912. var found = [], lineNo = from.line;
  6913. this.iter(from.line, to.line + 1, function(line) {
  6914. var spans = line.markedSpans;
  6915. if (spans) for (var i = 0; i < spans.length; i++) {
  6916. var span = spans[i];
  6917. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  6918. span.from == null && lineNo != from.line ||
  6919. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  6920. (!filter || filter(span.marker)))
  6921. found.push(span.marker.parent || span.marker);
  6922. }
  6923. ++lineNo;
  6924. });
  6925. return found;
  6926. },
  6927. getAllMarks: function() {
  6928. var markers = [];
  6929. this.iter(function(line) {
  6930. var sps = line.markedSpans;
  6931. if (sps) for (var i = 0; i < sps.length; ++i)
  6932. if (sps[i].from != null) markers.push(sps[i].marker);
  6933. });
  6934. return markers;
  6935. },
  6936. posFromIndex: function(off) {
  6937. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  6938. this.iter(function(line) {
  6939. var sz = line.text.length + sepSize;
  6940. if (sz > off) { ch = off; return true; }
  6941. off -= sz;
  6942. ++lineNo;
  6943. });
  6944. return clipPos(this, Pos(lineNo, ch));
  6945. },
  6946. indexFromPos: function (coords) {
  6947. coords = clipPos(this, coords);
  6948. var index = coords.ch;
  6949. if (coords.line < this.first || coords.ch < 0) return 0;
  6950. var sepSize = this.lineSeparator().length;
  6951. this.iter(this.first, coords.line, function (line) {
  6952. index += line.text.length + sepSize;
  6953. });
  6954. return index;
  6955. },
  6956. copy: function(copyHistory) {
  6957. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  6958. this.modeOption, this.first, this.lineSep);
  6959. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6960. doc.sel = this.sel;
  6961. doc.extend = false;
  6962. if (copyHistory) {
  6963. doc.history.undoDepth = this.history.undoDepth;
  6964. doc.setHistory(this.getHistory());
  6965. }
  6966. return doc;
  6967. },
  6968. linkedDoc: function(options) {
  6969. if (!options) options = {};
  6970. var from = this.first, to = this.first + this.size;
  6971. if (options.from != null && options.from > from) from = options.from;
  6972. if (options.to != null && options.to < to) to = options.to;
  6973. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
  6974. if (options.sharedHist) copy.history = this.history;
  6975. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6976. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6977. copySharedMarkers(copy, findSharedMarkers(this));
  6978. return copy;
  6979. },
  6980. unlinkDoc: function(other) {
  6981. if (other instanceof CodeMirror) other = other.doc;
  6982. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6983. var link = this.linked[i];
  6984. if (link.doc != other) continue;
  6985. this.linked.splice(i, 1);
  6986. other.unlinkDoc(this);
  6987. detachSharedMarkers(findSharedMarkers(this));
  6988. break;
  6989. }
  6990. // If the histories were shared, split them again
  6991. if (other.history == this.history) {
  6992. var splitIds = [other.id];
  6993. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  6994. other.history = new History(null);
  6995. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6996. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6997. }
  6998. },
  6999. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  7000. getMode: function() {return this.mode;},
  7001. getEditor: function() {return this.cm;},
  7002. splitLines: function(str) {
  7003. if (this.lineSep) return str.split(this.lineSep);
  7004. return splitLinesAuto(str);
  7005. },
  7006. lineSeparator: function() { return this.lineSep || "\n"; }
  7007. });
  7008. // Public alias.
  7009. Doc.prototype.eachLine = Doc.prototype.iter;
  7010. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  7011. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  7012. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  7013. CodeMirror.prototype[prop] = (function(method) {
  7014. return function() {return method.apply(this.doc, arguments);};
  7015. })(Doc.prototype[prop]);
  7016. eventMixin(Doc);
  7017. // Call f for all linked documents.
  7018. function linkedDocs(doc, f, sharedHistOnly) {
  7019. function propagate(doc, skip, sharedHist) {
  7020. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  7021. var rel = doc.linked[i];
  7022. if (rel.doc == skip) continue;
  7023. var shared = sharedHist && rel.sharedHist;
  7024. if (sharedHistOnly && !shared) continue;
  7025. f(rel.doc, shared);
  7026. propagate(rel.doc, doc, shared);
  7027. }
  7028. }
  7029. propagate(doc, null, true);
  7030. }
  7031. // Attach a document to an editor.
  7032. function attachDoc(cm, doc) {
  7033. if (doc.cm) throw new Error("This document is already in use.");
  7034. cm.doc = doc;
  7035. doc.cm = cm;
  7036. estimateLineHeights(cm);
  7037. loadMode(cm);
  7038. if (!cm.options.lineWrapping) findMaxLine(cm);
  7039. cm.options.mode = doc.modeOption;
  7040. regChange(cm);
  7041. }
  7042. // LINE UTILITIES
  7043. // Find the line object corresponding to the given line number.
  7044. function getLine(doc, n) {
  7045. n -= doc.first;
  7046. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  7047. for (var chunk = doc; !chunk.lines;) {
  7048. for (var i = 0;; ++i) {
  7049. var child = chunk.children[i], sz = child.chunkSize();
  7050. if (n < sz) { chunk = child; break; }
  7051. n -= sz;
  7052. }
  7053. }
  7054. return chunk.lines[n];
  7055. }
  7056. // Get the part of a document between two positions, as an array of
  7057. // strings.
  7058. function getBetween(doc, start, end) {
  7059. var out = [], n = start.line;
  7060. doc.iter(start.line, end.line + 1, function(line) {
  7061. var text = line.text;
  7062. if (n == end.line) text = text.slice(0, end.ch);
  7063. if (n == start.line) text = text.slice(start.ch);
  7064. out.push(text);
  7065. ++n;
  7066. });
  7067. return out;
  7068. }
  7069. // Get the lines between from and to, as array of strings.
  7070. function getLines(doc, from, to) {
  7071. var out = [];
  7072. doc.iter(from, to, function(line) { out.push(line.text); });
  7073. return out;
  7074. }
  7075. // Update the height of a line, propagating the height change
  7076. // upwards to parent nodes.
  7077. function updateLineHeight(line, height) {
  7078. var diff = height - line.height;
  7079. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  7080. }
  7081. // Given a line object, find its line number by walking up through
  7082. // its parent links.
  7083. function lineNo(line) {
  7084. if (line.parent == null) return null;
  7085. var cur = line.parent, no = indexOf(cur.lines, line);
  7086. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  7087. for (var i = 0;; ++i) {
  7088. if (chunk.children[i] == cur) break;
  7089. no += chunk.children[i].chunkSize();
  7090. }
  7091. }
  7092. return no + cur.first;
  7093. }
  7094. // Find the line at the given vertical position, using the height
  7095. // information in the document tree.
  7096. function lineAtHeight(chunk, h) {
  7097. var n = chunk.first;
  7098. outer: do {
  7099. for (var i = 0; i < chunk.children.length; ++i) {
  7100. var child = chunk.children[i], ch = child.height;
  7101. if (h < ch) { chunk = child; continue outer; }
  7102. h -= ch;
  7103. n += child.chunkSize();
  7104. }
  7105. return n;
  7106. } while (!chunk.lines);
  7107. for (var i = 0; i < chunk.lines.length; ++i) {
  7108. var line = chunk.lines[i], lh = line.height;
  7109. if (h < lh) break;
  7110. h -= lh;
  7111. }
  7112. return n + i;
  7113. }
  7114. // Find the height above the given line.
  7115. function heightAtLine(lineObj) {
  7116. lineObj = visualLine(lineObj);
  7117. var h = 0, chunk = lineObj.parent;
  7118. for (var i = 0; i < chunk.lines.length; ++i) {
  7119. var line = chunk.lines[i];
  7120. if (line == lineObj) break;
  7121. else h += line.height;
  7122. }
  7123. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  7124. for (var i = 0; i < p.children.length; ++i) {
  7125. var cur = p.children[i];
  7126. if (cur == chunk) break;
  7127. else h += cur.height;
  7128. }
  7129. }
  7130. return h;
  7131. }
  7132. // Get the bidi ordering for the given line (and cache it). Returns
  7133. // false for lines that are fully left-to-right, and an array of
  7134. // BidiSpan objects otherwise.
  7135. function getOrder(line) {
  7136. var order = line.order;
  7137. if (order == null) order = line.order = bidiOrdering(line.text);
  7138. return order;
  7139. }
  7140. // HISTORY
  7141. function History(startGen) {
  7142. // Arrays of change events and selections. Doing something adds an
  7143. // event to done and clears undo. Undoing moves events from done
  7144. // to undone, redoing moves them in the other direction.
  7145. this.done = []; this.undone = [];
  7146. this.undoDepth = Infinity;
  7147. // Used to track when changes can be merged into a single undo
  7148. // event
  7149. this.lastModTime = this.lastSelTime = 0;
  7150. this.lastOp = this.lastSelOp = null;
  7151. this.lastOrigin = this.lastSelOrigin = null;
  7152. // Used by the isClean() method
  7153. this.generation = this.maxGeneration = startGen || 1;
  7154. }
  7155. // Create a history change event from an updateDoc-style change
  7156. // object.
  7157. function historyChangeFromChange(doc, change) {
  7158. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  7159. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  7160. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  7161. return histChange;
  7162. }
  7163. // Pop all selection events off the end of a history array. Stop at
  7164. // a change event.
  7165. function clearSelectionEvents(array) {
  7166. while (array.length) {
  7167. var last = lst(array);
  7168. if (last.ranges) array.pop();
  7169. else break;
  7170. }
  7171. }
  7172. // Find the top change event in the history. Pop off selection
  7173. // events that are in the way.
  7174. function lastChangeEvent(hist, force) {
  7175. if (force) {
  7176. clearSelectionEvents(hist.done);
  7177. return lst(hist.done);
  7178. } else if (hist.done.length && !lst(hist.done).ranges) {
  7179. return lst(hist.done);
  7180. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  7181. hist.done.pop();
  7182. return lst(hist.done);
  7183. }
  7184. }
  7185. // Register a change in the history. Merges changes that are within
  7186. // a single operation, ore are close together with an origin that
  7187. // allows merging (starting with "+") into a single event.
  7188. function addChangeToHistory(doc, change, selAfter, opId) {
  7189. var hist = doc.history;
  7190. hist.undone.length = 0;
  7191. var time = +new Date, cur;
  7192. if ((hist.lastOp == opId ||
  7193. hist.lastOrigin == change.origin && change.origin &&
  7194. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  7195. change.origin.charAt(0) == "*")) &&
  7196. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  7197. // Merge this change into the last event
  7198. var last = lst(cur.changes);
  7199. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  7200. // Optimized case for simple insertion -- don't want to add
  7201. // new changesets for every character typed
  7202. last.to = changeEnd(change);
  7203. } else {
  7204. // Add new sub-event
  7205. cur.changes.push(historyChangeFromChange(doc, change));
  7206. }
  7207. } else {
  7208. // Can not be merged, start a new event.
  7209. var before = lst(hist.done);
  7210. if (!before || !before.ranges)
  7211. pushSelectionToHistory(doc.sel, hist.done);
  7212. cur = {changes: [historyChangeFromChange(doc, change)],
  7213. generation: hist.generation};
  7214. hist.done.push(cur);
  7215. while (hist.done.length > hist.undoDepth) {
  7216. hist.done.shift();
  7217. if (!hist.done[0].ranges) hist.done.shift();
  7218. }
  7219. }
  7220. hist.done.push(selAfter);
  7221. hist.generation = ++hist.maxGeneration;
  7222. hist.lastModTime = hist.lastSelTime = time;
  7223. hist.lastOp = hist.lastSelOp = opId;
  7224. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7225. if (!last) signal(doc, "historyAdded");
  7226. }
  7227. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7228. var ch = origin.charAt(0);
  7229. return ch == "*" ||
  7230. ch == "+" &&
  7231. prev.ranges.length == sel.ranges.length &&
  7232. prev.somethingSelected() == sel.somethingSelected() &&
  7233. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7234. }
  7235. // Called whenever the selection changes, sets the new selection as
  7236. // the pending selection in the history, and pushes the old pending
  7237. // selection into the 'done' array when it was significantly
  7238. // different (in number of selected ranges, emptiness, or time).
  7239. function addSelectionToHistory(doc, sel, opId, options) {
  7240. var hist = doc.history, origin = options && options.origin;
  7241. // A new event is started when the previous origin does not match
  7242. // the current, or the origins don't allow matching. Origins
  7243. // starting with * are always merged, those starting with + are
  7244. // merged when similar and close together in time.
  7245. if (opId == hist.lastSelOp ||
  7246. (origin && hist.lastSelOrigin == origin &&
  7247. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7248. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7249. hist.done[hist.done.length - 1] = sel;
  7250. else
  7251. pushSelectionToHistory(sel, hist.done);
  7252. hist.lastSelTime = +new Date;
  7253. hist.lastSelOrigin = origin;
  7254. hist.lastSelOp = opId;
  7255. if (options && options.clearRedo !== false)
  7256. clearSelectionEvents(hist.undone);
  7257. }
  7258. function pushSelectionToHistory(sel, dest) {
  7259. var top = lst(dest);
  7260. if (!(top && top.ranges && top.equals(sel)))
  7261. dest.push(sel);
  7262. }
  7263. // Used to store marked span information in the history.
  7264. function attachLocalSpans(doc, change, from, to) {
  7265. var existing = change["spans_" + doc.id], n = 0;
  7266. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  7267. if (line.markedSpans)
  7268. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7269. ++n;
  7270. });
  7271. }
  7272. // When un/re-doing restores text containing marked spans, those
  7273. // that have been explicitly cleared should not be restored.
  7274. function removeClearedSpans(spans) {
  7275. if (!spans) return null;
  7276. for (var i = 0, out; i < spans.length; ++i) {
  7277. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7278. else if (out) out.push(spans[i]);
  7279. }
  7280. return !out ? spans : out.length ? out : null;
  7281. }
  7282. // Retrieve and filter the old marked spans stored in a change event.
  7283. function getOldSpans(doc, change) {
  7284. var found = change["spans_" + doc.id];
  7285. if (!found) return null;
  7286. for (var i = 0, nw = []; i < change.text.length; ++i)
  7287. nw.push(removeClearedSpans(found[i]));
  7288. return nw;
  7289. }
  7290. // Used both to provide a JSON-safe object in .getHistory, and, when
  7291. // detaching a document, to split the history in two
  7292. function copyHistoryArray(events, newGroup, instantiateSel) {
  7293. for (var i = 0, copy = []; i < events.length; ++i) {
  7294. var event = events[i];
  7295. if (event.ranges) {
  7296. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7297. continue;
  7298. }
  7299. var changes = event.changes, newChanges = [];
  7300. copy.push({changes: newChanges});
  7301. for (var j = 0; j < changes.length; ++j) {
  7302. var change = changes[j], m;
  7303. newChanges.push({from: change.from, to: change.to, text: change.text});
  7304. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7305. if (indexOf(newGroup, Number(m[1])) > -1) {
  7306. lst(newChanges)[prop] = change[prop];
  7307. delete change[prop];
  7308. }
  7309. }
  7310. }
  7311. }
  7312. return copy;
  7313. }
  7314. // Rebasing/resetting history to deal with externally-sourced changes
  7315. function rebaseHistSelSingle(pos, from, to, diff) {
  7316. if (to < pos.line) {
  7317. pos.line += diff;
  7318. } else if (from < pos.line) {
  7319. pos.line = from;
  7320. pos.ch = 0;
  7321. }
  7322. }
  7323. // Tries to rebase an array of history events given a change in the
  7324. // document. If the change touches the same lines as the event, the
  7325. // event, and everything 'behind' it, is discarded. If the change is
  7326. // before the event, the event's positions are updated. Uses a
  7327. // copy-on-write scheme for the positions, to avoid having to
  7328. // reallocate them all on every rebase, but also avoid problems with
  7329. // shared position objects being unsafely updated.
  7330. function rebaseHistArray(array, from, to, diff) {
  7331. for (var i = 0; i < array.length; ++i) {
  7332. var sub = array[i], ok = true;
  7333. if (sub.ranges) {
  7334. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7335. for (var j = 0; j < sub.ranges.length; j++) {
  7336. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7337. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7338. }
  7339. continue;
  7340. }
  7341. for (var j = 0; j < sub.changes.length; ++j) {
  7342. var cur = sub.changes[j];
  7343. if (to < cur.from.line) {
  7344. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7345. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7346. } else if (from <= cur.to.line) {
  7347. ok = false;
  7348. break;
  7349. }
  7350. }
  7351. if (!ok) {
  7352. array.splice(0, i + 1);
  7353. i = 0;
  7354. }
  7355. }
  7356. }
  7357. function rebaseHist(hist, change) {
  7358. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7359. rebaseHistArray(hist.done, from, to, diff);
  7360. rebaseHistArray(hist.undone, from, to, diff);
  7361. }
  7362. // EVENT UTILITIES
  7363. // Due to the fact that we still support jurassic IE versions, some
  7364. // compatibility wrappers are needed.
  7365. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  7366. if (e.preventDefault) e.preventDefault();
  7367. else e.returnValue = false;
  7368. };
  7369. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  7370. if (e.stopPropagation) e.stopPropagation();
  7371. else e.cancelBubble = true;
  7372. };
  7373. function e_defaultPrevented(e) {
  7374. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7375. }
  7376. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  7377. function e_target(e) {return e.target || e.srcElement;}
  7378. function e_button(e) {
  7379. var b = e.which;
  7380. if (b == null) {
  7381. if (e.button & 1) b = 1;
  7382. else if (e.button & 2) b = 3;
  7383. else if (e.button & 4) b = 2;
  7384. }
  7385. if (mac && e.ctrlKey && b == 1) b = 3;
  7386. return b;
  7387. }
  7388. // EVENT HANDLING
  7389. // Lightweight event framework. on/off also work on DOM nodes,
  7390. // registering native DOM handlers.
  7391. var on = CodeMirror.on = function(emitter, type, f) {
  7392. if (emitter.addEventListener)
  7393. emitter.addEventListener(type, f, false);
  7394. else if (emitter.attachEvent)
  7395. emitter.attachEvent("on" + type, f);
  7396. else {
  7397. var map = emitter._handlers || (emitter._handlers = {});
  7398. var arr = map[type] || (map[type] = []);
  7399. arr.push(f);
  7400. }
  7401. };
  7402. var noHandlers = []
  7403. function getHandlers(emitter, type, copy) {
  7404. var arr = emitter._handlers && emitter._handlers[type]
  7405. if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
  7406. else return arr || noHandlers
  7407. }
  7408. var off = CodeMirror.off = function(emitter, type, f) {
  7409. if (emitter.removeEventListener)
  7410. emitter.removeEventListener(type, f, false);
  7411. else if (emitter.detachEvent)
  7412. emitter.detachEvent("on" + type, f);
  7413. else {
  7414. var handlers = getHandlers(emitter, type, false)
  7415. for (var i = 0; i < handlers.length; ++i)
  7416. if (handlers[i] == f) { handlers.splice(i, 1); break; }
  7417. }
  7418. };
  7419. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  7420. var handlers = getHandlers(emitter, type, true)
  7421. if (!handlers.length) return;
  7422. var args = Array.prototype.slice.call(arguments, 2);
  7423. for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
  7424. };
  7425. var orphanDelayedCallbacks = null;
  7426. // Often, we want to signal events at a point where we are in the
  7427. // middle of some work, but don't want the handler to start calling
  7428. // other methods on the editor, which might be in an inconsistent
  7429. // state or simply not expect any other events to happen.
  7430. // signalLater looks whether there are any handlers, and schedules
  7431. // them to be executed when the last operation ends, or, if no
  7432. // operation is active, when a timeout fires.
  7433. function signalLater(emitter, type /*, values...*/) {
  7434. var arr = getHandlers(emitter, type, false)
  7435. if (!arr.length) return;
  7436. var args = Array.prototype.slice.call(arguments, 2), list;
  7437. if (operationGroup) {
  7438. list = operationGroup.delayedCallbacks;
  7439. } else if (orphanDelayedCallbacks) {
  7440. list = orphanDelayedCallbacks;
  7441. } else {
  7442. list = orphanDelayedCallbacks = [];
  7443. setTimeout(fireOrphanDelayed, 0);
  7444. }
  7445. function bnd(f) {return function(){f.apply(null, args);};};
  7446. for (var i = 0; i < arr.length; ++i)
  7447. list.push(bnd(arr[i]));
  7448. }
  7449. function fireOrphanDelayed() {
  7450. var delayed = orphanDelayedCallbacks;
  7451. orphanDelayedCallbacks = null;
  7452. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7453. }
  7454. // The DOM events that CodeMirror handles can be overridden by
  7455. // registering a (non-DOM) handler on the editor for the event name,
  7456. // and preventDefault-ing the event in that handler.
  7457. function signalDOMEvent(cm, e, override) {
  7458. if (typeof e == "string")
  7459. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  7460. signal(cm, override || e.type, cm, e);
  7461. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7462. }
  7463. function signalCursorActivity(cm) {
  7464. var arr = cm._handlers && cm._handlers.cursorActivity;
  7465. if (!arr) return;
  7466. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7467. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7468. set.push(arr[i]);
  7469. }
  7470. function hasHandler(emitter, type) {
  7471. return getHandlers(emitter, type).length > 0
  7472. }
  7473. // Add on and off methods to a constructor's prototype, to make
  7474. // registering events on such objects more convenient.
  7475. function eventMixin(ctor) {
  7476. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7477. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7478. }
  7479. // MISC UTILITIES
  7480. // Number of pixels added to scroller and sizer to hide scrollbar
  7481. var scrollerGap = 30;
  7482. // Returned or thrown by various protocols to signal 'I'm not
  7483. // handling this'.
  7484. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  7485. // Reused option objects for setSelection & friends
  7486. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  7487. function Delayed() {this.id = null;}
  7488. Delayed.prototype.set = function(ms, f) {
  7489. clearTimeout(this.id);
  7490. this.id = setTimeout(f, ms);
  7491. };
  7492. // Counts the column offset in a string, taking tabs into account.
  7493. // Used mostly to find indentation.
  7494. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  7495. if (end == null) {
  7496. end = string.search(/[^\s\u00a0]/);
  7497. if (end == -1) end = string.length;
  7498. }
  7499. for (var i = startIndex || 0, n = startValue || 0;;) {
  7500. var nextTab = string.indexOf("\t", i);
  7501. if (nextTab < 0 || nextTab >= end)
  7502. return n + (end - i);
  7503. n += nextTab - i;
  7504. n += tabSize - (n % tabSize);
  7505. i = nextTab + 1;
  7506. }
  7507. };
  7508. // The inverse of countColumn -- find the offset that corresponds to
  7509. // a particular column.
  7510. var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
  7511. for (var pos = 0, col = 0;;) {
  7512. var nextTab = string.indexOf("\t", pos);
  7513. if (nextTab == -1) nextTab = string.length;
  7514. var skipped = nextTab - pos;
  7515. if (nextTab == string.length || col + skipped >= goal)
  7516. return pos + Math.min(skipped, goal - col);
  7517. col += nextTab - pos;
  7518. col += tabSize - (col % tabSize);
  7519. pos = nextTab + 1;
  7520. if (col >= goal) return pos;
  7521. }
  7522. }
  7523. var spaceStrs = [""];
  7524. function spaceStr(n) {
  7525. while (spaceStrs.length <= n)
  7526. spaceStrs.push(lst(spaceStrs) + " ");
  7527. return spaceStrs[n];
  7528. }
  7529. function lst(arr) { return arr[arr.length-1]; }
  7530. var selectInput = function(node) { node.select(); };
  7531. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7532. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7533. else if (ie) // Suppress mysterious IE10 errors
  7534. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  7535. function indexOf(array, elt) {
  7536. for (var i = 0; i < array.length; ++i)
  7537. if (array[i] == elt) return i;
  7538. return -1;
  7539. }
  7540. function map(array, f) {
  7541. var out = [];
  7542. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7543. return out;
  7544. }
  7545. function nothing() {}
  7546. function createObj(base, props) {
  7547. var inst;
  7548. if (Object.create) {
  7549. inst = Object.create(base);
  7550. } else {
  7551. nothing.prototype = base;
  7552. inst = new nothing();
  7553. }
  7554. if (props) copyObj(props, inst);
  7555. return inst;
  7556. };
  7557. function copyObj(obj, target, overwrite) {
  7558. if (!target) target = {};
  7559. for (var prop in obj)
  7560. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7561. target[prop] = obj[prop];
  7562. return target;
  7563. }
  7564. function bind(f) {
  7565. var args = Array.prototype.slice.call(arguments, 1);
  7566. return function(){return f.apply(null, args);};
  7567. }
  7568. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7569. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  7570. return /\w/.test(ch) || ch > "\x80" &&
  7571. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7572. };
  7573. function isWordChar(ch, helper) {
  7574. if (!helper) return isWordCharBasic(ch);
  7575. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7576. return helper.test(ch);
  7577. }
  7578. function isEmpty(obj) {
  7579. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7580. return true;
  7581. }
  7582. // Extending unicode characters. A series of a non-extending char +
  7583. // any number of extending chars is treated as a single unit as far
  7584. // as editing and measuring is concerned. This is not fully correct,
  7585. // since some scripts/fonts/browsers also treat other configurations
  7586. // of code points as a group.
  7587. 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]/;
  7588. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7589. // DOM UTILITIES
  7590. function elt(tag, content, className, style) {
  7591. var e = document.createElement(tag);
  7592. if (className) e.className = className;
  7593. if (style) e.style.cssText = style;
  7594. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7595. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7596. return e;
  7597. }
  7598. var range;
  7599. if (document.createRange) range = function(node, start, end, endNode) {
  7600. var r = document.createRange();
  7601. r.setEnd(endNode || node, end);
  7602. r.setStart(node, start);
  7603. return r;
  7604. };
  7605. else range = function(node, start, end) {
  7606. var r = document.body.createTextRange();
  7607. try { r.moveToElementText(node.parentNode); }
  7608. catch(e) { return r; }
  7609. r.collapse(true);
  7610. r.moveEnd("character", end);
  7611. r.moveStart("character", start);
  7612. return r;
  7613. };
  7614. function removeChildren(e) {
  7615. for (var count = e.childNodes.length; count > 0; --count)
  7616. e.removeChild(e.firstChild);
  7617. return e;
  7618. }
  7619. function removeChildrenAndAdd(parent, e) {
  7620. return removeChildren(parent).appendChild(e);
  7621. }
  7622. var contains = CodeMirror.contains = function(parent, child) {
  7623. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7624. child = child.parentNode;
  7625. if (parent.contains)
  7626. return parent.contains(child);
  7627. do {
  7628. if (child.nodeType == 11) child = child.host;
  7629. if (child == parent) return true;
  7630. } while (child = child.parentNode);
  7631. };
  7632. function activeElt() {
  7633. var activeElement = document.activeElement;
  7634. while (activeElement && activeElement.root && activeElement.root.activeElement)
  7635. activeElement = activeElement.root.activeElement;
  7636. return activeElement;
  7637. }
  7638. // Older versions of IE throws unspecified error when touching
  7639. // document.activeElement in some cases (during loading, in iframe)
  7640. if (ie && ie_version < 11) activeElt = function() {
  7641. try { return document.activeElement; }
  7642. catch(e) { return document.body; }
  7643. };
  7644. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7645. var rmClass = CodeMirror.rmClass = function(node, cls) {
  7646. var current = node.className;
  7647. var match = classTest(cls).exec(current);
  7648. if (match) {
  7649. var after = current.slice(match.index + match[0].length);
  7650. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7651. }
  7652. };
  7653. var addClass = CodeMirror.addClass = function(node, cls) {
  7654. var current = node.className;
  7655. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7656. };
  7657. function joinClasses(a, b) {
  7658. var as = a.split(" ");
  7659. for (var i = 0; i < as.length; i++)
  7660. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7661. return b;
  7662. }
  7663. // WINDOW-WIDE EVENTS
  7664. // These must be handled carefully, because naively registering a
  7665. // handler for each editor will cause the editors to never be
  7666. // garbage collected.
  7667. function forEachCodeMirror(f) {
  7668. if (!document.body.getElementsByClassName) return;
  7669. var byClass = document.body.getElementsByClassName("CodeMirror");
  7670. for (var i = 0; i < byClass.length; i++) {
  7671. var cm = byClass[i].CodeMirror;
  7672. if (cm) f(cm);
  7673. }
  7674. }
  7675. var globalsRegistered = false;
  7676. function ensureGlobalHandlers() {
  7677. if (globalsRegistered) return;
  7678. registerGlobalHandlers();
  7679. globalsRegistered = true;
  7680. }
  7681. function registerGlobalHandlers() {
  7682. // When the window resizes, we need to refresh active editors.
  7683. var resizeTimer;
  7684. on(window, "resize", function() {
  7685. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  7686. resizeTimer = null;
  7687. forEachCodeMirror(onResize);
  7688. }, 100);
  7689. });
  7690. // When the window loses focus, we want to show the editor as blurred
  7691. on(window, "blur", function() {
  7692. forEachCodeMirror(onBlur);
  7693. });
  7694. }
  7695. // FEATURE DETECTION
  7696. // Detect drag-and-drop
  7697. var dragAndDrop = function() {
  7698. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7699. // couldn't get it to work yet.
  7700. if (ie && ie_version < 9) return false;
  7701. var div = elt('div');
  7702. return "draggable" in div || "dragDrop" in div;
  7703. }();
  7704. var zwspSupported;
  7705. function zeroWidthElement(measure) {
  7706. if (zwspSupported == null) {
  7707. var test = elt("span", "\u200b");
  7708. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7709. if (measure.firstChild.offsetHeight != 0)
  7710. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7711. }
  7712. var node = zwspSupported ? elt("span", "\u200b") :
  7713. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7714. node.setAttribute("cm-text", "");
  7715. return node;
  7716. }
  7717. // Feature-detect IE's crummy client rect reporting for bidi text
  7718. var badBidiRects;
  7719. function hasBadBidiRects(measure) {
  7720. if (badBidiRects != null) return badBidiRects;
  7721. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7722. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7723. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7724. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7725. return badBidiRects = (r1.right - r0.right < 3);
  7726. }
  7727. // See if "".split is the broken IE version, if so, provide an
  7728. // alternative way to split lines.
  7729. var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7730. var pos = 0, result = [], l = string.length;
  7731. while (pos <= l) {
  7732. var nl = string.indexOf("\n", pos);
  7733. if (nl == -1) nl = string.length;
  7734. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7735. var rt = line.indexOf("\r");
  7736. if (rt != -1) {
  7737. result.push(line.slice(0, rt));
  7738. pos += rt + 1;
  7739. } else {
  7740. result.push(line);
  7741. pos = nl + 1;
  7742. }
  7743. }
  7744. return result;
  7745. } : function(string){return string.split(/\r\n?|\n/);};
  7746. var hasSelection = window.getSelection ? function(te) {
  7747. try { return te.selectionStart != te.selectionEnd; }
  7748. catch(e) { return false; }
  7749. } : function(te) {
  7750. try {var range = te.ownerDocument.selection.createRange();}
  7751. catch(e) {}
  7752. if (!range || range.parentElement() != te) return false;
  7753. return range.compareEndPoints("StartToEnd", range) != 0;
  7754. };
  7755. var hasCopyEvent = (function() {
  7756. var e = elt("div");
  7757. if ("oncopy" in e) return true;
  7758. e.setAttribute("oncopy", "return;");
  7759. return typeof e.oncopy == "function";
  7760. })();
  7761. var badZoomedRects = null;
  7762. function hasBadZoomedRects(measure) {
  7763. if (badZoomedRects != null) return badZoomedRects;
  7764. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7765. var normal = node.getBoundingClientRect();
  7766. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7767. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7768. }
  7769. // KEY NAMES
  7770. var keyNames = CodeMirror.keyNames = {
  7771. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7772. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7773. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7774. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  7775. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  7776. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7777. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7778. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7779. };
  7780. (function() {
  7781. // Number keys
  7782. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7783. // Alphabetic keys
  7784. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7785. // Function keys
  7786. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7787. })();
  7788. // BIDI HELPERS
  7789. function iterateBidiSections(order, from, to, f) {
  7790. if (!order) return f(from, to, "ltr");
  7791. var found = false;
  7792. for (var i = 0; i < order.length; ++i) {
  7793. var part = order[i];
  7794. if (part.from < to && part.to > from || from == to && part.to == from) {
  7795. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7796. found = true;
  7797. }
  7798. }
  7799. if (!found) f(from, to, "ltr");
  7800. }
  7801. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7802. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7803. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7804. function lineRight(line) {
  7805. var order = getOrder(line);
  7806. if (!order) return line.text.length;
  7807. return bidiRight(lst(order));
  7808. }
  7809. function lineStart(cm, lineN) {
  7810. var line = getLine(cm.doc, lineN);
  7811. var visual = visualLine(line);
  7812. if (visual != line) lineN = lineNo(visual);
  7813. var order = getOrder(visual);
  7814. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7815. return Pos(lineN, ch);
  7816. }
  7817. function lineEnd(cm, lineN) {
  7818. var merged, line = getLine(cm.doc, lineN);
  7819. while (merged = collapsedSpanAtEnd(line)) {
  7820. line = merged.find(1, true).line;
  7821. lineN = null;
  7822. }
  7823. var order = getOrder(line);
  7824. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7825. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7826. }
  7827. function lineStartSmart(cm, pos) {
  7828. var start = lineStart(cm, pos.line);
  7829. var line = getLine(cm.doc, start.line);
  7830. var order = getOrder(line);
  7831. if (!order || order[0].level == 0) {
  7832. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7833. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7834. return Pos(start.line, inWS ? 0 : firstNonWS);
  7835. }
  7836. return start;
  7837. }
  7838. function compareBidiLevel(order, a, b) {
  7839. var linedir = order[0].level;
  7840. if (a == linedir) return true;
  7841. if (b == linedir) return false;
  7842. return a < b;
  7843. }
  7844. var bidiOther;
  7845. function getBidiPartAt(order, pos) {
  7846. bidiOther = null;
  7847. for (var i = 0, found; i < order.length; ++i) {
  7848. var cur = order[i];
  7849. if (cur.from < pos && cur.to > pos) return i;
  7850. if ((cur.from == pos || cur.to == pos)) {
  7851. if (found == null) {
  7852. found = i;
  7853. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7854. if (cur.from != cur.to) bidiOther = found;
  7855. return i;
  7856. } else {
  7857. if (cur.from != cur.to) bidiOther = i;
  7858. return found;
  7859. }
  7860. }
  7861. }
  7862. return found;
  7863. }
  7864. function moveInLine(line, pos, dir, byUnit) {
  7865. if (!byUnit) return pos + dir;
  7866. do pos += dir;
  7867. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7868. return pos;
  7869. }
  7870. // This is needed in order to move 'visually' through bi-directional
  7871. // text -- i.e., pressing left should make the cursor go left, even
  7872. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7873. // LTR text touch each other. This often requires the cursor offset
  7874. // to move more than one unit, in order to visually move one unit.
  7875. function moveVisually(line, start, dir, byUnit) {
  7876. var bidi = getOrder(line);
  7877. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7878. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7879. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7880. for (;;) {
  7881. if (target > part.from && target < part.to) return target;
  7882. if (target == part.from || target == part.to) {
  7883. if (getBidiPartAt(bidi, target) == pos) return target;
  7884. part = bidi[pos += dir];
  7885. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7886. } else {
  7887. part = bidi[pos += dir];
  7888. if (!part) return null;
  7889. if ((dir > 0) == part.level % 2)
  7890. target = moveInLine(line, part.to, -1, byUnit);
  7891. else
  7892. target = moveInLine(line, part.from, 1, byUnit);
  7893. }
  7894. }
  7895. }
  7896. function moveLogically(line, start, dir, byUnit) {
  7897. var target = start + dir;
  7898. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7899. return target < 0 || target > line.text.length ? null : target;
  7900. }
  7901. // Bidirectional ordering algorithm
  7902. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7903. // that this (partially) implements.
  7904. // One-char codes used for character types:
  7905. // L (L): Left-to-Right
  7906. // R (R): Right-to-Left
  7907. // r (AL): Right-to-Left Arabic
  7908. // 1 (EN): European Number
  7909. // + (ES): European Number Separator
  7910. // % (ET): European Number Terminator
  7911. // n (AN): Arabic Number
  7912. // , (CS): Common Number Separator
  7913. // m (NSM): Non-Spacing Mark
  7914. // b (BN): Boundary Neutral
  7915. // s (B): Paragraph Separator
  7916. // t (S): Segment Separator
  7917. // w (WS): Whitespace
  7918. // N (ON): Other Neutrals
  7919. // Returns null if characters are ordered as they appear
  7920. // (left-to-right), or an array of sections ({from, to, level}
  7921. // objects) in the order in which they occur visually.
  7922. var bidiOrdering = (function() {
  7923. // Character types for codepoints 0 to 0xff
  7924. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7925. // Character types for codepoints 0x600 to 0x6ff
  7926. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7927. function charType(code) {
  7928. if (code <= 0xf7) return lowTypes.charAt(code);
  7929. else if (0x590 <= code && code <= 0x5f4) return "R";
  7930. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7931. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7932. else if (0x2000 <= code && code <= 0x200b) return "w";
  7933. else if (code == 0x200c) return "b";
  7934. else return "L";
  7935. }
  7936. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7937. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7938. // Browsers seem to always treat the boundaries of block elements as being L.
  7939. var outerType = "L";
  7940. function BidiSpan(level, from, to) {
  7941. this.level = level;
  7942. this.from = from; this.to = to;
  7943. }
  7944. return function(str) {
  7945. if (!bidiRE.test(str)) return false;
  7946. var len = str.length, types = [];
  7947. for (var i = 0, type; i < len; ++i)
  7948. types.push(type = charType(str.charCodeAt(i)));
  7949. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7950. // change the type of the NSM to the type of the previous
  7951. // character. If the NSM is at the start of the level run, it will
  7952. // get the type of sor.
  7953. for (var i = 0, prev = outerType; i < len; ++i) {
  7954. var type = types[i];
  7955. if (type == "m") types[i] = prev;
  7956. else prev = type;
  7957. }
  7958. // W2. Search backwards from each instance of a European number
  7959. // until the first strong type (R, L, AL, or sor) is found. If an
  7960. // AL is found, change the type of the European number to Arabic
  7961. // number.
  7962. // W3. Change all ALs to R.
  7963. for (var i = 0, cur = outerType; i < len; ++i) {
  7964. var type = types[i];
  7965. if (type == "1" && cur == "r") types[i] = "n";
  7966. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7967. }
  7968. // W4. A single European separator between two European numbers
  7969. // changes to a European number. A single common separator between
  7970. // two numbers of the same type changes to that type.
  7971. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7972. var type = types[i];
  7973. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  7974. else if (type == "," && prev == types[i+1] &&
  7975. (prev == "1" || prev == "n")) types[i] = prev;
  7976. prev = type;
  7977. }
  7978. // W5. A sequence of European terminators adjacent to European
  7979. // numbers changes to all European numbers.
  7980. // W6. Otherwise, separators and terminators change to Other
  7981. // Neutral.
  7982. for (var i = 0; i < len; ++i) {
  7983. var type = types[i];
  7984. if (type == ",") types[i] = "N";
  7985. else if (type == "%") {
  7986. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  7987. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7988. for (var j = i; j < end; ++j) types[j] = replace;
  7989. i = end - 1;
  7990. }
  7991. }
  7992. // W7. Search backwards from each instance of a European number
  7993. // until the first strong type (R, L, or sor) is found. If an L is
  7994. // found, then change the type of the European number to L.
  7995. for (var i = 0, cur = outerType; i < len; ++i) {
  7996. var type = types[i];
  7997. if (cur == "L" && type == "1") types[i] = "L";
  7998. else if (isStrong.test(type)) cur = type;
  7999. }
  8000. // N1. A sequence of neutrals takes the direction of the
  8001. // surrounding strong text if the text on both sides has the same
  8002. // direction. European and Arabic numbers act as if they were R in
  8003. // terms of their influence on neutrals. Start-of-level-run (sor)
  8004. // and end-of-level-run (eor) are used at level run boundaries.
  8005. // N2. Any remaining neutrals take the embedding direction.
  8006. for (var i = 0; i < len; ++i) {
  8007. if (isNeutral.test(types[i])) {
  8008. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  8009. var before = (i ? types[i-1] : outerType) == "L";
  8010. var after = (end < len ? types[end] : outerType) == "L";
  8011. var replace = before || after ? "L" : "R";
  8012. for (var j = i; j < end; ++j) types[j] = replace;
  8013. i = end - 1;
  8014. }
  8015. }
  8016. // Here we depart from the documented algorithm, in order to avoid
  8017. // building up an actual levels array. Since there are only three
  8018. // levels (0, 1, 2) in an implementation that doesn't take
  8019. // explicit embedding into account, we can build up the order on
  8020. // the fly, without following the level-based algorithm.
  8021. var order = [], m;
  8022. for (var i = 0; i < len;) {
  8023. if (countsAsLeft.test(types[i])) {
  8024. var start = i;
  8025. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  8026. order.push(new BidiSpan(0, start, i));
  8027. } else {
  8028. var pos = i, at = order.length;
  8029. for (++i; i < len && types[i] != "L"; ++i) {}
  8030. for (var j = pos; j < i;) {
  8031. if (countsAsNum.test(types[j])) {
  8032. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  8033. var nstart = j;
  8034. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  8035. order.splice(at, 0, new BidiSpan(2, nstart, j));
  8036. pos = j;
  8037. } else ++j;
  8038. }
  8039. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  8040. }
  8041. }
  8042. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  8043. order[0].from = m[0].length;
  8044. order.unshift(new BidiSpan(0, 0, m[0].length));
  8045. }
  8046. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  8047. lst(order).to -= m[0].length;
  8048. order.push(new BidiSpan(0, len - m[0].length, len));
  8049. }
  8050. if (order[0].level == 2)
  8051. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  8052. if (order[0].level != lst(order).level)
  8053. order.push(new BidiSpan(order[0].level, len, len));
  8054. return order;
  8055. };
  8056. })();
  8057. // THE END
  8058. CodeMirror.version = "5.14.2";
  8059. return CodeMirror;
  8060. });