0c8efce3abfb24c39dd7cf7399b1c4fdbc98e0a8.svn-base 339 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function(mod) {
  9. // if (typeof exports == "object" && typeof module == "object") // CommonJS
  10. // module.exports = mod();
  11. // else if (typeof define == "function" && define.amd) // AMD
  12. // return define([], mod);
  13. // else // Plain browser env
  14. this.CodeMirror = mod();
  15. })(function() {
  16. "use strict";
  17. // BROWSER SNIFFING
  18. // Kludges for bugs and behavior differences that can't be feature
  19. // detected are enabled based on userAgent etc sniffing.
  20. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  21. var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
  22. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
  23. var ie = ie_upto10 || ie_11up;
  24. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  25. var webkit = /WebKit\//.test(navigator.userAgent);
  26. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  27. var chrome = /Chrome\//.test(navigator.userAgent);
  28. var presto = /Opera\//.test(navigator.userAgent);
  29. var safari = /Apple Computer/.test(navigator.vendor);
  30. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  31. var phantom = /PhantomJS/.test(navigator.userAgent);
  32. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  33. // This is woefully incomplete. Suggestions for alternative methods welcome.
  34. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
  35. var mac = ios || /Mac/.test(navigator.platform);
  36. var windows = /win/i.test(navigator.platform);
  37. var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
  38. if (presto_version) presto_version = Number(presto_version[1]);
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  42. var captureRightClick = gecko || (ie && ie_version >= 9);
  43. // Optimize some code when these features are not used.
  44. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  45. // EDITOR CONSTRUCTOR
  46. // A CodeMirror instance represents an editor. This is the object
  47. // that user code is usually dealing with.
  48. function CodeMirror(place, options) {
  49. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  50. this.options = options = options ? copyObj(options) : {};
  51. // Determine effective options based on given values and defaults.
  52. copyObj(defaults, options, false);
  53. setGuttersForLineNumbers(options);
  54. var doc = options.value;
  55. if (typeof doc == "string") doc = new Doc(doc, options.mode);
  56. this.doc = doc;
  57. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  58. var display = this.display = new Display(place, doc, input);
  59. display.wrapper.CodeMirror = this;
  60. updateGutters(this);
  61. themeChanged(this);
  62. if (options.lineWrapping)
  63. this.display.wrapper.className += " CodeMirror-wrap";
  64. if (options.autofocus && !mobile) display.input.focus();
  65. initScrollbars(this);
  66. this.state = {
  67. keyMaps: [], // stores maps added by addKeyMap
  68. overlays: [], // highlighting overlays, as added by addOverlay
  69. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  70. overwrite: false,
  71. delayingBlurEvent: false,
  72. focused: false,
  73. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  74. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  75. draggingText: false,
  76. highlight: new Delayed(), // stores highlight worker timeout
  77. keySeq: null, // Unfinished key sequence
  78. specialChars: null
  79. };
  80. var cm = this;
  81. // Override magic textarea content restore that IE sometimes does
  82. // on our hidden textarea on reload
  83. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  84. registerEventHandlers(this);
  85. ensureGlobalHandlers();
  86. startOperation(this);
  87. this.curOp.forceUpdate = true;
  88. attachDoc(this, doc);
  89. if ((options.autofocus && !mobile) || cm.hasFocus())
  90. setTimeout(bind(onFocus, this), 20);
  91. else
  92. onBlur(this);
  93. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  94. optionHandlers[opt](this, options[opt], Init);
  95. maybeUpdateLineNumberWidth(this);
  96. if (options.finishInit) options.finishInit(this);
  97. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  98. endOperation(this);
  99. // Suppress optimizelegibility in Webkit, since it breaks text
  100. // measuring on line wrapping boundaries.
  101. if (webkit && options.lineWrapping &&
  102. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  103. display.lineDiv.style.textRendering = "auto";
  104. }
  105. // DISPLAY CONSTRUCTOR
  106. // The display handles the DOM integration, both for input reading
  107. // and content drawing. It holds references to DOM nodes and
  108. // display-related state.
  109. function Display(place, doc, input) {
  110. var d = this;
  111. this.input = input;
  112. // Covers bottom-right square when both scrollbars are present.
  113. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  114. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  115. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  116. // and h scrollbar is present.
  117. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  118. d.gutterFiller.setAttribute("cm-not-content", "true");
  119. // Will contain the actual code, positioned to cover the viewport.
  120. d.lineDiv = elt("div", null, "CodeMirror-code");
  121. // Elements are added to these to represent selection and cursors.
  122. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  123. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  124. // A visibility: hidden element used to find the size of things.
  125. d.measure = elt("div", null, "CodeMirror-measure");
  126. // When lines outside of the viewport are measured, they are drawn in this.
  127. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  128. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  129. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  130. null, "position: relative; outline: none");
  131. // Moved around its parent to cover visible view.
  132. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  133. // Set to the height of the document, allowing scrolling.
  134. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  135. d.sizerWidth = null;
  136. // Behavior of elts with overflow: auto and padding is
  137. // inconsistent across browsers. This is used to ensure the
  138. // scrollable area is big enough.
  139. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  140. // Will contain the gutters, if any.
  141. d.gutters = elt("div", null, "CodeMirror-gutters");
  142. d.lineGutter = null;
  143. // Actual scrollable element.
  144. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  145. d.scroller.setAttribute("tabIndex", "-1");
  146. // The element in which the editor lives.
  147. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  148. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  149. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  150. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  151. if (place) {
  152. if (place.appendChild) place.appendChild(d.wrapper);
  153. else place(d.wrapper);
  154. }
  155. // Current rendered range (may be bigger than the view window).
  156. d.viewFrom = d.viewTo = doc.first;
  157. d.reportedViewFrom = d.reportedViewTo = doc.first;
  158. // Information about the rendered lines.
  159. d.view = [];
  160. d.renderedView = null;
  161. // Holds info about a single rendered line when it was rendered
  162. // for measurement, while not in view.
  163. d.externalMeasured = null;
  164. // Empty space (in pixels) above the view
  165. d.viewOffset = 0;
  166. d.lastWrapHeight = d.lastWrapWidth = 0;
  167. d.updateLineNumbers = null;
  168. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  169. d.scrollbarsClipped = false;
  170. // Used to only resize the line number gutter when necessary (when
  171. // the amount of lines crosses a boundary that makes its width change)
  172. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  173. // Set to true when a non-horizontal-scrolling line widget is
  174. // added. As an optimization, line widget aligning is skipped when
  175. // this is false.
  176. d.alignWidgets = false;
  177. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  178. // Tracks the maximum line length so that the horizontal scrollbar
  179. // can be kept static when scrolling.
  180. d.maxLine = null;
  181. d.maxLineLength = 0;
  182. d.maxLineChanged = false;
  183. // Used for measuring wheel scrolling granularity
  184. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  185. // True when shift is held down.
  186. d.shift = false;
  187. // Used to track whether anything happened since the context menu
  188. // was opened.
  189. d.selForContextMenu = null;
  190. d.activeTouch = null;
  191. input.init(d);
  192. }
  193. // STATE UPDATES
  194. // Used to get the editor into a consistent state again when options change.
  195. function loadMode(cm) {
  196. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  197. resetModeState(cm);
  198. }
  199. function resetModeState(cm) {
  200. cm.doc.iter(function(line) {
  201. if (line.stateAfter) line.stateAfter = null;
  202. if (line.styles) line.styles = null;
  203. });
  204. cm.doc.frontier = cm.doc.first;
  205. startWorker(cm, 100);
  206. cm.state.modeGen++;
  207. if (cm.curOp) regChange(cm);
  208. }
  209. function wrappingChanged(cm) {
  210. if (cm.options.lineWrapping) {
  211. addClass(cm.display.wrapper, "CodeMirror-wrap");
  212. cm.display.sizer.style.minWidth = "";
  213. cm.display.sizerWidth = null;
  214. } else {
  215. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  216. findMaxLine(cm);
  217. }
  218. estimateLineHeights(cm);
  219. regChange(cm);
  220. clearCaches(cm);
  221. setTimeout(function(){updateScrollbars(cm);}, 100);
  222. }
  223. // Returns a function that estimates the height of a line, to use as
  224. // first approximation until the line becomes visible (and is thus
  225. // properly measurable).
  226. function estimateHeight(cm) {
  227. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  228. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  229. return function(line) {
  230. if (lineIsHidden(cm.doc, line)) return 0;
  231. var widgetsHeight = 0;
  232. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  233. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  234. }
  235. if (wrapping)
  236. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  237. else
  238. return widgetsHeight + th;
  239. };
  240. }
  241. function estimateLineHeights(cm) {
  242. var doc = cm.doc, est = estimateHeight(cm);
  243. doc.iter(function(line) {
  244. var estHeight = est(line);
  245. if (estHeight != line.height) updateLineHeight(line, estHeight);
  246. });
  247. }
  248. function themeChanged(cm) {
  249. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  250. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  251. clearCaches(cm);
  252. }
  253. function guttersChanged(cm) {
  254. updateGutters(cm);
  255. regChange(cm);
  256. setTimeout(function(){alignHorizontally(cm);}, 20);
  257. }
  258. // Rebuild the gutter elements, ensure the margin to the left of the
  259. // code matches their width.
  260. function updateGutters(cm) {
  261. var gutters = cm.display.gutters, specs = cm.options.gutters;
  262. removeChildren(gutters);
  263. for (var i = 0; i < specs.length; ++i) {
  264. var gutterClass = specs[i];
  265. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  266. if (gutterClass == "CodeMirror-linenumbers") {
  267. cm.display.lineGutter = gElt;
  268. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  269. }
  270. }
  271. gutters.style.display = i ? "" : "none";
  272. updateGutterSpace(cm);
  273. }
  274. function updateGutterSpace(cm) {
  275. var width = cm.display.gutters.offsetWidth;
  276. cm.display.sizer.style.marginLeft = width + "px";
  277. }
  278. // Compute the character length of a line, taking into account
  279. // collapsed ranges (see markText) that might hide parts, and join
  280. // other lines onto it.
  281. function lineLength(line) {
  282. if (line.height == 0) return 0;
  283. var len = line.text.length, merged, cur = line;
  284. while (merged = collapsedSpanAtStart(cur)) {
  285. var found = merged.find(0, true);
  286. cur = found.from.line;
  287. len += found.from.ch - found.to.ch;
  288. }
  289. cur = line;
  290. while (merged = collapsedSpanAtEnd(cur)) {
  291. var found = merged.find(0, true);
  292. len -= cur.text.length - found.from.ch;
  293. cur = found.to.line;
  294. len += cur.text.length - found.to.ch;
  295. }
  296. return len;
  297. }
  298. // Find the longest line in the document.
  299. function findMaxLine(cm) {
  300. var d = cm.display, doc = cm.doc;
  301. d.maxLine = getLine(doc, doc.first);
  302. d.maxLineLength = lineLength(d.maxLine);
  303. d.maxLineChanged = true;
  304. doc.iter(function(line) {
  305. var len = lineLength(line);
  306. if (len > d.maxLineLength) {
  307. d.maxLineLength = len;
  308. d.maxLine = line;
  309. }
  310. });
  311. }
  312. // Make sure the gutters options contains the element
  313. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  314. function setGuttersForLineNumbers(options) {
  315. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  316. if (found == -1 && options.lineNumbers) {
  317. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  318. } else if (found > -1 && !options.lineNumbers) {
  319. options.gutters = options.gutters.slice(0);
  320. options.gutters.splice(found, 1);
  321. }
  322. }
  323. // SCROLLBARS
  324. // Prepare DOM reads needed to update the scrollbars. Done in one
  325. // shot to minimize update/measure roundtrips.
  326. function measureForScrollbars(cm) {
  327. var d = cm.display, gutterW = d.gutters.offsetWidth;
  328. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  329. return {
  330. clientHeight: d.scroller.clientHeight,
  331. viewHeight: d.wrapper.clientHeight,
  332. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  333. viewWidth: d.wrapper.clientWidth,
  334. barLeft: cm.options.fixedGutter ? gutterW : 0,
  335. docHeight: docH,
  336. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  337. nativeBarWidth: d.nativeBarWidth,
  338. gutterWidth: gutterW
  339. };
  340. }
  341. function NativeScrollbars(place, scroll, cm) {
  342. this.cm = cm;
  343. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  344. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  345. place(vert); place(horiz);
  346. on(vert, "scroll", function() {
  347. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  348. });
  349. on(horiz, "scroll", function() {
  350. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  351. });
  352. this.checkedOverlay = false;
  353. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  354. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  355. }
  356. NativeScrollbars.prototype = copyObj({
  357. update: function(measure) {
  358. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  359. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  360. var sWidth = measure.nativeBarWidth;
  361. if (needsV) {
  362. this.vert.style.display = "block";
  363. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  364. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  365. // A bug in IE8 can cause this value to be negative, so guard it.
  366. this.vert.firstChild.style.height =
  367. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  368. } else {
  369. this.vert.style.display = "";
  370. this.vert.firstChild.style.height = "0";
  371. }
  372. if (needsH) {
  373. this.horiz.style.display = "block";
  374. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  375. this.horiz.style.left = measure.barLeft + "px";
  376. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  377. this.horiz.firstChild.style.width =
  378. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  379. } else {
  380. this.horiz.style.display = "";
  381. this.horiz.firstChild.style.width = "0";
  382. }
  383. if (!this.checkedOverlay && measure.clientHeight > 0) {
  384. if (sWidth == 0) this.overlayHack();
  385. this.checkedOverlay = true;
  386. }
  387. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  388. },
  389. setScrollLeft: function(pos) {
  390. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  391. },
  392. setScrollTop: function(pos) {
  393. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  394. },
  395. overlayHack: function() {
  396. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  397. this.horiz.style.minHeight = this.vert.style.minWidth = w;
  398. var self = this;
  399. var barMouseDown = function(e) {
  400. if (e_target(e) != self.vert && e_target(e) != self.horiz)
  401. operation(self.cm, onMouseDown)(e);
  402. };
  403. on(this.vert, "mousedown", barMouseDown);
  404. on(this.horiz, "mousedown", barMouseDown);
  405. },
  406. clear: function() {
  407. var parent = this.horiz.parentNode;
  408. parent.removeChild(this.horiz);
  409. parent.removeChild(this.vert);
  410. }
  411. }, NativeScrollbars.prototype);
  412. function NullScrollbars() {}
  413. NullScrollbars.prototype = copyObj({
  414. update: function() { return {bottom: 0, right: 0}; },
  415. setScrollLeft: function() {},
  416. setScrollTop: function() {},
  417. clear: function() {}
  418. }, NullScrollbars.prototype);
  419. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  420. function initScrollbars(cm) {
  421. if (cm.display.scrollbars) {
  422. cm.display.scrollbars.clear();
  423. if (cm.display.scrollbars.addClass)
  424. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  425. }
  426. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  427. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  428. // Prevent clicks in the scrollbars from killing focus
  429. on(node, "mousedown", function() {
  430. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  431. });
  432. node.setAttribute("cm-not-content", "true");
  433. }, function(pos, axis) {
  434. if (axis == "horizontal") setScrollLeft(cm, pos);
  435. else setScrollTop(cm, pos);
  436. }, cm);
  437. if (cm.display.scrollbars.addClass)
  438. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  439. }
  440. function updateScrollbars(cm, measure) {
  441. if (!measure) measure = measureForScrollbars(cm);
  442. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  443. updateScrollbarsInner(cm, measure);
  444. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  445. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  446. updateHeightsInViewport(cm);
  447. updateScrollbarsInner(cm, measureForScrollbars(cm));
  448. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  449. }
  450. }
  451. // Re-synchronize the fake scrollbars with the actual size of the
  452. // content.
  453. function updateScrollbarsInner(cm, measure) {
  454. var d = cm.display;
  455. var sizes = d.scrollbars.update(measure);
  456. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  457. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  458. if (sizes.right && sizes.bottom) {
  459. d.scrollbarFiller.style.display = "block";
  460. d.scrollbarFiller.style.height = sizes.bottom + "px";
  461. d.scrollbarFiller.style.width = sizes.right + "px";
  462. } else d.scrollbarFiller.style.display = "";
  463. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  464. d.gutterFiller.style.display = "block";
  465. d.gutterFiller.style.height = sizes.bottom + "px";
  466. d.gutterFiller.style.width = measure.gutterWidth + "px";
  467. } else d.gutterFiller.style.display = "";
  468. }
  469. // Compute the lines that are visible in a given viewport (defaults
  470. // the the current scroll position). viewport may contain top,
  471. // height, and ensure (see op.scrollToPos) properties.
  472. function visibleLines(display, doc, viewport) {
  473. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  474. top = Math.floor(top - paddingTop(display));
  475. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  476. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  477. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  478. // forces those lines into the viewport (if possible).
  479. if (viewport && viewport.ensure) {
  480. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  481. if (ensureFrom < from) {
  482. from = ensureFrom;
  483. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  484. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  485. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  486. to = ensureTo;
  487. }
  488. }
  489. return {from: from, to: Math.max(to, from + 1)};
  490. }
  491. // LINE NUMBERS
  492. // Re-align line numbers and gutter marks to compensate for
  493. // horizontal scrolling.
  494. function alignHorizontally(cm) {
  495. var display = cm.display, view = display.view;
  496. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  497. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  498. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  499. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  500. if (cm.options.fixedGutter && view[i].gutter)
  501. view[i].gutter.style.left = left;
  502. var align = view[i].alignable;
  503. if (align) for (var j = 0; j < align.length; j++)
  504. align[j].style.left = left;
  505. }
  506. if (cm.options.fixedGutter)
  507. display.gutters.style.left = (comp + gutterW) + "px";
  508. }
  509. // Used to ensure that the line number gutter is still the right
  510. // size for the current document size. Returns true when an update
  511. // is needed.
  512. function maybeUpdateLineNumberWidth(cm) {
  513. if (!cm.options.lineNumbers) return false;
  514. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  515. if (last.length != display.lineNumChars) {
  516. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  517. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  518. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  519. display.lineGutter.style.width = "";
  520. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  521. display.lineNumWidth = display.lineNumInnerWidth + padding;
  522. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  523. display.lineGutter.style.width = display.lineNumWidth + "px";
  524. updateGutterSpace(cm);
  525. return true;
  526. }
  527. return false;
  528. }
  529. function lineNumberFor(options, i) {
  530. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  531. }
  532. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  533. // but using getBoundingClientRect to get a sub-pixel-accurate
  534. // result.
  535. function compensateForHScroll(display) {
  536. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  537. }
  538. // DISPLAY DRAWING
  539. function DisplayUpdate(cm, viewport, force) {
  540. var display = cm.display;
  541. this.viewport = viewport;
  542. // Store some values that we'll need later (but don't want to force a relayout for)
  543. this.visible = visibleLines(display, cm.doc, viewport);
  544. this.editorIsHidden = !display.wrapper.offsetWidth;
  545. this.wrapperHeight = display.wrapper.clientHeight;
  546. this.wrapperWidth = display.wrapper.clientWidth;
  547. this.oldDisplayWidth = displayWidth(cm);
  548. this.force = force;
  549. this.dims = getDimensions(cm);
  550. this.events = [];
  551. }
  552. DisplayUpdate.prototype.signal = function(emitter, type) {
  553. if (hasHandler(emitter, type))
  554. this.events.push(arguments);
  555. };
  556. DisplayUpdate.prototype.finish = function() {
  557. for (var i = 0; i < this.events.length; i++)
  558. signal.apply(null, this.events[i]);
  559. };
  560. function maybeClipScrollbars(cm) {
  561. var display = cm.display;
  562. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  563. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  564. display.heightForcer.style.height = scrollGap(cm) + "px";
  565. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  566. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  567. display.scrollbarsClipped = true;
  568. }
  569. }
  570. // Does the actual updating of the line display. Bails out
  571. // (returning false) when there is nothing to be done and forced is
  572. // false.
  573. function updateDisplayIfNeeded(cm, update) {
  574. var display = cm.display, doc = cm.doc;
  575. if (update.editorIsHidden) {
  576. resetView(cm);
  577. return false;
  578. }
  579. // Bail out if the visible area is already rendered and nothing changed.
  580. if (!update.force &&
  581. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  582. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  583. display.renderedView == display.view && countDirtyView(cm) == 0)
  584. return false;
  585. if (maybeUpdateLineNumberWidth(cm)) {
  586. resetView(cm);
  587. update.dims = getDimensions(cm);
  588. }
  589. // Compute a suitable new viewport (from & to)
  590. var end = doc.first + doc.size;
  591. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  592. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  593. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  594. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  595. if (sawCollapsedSpans) {
  596. from = visualLineNo(cm.doc, from);
  597. to = visualLineEndNo(cm.doc, to);
  598. }
  599. var different = from != display.viewFrom || to != display.viewTo ||
  600. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  601. adjustView(cm, from, to);
  602. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  603. // Position the mover div to align with the current scroll position
  604. cm.display.mover.style.top = display.viewOffset + "px";
  605. var toUpdate = countDirtyView(cm);
  606. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  607. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  608. return false;
  609. // For big changes, we hide the enclosing element during the
  610. // update, since that speeds up the operations on most browsers.
  611. var focused = activeElt();
  612. if (toUpdate > 4) display.lineDiv.style.display = "none";
  613. patchDisplay(cm, display.updateLineNumbers, update.dims);
  614. if (toUpdate > 4) display.lineDiv.style.display = "";
  615. display.renderedView = display.view;
  616. // There might have been a widget with a focused element that got
  617. // hidden or updated, if so re-focus it.
  618. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  619. // Prevent selection and cursors from interfering with the scroll
  620. // width and height.
  621. removeChildren(display.cursorDiv);
  622. removeChildren(display.selectionDiv);
  623. display.gutters.style.height = 0;
  624. if (different) {
  625. display.lastWrapHeight = update.wrapperHeight;
  626. display.lastWrapWidth = update.wrapperWidth;
  627. startWorker(cm, 400);
  628. }
  629. display.updateLineNumbers = null;
  630. return true;
  631. }
  632. function postUpdateDisplay(cm, update) {
  633. var viewport = update.viewport;
  634. for (var first = true;; first = false) {
  635. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  636. // Clip forced viewport to actual scrollable area.
  637. if (viewport && viewport.top != null)
  638. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  639. // Updated line heights might result in the drawn area not
  640. // actually covering the viewport. Keep looping until it does.
  641. update.visible = visibleLines(cm.display, cm.doc, viewport);
  642. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  643. break;
  644. }
  645. if (!updateDisplayIfNeeded(cm, update)) break;
  646. updateHeightsInViewport(cm);
  647. var barMeasure = measureForScrollbars(cm);
  648. updateSelection(cm);
  649. setDocumentHeight(cm, barMeasure);
  650. updateScrollbars(cm, barMeasure);
  651. }
  652. update.signal(cm, "update", cm);
  653. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  654. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  655. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  656. }
  657. }
  658. function updateDisplaySimple(cm, viewport) {
  659. var update = new DisplayUpdate(cm, viewport);
  660. if (updateDisplayIfNeeded(cm, update)) {
  661. updateHeightsInViewport(cm);
  662. postUpdateDisplay(cm, update);
  663. var barMeasure = measureForScrollbars(cm);
  664. updateSelection(cm);
  665. setDocumentHeight(cm, barMeasure);
  666. updateScrollbars(cm, barMeasure);
  667. update.finish();
  668. }
  669. }
  670. function setDocumentHeight(cm, measure) {
  671. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  672. var total = measure.docHeight + cm.display.barHeight;
  673. cm.display.heightForcer.style.top = total + "px";
  674. cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
  675. }
  676. // Read the actual heights of the rendered lines, and update their
  677. // stored heights to match.
  678. function updateHeightsInViewport(cm) {
  679. var display = cm.display;
  680. var prevBottom = display.lineDiv.offsetTop;
  681. for (var i = 0; i < display.view.length; i++) {
  682. var cur = display.view[i], height;
  683. if (cur.hidden) continue;
  684. if (ie && ie_version < 8) {
  685. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  686. height = bot - prevBottom;
  687. prevBottom = bot;
  688. } else {
  689. var box = cur.node.getBoundingClientRect();
  690. height = box.bottom - box.top;
  691. }
  692. var diff = cur.line.height - height;
  693. if (height < 2) height = textHeight(display);
  694. if (diff > .001 || diff < -.001) {
  695. updateLineHeight(cur.line, height);
  696. updateWidgetHeight(cur.line);
  697. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  698. updateWidgetHeight(cur.rest[j]);
  699. }
  700. }
  701. }
  702. // Read and store the height of line widgets associated with the
  703. // given line.
  704. function updateWidgetHeight(line) {
  705. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  706. line.widgets[i].height = line.widgets[i].node.offsetHeight;
  707. }
  708. // Do a bulk-read of the DOM positions and sizes needed to draw the
  709. // view, so that we don't interleave reading and writing to the DOM.
  710. function getDimensions(cm) {
  711. var d = cm.display, left = {}, width = {};
  712. var gutterLeft = d.gutters.clientLeft;
  713. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  714. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  715. width[cm.options.gutters[i]] = n.clientWidth;
  716. }
  717. return {fixedPos: compensateForHScroll(d),
  718. gutterTotalWidth: d.gutters.offsetWidth,
  719. gutterLeft: left,
  720. gutterWidth: width,
  721. wrapperWidth: d.wrapper.clientWidth};
  722. }
  723. // Sync the actual display DOM structure with display.view, removing
  724. // nodes for lines that are no longer in view, and creating the ones
  725. // that are not there yet, and updating the ones that are out of
  726. // date.
  727. function patchDisplay(cm, updateNumbersFrom, dims) {
  728. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  729. var container = display.lineDiv, cur = container.firstChild;
  730. function rm(node) {
  731. var next = node.nextSibling;
  732. // Works around a throw-scroll bug in OS X Webkit
  733. if (webkit && mac && cm.display.currentWheelTarget == node)
  734. node.style.display = "none";
  735. else
  736. node.parentNode.removeChild(node);
  737. return next;
  738. }
  739. var view = display.view, lineN = display.viewFrom;
  740. // Loop over the elements in the view, syncing cur (the DOM nodes
  741. // in display.lineDiv) with the view as we go.
  742. for (var i = 0; i < view.length; i++) {
  743. var lineView = view[i];
  744. if (lineView.hidden) {
  745. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  746. var node = buildLineElement(cm, lineView, lineN, dims);
  747. container.insertBefore(node, cur);
  748. } else { // Already drawn
  749. while (cur != lineView.node) cur = rm(cur);
  750. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  751. updateNumbersFrom <= lineN && lineView.lineNumber;
  752. if (lineView.changes) {
  753. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  754. updateLineForChanges(cm, lineView, lineN, dims);
  755. }
  756. if (updateNumber) {
  757. removeChildren(lineView.lineNumber);
  758. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  759. }
  760. cur = lineView.node.nextSibling;
  761. }
  762. lineN += lineView.size;
  763. }
  764. while (cur) cur = rm(cur);
  765. }
  766. // When an aspect of a line changes, a string is added to
  767. // lineView.changes. This updates the relevant part of the line's
  768. // DOM structure.
  769. function updateLineForChanges(cm, lineView, lineN, dims) {
  770. for (var j = 0; j < lineView.changes.length; j++) {
  771. var type = lineView.changes[j];
  772. if (type == "text") updateLineText(cm, lineView);
  773. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  774. else if (type == "class") updateLineClasses(lineView);
  775. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  776. }
  777. lineView.changes = null;
  778. }
  779. // Lines with gutter elements, widgets or a background class need to
  780. // be wrapped, and have the extra elements added to the wrapper div
  781. function ensureLineWrapped(lineView) {
  782. if (lineView.node == lineView.text) {
  783. lineView.node = elt("div", null, null, "position: relative");
  784. if (lineView.text.parentNode)
  785. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  786. lineView.node.appendChild(lineView.text);
  787. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  788. }
  789. return lineView.node;
  790. }
  791. function updateLineBackground(lineView) {
  792. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  793. if (cls) cls += " CodeMirror-linebackground";
  794. if (lineView.background) {
  795. if (cls) lineView.background.className = cls;
  796. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  797. } else if (cls) {
  798. var wrap = ensureLineWrapped(lineView);
  799. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  800. }
  801. }
  802. // Wrapper around buildLineContent which will reuse the structure
  803. // in display.externalMeasured when possible.
  804. function getLineContent(cm, lineView) {
  805. var ext = cm.display.externalMeasured;
  806. if (ext && ext.line == lineView.line) {
  807. cm.display.externalMeasured = null;
  808. lineView.measure = ext.measure;
  809. return ext.built;
  810. }
  811. return buildLineContent(cm, lineView);
  812. }
  813. // Redraw the line's text. Interacts with the background and text
  814. // classes because the mode may output tokens that influence these
  815. // classes.
  816. function updateLineText(cm, lineView) {
  817. var cls = lineView.text.className;
  818. var built = getLineContent(cm, lineView);
  819. if (lineView.text == lineView.node) lineView.node = built.pre;
  820. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  821. lineView.text = built.pre;
  822. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  823. lineView.bgClass = built.bgClass;
  824. lineView.textClass = built.textClass;
  825. updateLineClasses(lineView);
  826. } else if (cls) {
  827. lineView.text.className = cls;
  828. }
  829. }
  830. function updateLineClasses(lineView) {
  831. updateLineBackground(lineView);
  832. if (lineView.line.wrapClass)
  833. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  834. else if (lineView.node != lineView.text)
  835. lineView.node.className = "";
  836. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  837. lineView.text.className = textClass || "";
  838. }
  839. function updateLineGutter(cm, lineView, lineN, dims) {
  840. if (lineView.gutter) {
  841. lineView.node.removeChild(lineView.gutter);
  842. lineView.gutter = null;
  843. }
  844. var markers = lineView.line.gutterMarkers;
  845. if (cm.options.lineNumbers || markers) {
  846. var wrap = ensureLineWrapped(lineView);
  847. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  848. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  849. "px; width: " + dims.gutterTotalWidth + "px");
  850. cm.display.input.setUneditable(gutterWrap);
  851. wrap.insertBefore(gutterWrap, lineView.text);
  852. if (lineView.line.gutterClass)
  853. gutterWrap.className += " " + lineView.line.gutterClass;
  854. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  855. lineView.lineNumber = gutterWrap.appendChild(
  856. elt("div", lineNumberFor(cm.options, lineN),
  857. "CodeMirror-linenumber CodeMirror-gutter-elt",
  858. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  859. + cm.display.lineNumInnerWidth + "px"));
  860. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  861. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  862. if (found)
  863. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  864. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  865. }
  866. }
  867. }
  868. function updateLineWidgets(cm, lineView, dims) {
  869. if (lineView.alignable) lineView.alignable = null;
  870. for (var node = lineView.node.firstChild, next; node; node = next) {
  871. var next = node.nextSibling;
  872. if (node.className == "CodeMirror-linewidget")
  873. lineView.node.removeChild(node);
  874. }
  875. insertLineWidgets(cm, lineView, dims);
  876. }
  877. // Build a line's DOM representation from scratch
  878. function buildLineElement(cm, lineView, lineN, dims) {
  879. var built = getLineContent(cm, lineView);
  880. lineView.text = lineView.node = built.pre;
  881. if (built.bgClass) lineView.bgClass = built.bgClass;
  882. if (built.textClass) lineView.textClass = built.textClass;
  883. updateLineClasses(lineView);
  884. updateLineGutter(cm, lineView, lineN, dims);
  885. insertLineWidgets(cm, lineView, dims);
  886. return lineView.node;
  887. }
  888. // A lineView may contain multiple logical lines (when merged by
  889. // collapsed spans). The widgets for all of them need to be drawn.
  890. function insertLineWidgets(cm, lineView, dims) {
  891. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  892. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  893. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  894. }
  895. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  896. if (!line.widgets) return;
  897. var wrap = ensureLineWrapped(lineView);
  898. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  899. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  900. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  901. positionLineWidget(widget, node, lineView, dims);
  902. cm.display.input.setUneditable(node);
  903. if (allowAbove && widget.above)
  904. wrap.insertBefore(node, lineView.gutter || lineView.text);
  905. else
  906. wrap.appendChild(node);
  907. signalLater(widget, "redraw");
  908. }
  909. }
  910. function positionLineWidget(widget, node, lineView, dims) {
  911. if (widget.noHScroll) {
  912. (lineView.alignable || (lineView.alignable = [])).push(node);
  913. var width = dims.wrapperWidth;
  914. node.style.left = dims.fixedPos + "px";
  915. if (!widget.coverGutter) {
  916. width -= dims.gutterTotalWidth;
  917. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  918. }
  919. node.style.width = width + "px";
  920. }
  921. if (widget.coverGutter) {
  922. node.style.zIndex = 5;
  923. node.style.position = "relative";
  924. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  925. }
  926. }
  927. // POSITION OBJECT
  928. // A Pos instance represents a position within the text.
  929. var Pos = CodeMirror.Pos = function(line, ch) {
  930. if (!(this instanceof Pos)) return new Pos(line, ch);
  931. this.line = line; this.ch = ch;
  932. };
  933. // Compare two positions, return 0 if they are the same, a negative
  934. // number when a is less, and a positive number otherwise.
  935. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  936. function copyPos(x) {return Pos(x.line, x.ch);}
  937. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  938. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  939. // INPUT HANDLING
  940. function ensureFocus(cm) {
  941. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  942. }
  943. function isReadOnly(cm) {
  944. return cm.options.readOnly || cm.doc.cantEdit;
  945. }
  946. // This will be set to an array of strings when copying, so that,
  947. // when pasting, we know what kind of selections the copied text
  948. // was made out of.
  949. var lastCopied = null;
  950. function applyTextInput(cm, inserted, deleted, sel, origin) {
  951. var doc = cm.doc;
  952. cm.display.shift = false;
  953. if (!sel) sel = doc.sel;
  954. var textLines = splitLines(inserted), multiPaste = null;
  955. // When pasing N lines into N selections, insert one line per selection
  956. if (cm.state.pasteIncoming && sel.ranges.length > 1) {
  957. if (lastCopied && lastCopied.join("\n") == inserted)
  958. multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);
  959. else if (textLines.length == sel.ranges.length)
  960. multiPaste = map(textLines, function(l) { return [l]; });
  961. }
  962. // Normal behavior is to insert the new text into every selection
  963. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  964. var range = sel.ranges[i];
  965. var from = range.from(), to = range.to();
  966. if (range.empty()) {
  967. if (deleted && deleted > 0) // Handle deletion
  968. from = Pos(from.line, from.ch - deleted);
  969. else if (cm.state.overwrite && !cm.state.pasteIncoming) // Handle overwrite
  970. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  971. }
  972. var updateInput = cm.curOp.updateInput;
  973. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  974. origin: origin || (cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  975. makeChange(cm.doc, changeEvent);
  976. signalLater(cm, "inputRead", cm, changeEvent);
  977. }
  978. if (inserted && !cm.state.pasteIncoming)
  979. triggerElectric(cm, inserted);
  980. ensureCursorVisible(cm);
  981. cm.curOp.updateInput = updateInput;
  982. cm.curOp.typing = true;
  983. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  984. }
  985. function triggerElectric(cm, inserted) {
  986. // When an 'electric' character is inserted, immediately trigger a reindent
  987. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  988. var sel = cm.doc.sel;
  989. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  990. var range = sel.ranges[i];
  991. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  992. var mode = cm.getModeAt(range.head);
  993. var indented = false;
  994. if (mode.electricChars) {
  995. for (var j = 0; j < mode.electricChars.length; j++)
  996. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  997. indented = indentLine(cm, range.head.line, "smart");
  998. break;
  999. }
  1000. } else if (mode.electricInput) {
  1001. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  1002. indented = indentLine(cm, range.head.line, "smart");
  1003. }
  1004. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  1005. }
  1006. }
  1007. function copyableRanges(cm) {
  1008. var text = [], ranges = [];
  1009. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1010. var line = cm.doc.sel.ranges[i].head.line;
  1011. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  1012. ranges.push(lineRange);
  1013. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1014. }
  1015. return {text: text, ranges: ranges};
  1016. }
  1017. function disableBrowserMagic(field) {
  1018. field.setAttribute("autocorrect", "off");
  1019. field.setAttribute("autocapitalize", "off");
  1020. field.setAttribute("spellcheck", "false");
  1021. }
  1022. // TEXTAREA INPUT STYLE
  1023. function TextareaInput(cm) {
  1024. this.cm = cm;
  1025. // See input.poll and input.reset
  1026. this.prevInput = "";
  1027. // Flag that indicates whether we expect input to appear real soon
  1028. // now (after some event like 'keypress' or 'input') and are
  1029. // polling intensively.
  1030. this.pollingFast = false;
  1031. // Self-resetting timeout for the poller
  1032. this.polling = new Delayed();
  1033. // Tracks when input.reset has punted to just putting a short
  1034. // string into the textarea instead of the full selection.
  1035. this.inaccurateSelection = false;
  1036. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1037. this.hasSelection = false;
  1038. this.composing = null;
  1039. };
  1040. function hiddenTextarea() {
  1041. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  1042. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1043. // The textarea is kept positioned near the cursor to prevent the
  1044. // fact that it'll be scrolled into view on input from scrolling
  1045. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1046. // very slow. So make the area wide instead.
  1047. if (webkit) te.style.width = "1000px";
  1048. else te.setAttribute("wrap", "off");
  1049. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1050. if (ios) te.style.border = "1px solid black";
  1051. disableBrowserMagic(te);
  1052. return div;
  1053. }
  1054. TextareaInput.prototype = copyObj({
  1055. init: function(display) {
  1056. var input = this, cm = this.cm;
  1057. // Wraps and hides input textarea
  1058. var div = this.wrapper = hiddenTextarea();
  1059. // The semihidden textarea that is focused when the editor is
  1060. // focused, and receives input.
  1061. var te = this.textarea = div.firstChild;
  1062. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1063. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1064. if (ios) te.style.width = "0px";
  1065. on(te, "input", function() {
  1066. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1067. input.poll();
  1068. });
  1069. on(te, "paste", function() {
  1070. // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
  1071. // Add a char to the end of textarea before paste occur so that
  1072. // selection doesn't span to the end of textarea.
  1073. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
  1074. var start = te.selectionStart, end = te.selectionEnd;
  1075. te.value += "$";
  1076. // The selection end needs to be set before the start, otherwise there
  1077. // can be an intermediate non-empty selection between the two, which
  1078. // can override the middle-click paste buffer on linux and cause the
  1079. // wrong thing to get pasted.
  1080. te.selectionEnd = end;
  1081. te.selectionStart = start;
  1082. cm.state.fakedLastChar = true;
  1083. }
  1084. cm.state.pasteIncoming = true;
  1085. input.fastPoll();
  1086. });
  1087. function prepareCopyCut(e) {
  1088. if (cm.somethingSelected()) {
  1089. lastCopied = cm.getSelections();
  1090. if (input.inaccurateSelection) {
  1091. input.prevInput = "";
  1092. input.inaccurateSelection = false;
  1093. te.value = lastCopied.join("\n");
  1094. selectInput(te);
  1095. }
  1096. } else if (!cm.options.lineWiseCopyCut) {
  1097. return;
  1098. } else {
  1099. var ranges = copyableRanges(cm);
  1100. lastCopied = ranges.text;
  1101. if (e.type == "cut") {
  1102. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1103. } else {
  1104. input.prevInput = "";
  1105. te.value = ranges.text.join("\n");
  1106. selectInput(te);
  1107. }
  1108. }
  1109. if (e.type == "cut") cm.state.cutIncoming = true;
  1110. }
  1111. on(te, "cut", prepareCopyCut);
  1112. on(te, "copy", prepareCopyCut);
  1113. on(display.scroller, "paste", function(e) {
  1114. if (eventInWidget(display, e)) return;
  1115. cm.state.pasteIncoming = true;
  1116. input.focus();
  1117. });
  1118. // Prevent normal selection in the editor (we handle our own)
  1119. on(display.lineSpace, "selectstart", function(e) {
  1120. if (!eventInWidget(display, e)) e_preventDefault(e);
  1121. });
  1122. on(te, "compositionstart", function() {
  1123. var start = cm.getCursor("from");
  1124. input.composing = {
  1125. start: start,
  1126. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  1127. };
  1128. });
  1129. on(te, "compositionend", function() {
  1130. if (input.composing) {
  1131. input.poll();
  1132. input.composing.range.clear();
  1133. input.composing = null;
  1134. }
  1135. });
  1136. },
  1137. prepareSelection: function() {
  1138. // Redraw the selection and/or cursor
  1139. var cm = this.cm, display = cm.display, doc = cm.doc;
  1140. var result = prepareSelection(cm);
  1141. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1142. if (cm.options.moveInputWithCursor) {
  1143. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1144. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1145. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1146. headPos.top + lineOff.top - wrapOff.top));
  1147. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1148. headPos.left + lineOff.left - wrapOff.left));
  1149. }
  1150. return result;
  1151. },
  1152. showSelection: function(drawn) {
  1153. var cm = this.cm, display = cm.display;
  1154. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1155. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1156. if (drawn.teTop != null) {
  1157. this.wrapper.style.top = drawn.teTop + "px";
  1158. this.wrapper.style.left = drawn.teLeft + "px";
  1159. }
  1160. },
  1161. // Reset the input to correspond to the selection (or to be empty,
  1162. // when not typing and nothing is selected)
  1163. reset: function(typing) {
  1164. if (this.contextMenuPending) return;
  1165. var minimal, selected, cm = this.cm, doc = cm.doc;
  1166. if (cm.somethingSelected()) {
  1167. this.prevInput = "";
  1168. var range = doc.sel.primary();
  1169. minimal = hasCopyEvent &&
  1170. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1171. var content = minimal ? "-" : selected || cm.getSelection();
  1172. this.textarea.value = content;
  1173. if (cm.state.focused) selectInput(this.textarea);
  1174. if (ie && ie_version >= 9) this.hasSelection = content;
  1175. } else if (!typing) {
  1176. this.prevInput = this.textarea.value = "";
  1177. if (ie && ie_version >= 9) this.hasSelection = null;
  1178. }
  1179. this.inaccurateSelection = minimal;
  1180. },
  1181. getField: function() { return this.textarea; },
  1182. supportsTouch: function() { return false; },
  1183. focus: function() {
  1184. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1185. try { this.textarea.focus(); }
  1186. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  1187. }
  1188. },
  1189. blur: function() { this.textarea.blur(); },
  1190. resetPosition: function() {
  1191. this.wrapper.style.top = this.wrapper.style.left = 0;
  1192. },
  1193. receivedFocus: function() { this.slowPoll(); },
  1194. // Poll for input changes, using the normal rate of polling. This
  1195. // runs as long as the editor is focused.
  1196. slowPoll: function() {
  1197. var input = this;
  1198. if (input.pollingFast) return;
  1199. input.polling.set(this.cm.options.pollInterval, function() {
  1200. input.poll();
  1201. if (input.cm.state.focused) input.slowPoll();
  1202. });
  1203. },
  1204. // When an event has just come in that is likely to add or change
  1205. // something in the input textarea, we poll faster, to ensure that
  1206. // the change appears on the screen quickly.
  1207. fastPoll: function() {
  1208. var missed = false, input = this;
  1209. input.pollingFast = true;
  1210. function p() {
  1211. var changed = input.poll();
  1212. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  1213. else {input.pollingFast = false; input.slowPoll();}
  1214. }
  1215. input.polling.set(20, p);
  1216. },
  1217. // Read input from the textarea, and update the document to match.
  1218. // When something is selected, it is present in the textarea, and
  1219. // selected (unless it is huge, in which case a placeholder is
  1220. // used). When nothing is selected, the cursor sits after previously
  1221. // seen text (can be empty), which is stored in prevInput (we must
  1222. // not reset the textarea when typing, because that breaks IME).
  1223. poll: function() {
  1224. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1225. // Since this is called a *lot*, try to bail out as cheaply as
  1226. // possible when it is clear that nothing happened. hasSelection
  1227. // will be the case when there is a lot of text in the textarea,
  1228. // in which case reading its value would be expensive.
  1229. if (!cm.state.focused || (hasSelection(input) && !prevInput) ||
  1230. isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
  1231. return false;
  1232. // See paste handler for more on the fakedLastChar kludge
  1233. if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
  1234. input.value = input.value.substring(0, input.value.length - 1);
  1235. cm.state.fakedLastChar = false;
  1236. }
  1237. var text = input.value;
  1238. // If nothing changed, bail.
  1239. if (text == prevInput && !cm.somethingSelected()) return false;
  1240. // Work around nonsensical selection resetting in IE9/10, and
  1241. // inexplicable appearance of private area unicode characters on
  1242. // some key combos in Mac (#2689).
  1243. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1244. mac && /[\uf700-\uf7ff]/.test(text)) {
  1245. cm.display.input.reset();
  1246. return false;
  1247. }
  1248. if (cm.doc.sel == cm.display.selForContextMenu) {
  1249. var first = text.charCodeAt(0);
  1250. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  1251. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  1252. }
  1253. // Find the part of the input that is actually new
  1254. var same = 0, l = Math.min(prevInput.length, text.length);
  1255. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1256. var self = this;
  1257. runInOp(cm, function() {
  1258. applyTextInput(cm, text.slice(same), prevInput.length - same,
  1259. null, self.composing ? "*compose" : null);
  1260. // Don't leave long text in the textarea, since it makes further polling slow
  1261. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1262. else self.prevInput = text;
  1263. if (self.composing) {
  1264. self.composing.range.clear();
  1265. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  1266. {className: "CodeMirror-composing"});
  1267. }
  1268. });
  1269. return true;
  1270. },
  1271. ensurePolled: function() {
  1272. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1273. },
  1274. onKeyPress: function() {
  1275. if (ie && ie_version >= 9) this.hasSelection = null;
  1276. this.fastPoll();
  1277. },
  1278. onContextMenu: function(e) {
  1279. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1280. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1281. if (!pos || presto) return; // Opera is difficult.
  1282. // Reset the current text selection only if the click is done outside of the selection
  1283. // and 'resetSelectionOnContextMenu' option is true.
  1284. var reset = cm.options.resetSelectionOnContextMenu;
  1285. if (reset && cm.doc.sel.contains(pos) == -1)
  1286. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1287. var oldCSS = te.style.cssText;
  1288. input.wrapper.style.position = "absolute";
  1289. te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1290. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
  1291. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1292. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1293. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1294. display.input.focus();
  1295. if (webkit) window.scrollTo(null, oldScrollY);
  1296. display.input.reset();
  1297. // Adds "Select all" to context menu in FF
  1298. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1299. input.contextMenuPending = true;
  1300. display.selForContextMenu = cm.doc.sel;
  1301. clearTimeout(display.detectingSelectAll);
  1302. // Select-all will be greyed out if there's nothing to select, so
  1303. // this adds a zero-width space so that we can later check whether
  1304. // it got selected.
  1305. function prepareSelectAllHack() {
  1306. if (te.selectionStart != null) {
  1307. var selected = cm.somethingSelected();
  1308. var extval = "\u200b" + (selected ? te.value : "");
  1309. te.value = "\u21da"; // Used to catch context-menu undo
  1310. te.value = extval;
  1311. input.prevInput = selected ? "" : "\u200b";
  1312. te.selectionStart = 1; te.selectionEnd = extval.length;
  1313. // Re-set this, in case some other handler touched the
  1314. // selection in the meantime.
  1315. display.selForContextMenu = cm.doc.sel;
  1316. }
  1317. }
  1318. function rehide() {
  1319. input.contextMenuPending = false;
  1320. input.wrapper.style.position = "relative";
  1321. te.style.cssText = oldCSS;
  1322. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1323. // Try to detect the user choosing select-all
  1324. if (te.selectionStart != null) {
  1325. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1326. var i = 0, poll = function() {
  1327. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  1328. te.selectionEnd > 0 && input.prevInput == "\u200b")
  1329. operation(cm, commands.selectAll)(cm);
  1330. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1331. else display.input.reset();
  1332. };
  1333. display.detectingSelectAll = setTimeout(poll, 200);
  1334. }
  1335. }
  1336. if (ie && ie_version >= 9) prepareSelectAllHack();
  1337. if (captureRightClick) {
  1338. e_stop(e);
  1339. var mouseup = function() {
  1340. off(window, "mouseup", mouseup);
  1341. setTimeout(rehide, 20);
  1342. };
  1343. on(window, "mouseup", mouseup);
  1344. } else {
  1345. setTimeout(rehide, 50);
  1346. }
  1347. },
  1348. setUneditable: nothing,
  1349. needsContentAttribute: false
  1350. }, TextareaInput.prototype);
  1351. // CONTENTEDITABLE INPUT STYLE
  1352. function ContentEditableInput(cm) {
  1353. this.cm = cm;
  1354. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1355. this.polling = new Delayed();
  1356. this.gracePeriod = false;
  1357. }
  1358. ContentEditableInput.prototype = copyObj({
  1359. init: function(display) {
  1360. var input = this, cm = input.cm;
  1361. var div = input.div = display.lineDiv;
  1362. div.contentEditable = "true";
  1363. disableBrowserMagic(div);
  1364. on(div, "paste", function(e) {
  1365. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1366. if (pasted) {
  1367. e.preventDefault();
  1368. cm.replaceSelection(pasted, null, "paste");
  1369. }
  1370. });
  1371. on(div, "compositionstart", function(e) {
  1372. var data = e.data;
  1373. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  1374. if (!data) return;
  1375. var prim = cm.doc.sel.primary();
  1376. var line = cm.getLine(prim.head.line);
  1377. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1378. if (found > -1 && found <= prim.head.ch)
  1379. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1380. Pos(prim.head.line, found + data.length));
  1381. });
  1382. on(div, "compositionupdate", function(e) {
  1383. input.composing.data = e.data;
  1384. });
  1385. on(div, "compositionend", function(e) {
  1386. var ours = input.composing;
  1387. if (!ours) return;
  1388. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1389. ours.data = e.data;
  1390. // Need a small delay to prevent other code (input event,
  1391. // selection polling) from doing damage when fired right after
  1392. // compositionend.
  1393. setTimeout(function() {
  1394. if (!ours.handled)
  1395. input.applyComposition(ours);
  1396. if (input.composing == ours)
  1397. input.composing = null;
  1398. }, 50);
  1399. });
  1400. on(div, "touchstart", function() {
  1401. input.forceCompositionEnd();
  1402. });
  1403. on(div, "input", function() {
  1404. if (input.composing) return;
  1405. if (!input.pollContent())
  1406. runInOp(input.cm, function() {regChange(cm);});
  1407. });
  1408. function onCopyCut(e) {
  1409. if (cm.somethingSelected()) {
  1410. lastCopied = cm.getSelections();
  1411. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1412. } else if (!cm.options.lineWiseCopyCut) {
  1413. return;
  1414. } else {
  1415. var ranges = copyableRanges(cm);
  1416. lastCopied = ranges.text;
  1417. if (e.type == "cut") {
  1418. cm.operation(function() {
  1419. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1420. cm.replaceSelection("", null, "cut");
  1421. });
  1422. }
  1423. }
  1424. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1425. if (e.clipboardData && !ios) {
  1426. e.preventDefault();
  1427. e.clipboardData.clearData();
  1428. e.clipboardData.setData("text/plain", lastCopied.join("\n"));
  1429. } else {
  1430. // Old-fashioned briefly-focus-a-textarea hack
  1431. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1432. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1433. te.value = lastCopied.join("\n");
  1434. var hadFocus = document.activeElement;
  1435. selectInput(te);
  1436. setTimeout(function() {
  1437. cm.display.lineSpace.removeChild(kludge);
  1438. hadFocus.focus();
  1439. }, 50);
  1440. }
  1441. }
  1442. on(div, "copy", onCopyCut);
  1443. on(div, "cut", onCopyCut);
  1444. },
  1445. prepareSelection: function() {
  1446. var result = prepareSelection(this.cm, false);
  1447. result.focus = this.cm.state.focused;
  1448. return result;
  1449. },
  1450. showSelection: function(info) {
  1451. if (!info || !this.cm.display.view.length) return;
  1452. if (info.focus) this.showPrimarySelection();
  1453. this.showMultipleSelections(info);
  1454. },
  1455. showPrimarySelection: function() {
  1456. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1457. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1458. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1459. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1460. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1461. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1462. return;
  1463. var start = posToDOM(this.cm, prim.from());
  1464. var end = posToDOM(this.cm, prim.to());
  1465. if (!start && !end) return;
  1466. var view = this.cm.display.view;
  1467. var old = sel.rangeCount && sel.getRangeAt(0);
  1468. if (!start) {
  1469. start = {node: view[0].measure.map[2], offset: 0};
  1470. } else if (!end) { // FIXME dangerously hacky
  1471. var measure = view[view.length - 1].measure;
  1472. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1473. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  1474. }
  1475. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1476. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1477. if (rng) {
  1478. sel.removeAllRanges();
  1479. sel.addRange(rng);
  1480. if (old && sel.anchorNode == null) sel.addRange(old);
  1481. else if (gecko) this.startGracePeriod();
  1482. }
  1483. this.rememberSelection();
  1484. },
  1485. startGracePeriod: function() {
  1486. var input = this;
  1487. clearTimeout(this.gracePeriod);
  1488. this.gracePeriod = setTimeout(function() {
  1489. input.gracePeriod = false;
  1490. if (input.selectionChanged())
  1491. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  1492. }, 20);
  1493. },
  1494. showMultipleSelections: function(info) {
  1495. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1496. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1497. },
  1498. rememberSelection: function() {
  1499. var sel = window.getSelection();
  1500. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1501. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1502. },
  1503. selectionInEditor: function() {
  1504. var sel = window.getSelection();
  1505. if (!sel.rangeCount) return false;
  1506. var node = sel.getRangeAt(0).commonAncestorContainer;
  1507. return contains(this.div, node);
  1508. },
  1509. focus: function() {
  1510. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1511. },
  1512. blur: function() { this.div.blur(); },
  1513. getField: function() { return this.div; },
  1514. supportsTouch: function() { return true; },
  1515. receivedFocus: function() {
  1516. var input = this;
  1517. if (this.selectionInEditor())
  1518. this.pollSelection();
  1519. else
  1520. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  1521. function poll() {
  1522. if (input.cm.state.focused) {
  1523. input.pollSelection();
  1524. input.polling.set(input.cm.options.pollInterval, poll);
  1525. }
  1526. }
  1527. this.polling.set(this.cm.options.pollInterval, poll);
  1528. },
  1529. selectionChanged: function() {
  1530. var sel = window.getSelection();
  1531. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1532. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  1533. },
  1534. pollSelection: function() {
  1535. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  1536. var sel = window.getSelection(), cm = this.cm;
  1537. this.rememberSelection();
  1538. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1539. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1540. if (anchor && head) runInOp(cm, function() {
  1541. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1542. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1543. });
  1544. }
  1545. },
  1546. pollContent: function() {
  1547. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1548. var from = sel.from(), to = sel.to();
  1549. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1550. var fromIndex;
  1551. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1552. var fromLine = lineNo(display.view[0].line);
  1553. var fromNode = display.view[0].node;
  1554. } else {
  1555. var fromLine = lineNo(display.view[fromIndex].line);
  1556. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1557. }
  1558. var toIndex = findViewIndex(cm, to.line);
  1559. if (toIndex == display.view.length - 1) {
  1560. var toLine = display.viewTo - 1;
  1561. var toNode = display.view[toIndex].node;
  1562. } else {
  1563. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1564. var toNode = display.view[toIndex + 1].node.previousSibling;
  1565. }
  1566. var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1567. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1568. while (newText.length > 1 && oldText.length > 1) {
  1569. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1570. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1571. else break;
  1572. }
  1573. var cutFront = 0, cutEnd = 0;
  1574. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1575. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1576. ++cutFront;
  1577. var newBot = lst(newText), oldBot = lst(oldText);
  1578. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1579. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1580. while (cutEnd < maxCutEnd &&
  1581. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1582. ++cutEnd;
  1583. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1584. newText[0] = newText[0].slice(cutFront);
  1585. var chFrom = Pos(fromLine, cutFront);
  1586. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1587. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1588. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1589. return true;
  1590. }
  1591. },
  1592. ensurePolled: function() {
  1593. this.forceCompositionEnd();
  1594. },
  1595. reset: function() {
  1596. this.forceCompositionEnd();
  1597. },
  1598. forceCompositionEnd: function() {
  1599. if (!this.composing || this.composing.handled) return;
  1600. this.applyComposition(this.composing);
  1601. this.composing.handled = true;
  1602. this.div.blur();
  1603. this.div.focus();
  1604. },
  1605. applyComposition: function(composing) {
  1606. if (composing.data && composing.data != composing.startData)
  1607. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1608. },
  1609. setUneditable: function(node) {
  1610. node.setAttribute("contenteditable", "false");
  1611. },
  1612. onKeyPress: function(e) {
  1613. e.preventDefault();
  1614. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1615. },
  1616. onContextMenu: nothing,
  1617. resetPosition: nothing,
  1618. needsContentAttribute: true
  1619. }, ContentEditableInput.prototype);
  1620. function posToDOM(cm, pos) {
  1621. var view = findViewForLine(cm, pos.line);
  1622. if (!view || view.hidden) return null;
  1623. var line = getLine(cm.doc, pos.line);
  1624. var info = mapFromLineView(view, line, pos.line);
  1625. var order = getOrder(line), side = "left";
  1626. if (order) {
  1627. var partPos = getBidiPartAt(order, pos.ch);
  1628. side = partPos % 2 ? "right" : "left";
  1629. }
  1630. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  1631. result.offset = result.collapse == "right" ? result.end : result.start;
  1632. return result;
  1633. }
  1634. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1635. function domToPos(cm, node, offset) {
  1636. var lineNode;
  1637. if (node == cm.display.lineDiv) {
  1638. lineNode = cm.display.lineDiv.childNodes[offset];
  1639. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1640. node = null; offset = 0;
  1641. } else {
  1642. for (lineNode = node;; lineNode = lineNode.parentNode) {
  1643. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1644. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1645. }
  1646. }
  1647. for (var i = 0; i < cm.display.view.length; i++) {
  1648. var lineView = cm.display.view[i];
  1649. if (lineView.node == lineNode)
  1650. return locateNodeInLineView(lineView, node, offset);
  1651. }
  1652. }
  1653. function locateNodeInLineView(lineView, node, offset) {
  1654. var wrapper = lineView.text.firstChild, bad = false;
  1655. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1656. if (node == wrapper) {
  1657. bad = true;
  1658. node = wrapper.childNodes[offset];
  1659. offset = 0;
  1660. if (!node) {
  1661. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1662. return badPos(Pos(lineNo(line), line.text.length), bad);
  1663. }
  1664. }
  1665. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1666. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1667. textNode = node.firstChild;
  1668. if (offset) offset = textNode.nodeValue.length;
  1669. }
  1670. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1671. var measure = lineView.measure, maps = measure.maps;
  1672. function find(textNode, topNode, offset) {
  1673. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1674. var map = i < 0 ? measure.map : maps[i];
  1675. for (var j = 0; j < map.length; j += 3) {
  1676. var curNode = map[j + 2];
  1677. if (curNode == textNode || curNode == topNode) {
  1678. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1679. var ch = map[j] + offset;
  1680. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1681. return Pos(line, ch);
  1682. }
  1683. }
  1684. }
  1685. }
  1686. var found = find(textNode, topNode, offset);
  1687. if (found) return badPos(found, bad);
  1688. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1689. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1690. found = find(after, after.firstChild, 0);
  1691. if (found)
  1692. return badPos(Pos(found.line, found.ch - dist), bad);
  1693. else
  1694. dist += after.textContent.length;
  1695. }
  1696. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1697. found = find(before, before.firstChild, -1);
  1698. if (found)
  1699. return badPos(Pos(found.line, found.ch + dist), bad);
  1700. else
  1701. dist += after.textContent.length;
  1702. }
  1703. }
  1704. function domTextBetween(cm, from, to, fromLine, toLine) {
  1705. var text = "", closing = false;
  1706. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  1707. function walk(node) {
  1708. if (node.nodeType == 1) {
  1709. var cmText = node.getAttribute("cm-text");
  1710. if (cmText != null) {
  1711. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1712. text += cmText;
  1713. return;
  1714. }
  1715. var markerID = node.getAttribute("cm-marker"), range;
  1716. if (markerID) {
  1717. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1718. if (found.length && (range = found[0].find()))
  1719. text += getBetween(cm.doc, range.from, range.to).join("\n");
  1720. return;
  1721. }
  1722. if (node.getAttribute("contenteditable") == "false") return;
  1723. for (var i = 0; i < node.childNodes.length; i++)
  1724. walk(node.childNodes[i]);
  1725. if (/^(pre|div|p)$/i.test(node.nodeName))
  1726. closing = true;
  1727. } else if (node.nodeType == 3) {
  1728. var val = node.nodeValue;
  1729. if (!val) return;
  1730. if (closing) {
  1731. text += "\n";
  1732. closing = false;
  1733. }
  1734. text += val;
  1735. }
  1736. }
  1737. for (;;) {
  1738. walk(from);
  1739. if (from == to) break;
  1740. from = from.nextSibling;
  1741. }
  1742. return text;
  1743. }
  1744. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  1745. // SELECTION / CURSOR
  1746. // Selection objects are immutable. A new one is created every time
  1747. // the selection changes. A selection is one or more non-overlapping
  1748. // (and non-touching) ranges, sorted, and an integer that indicates
  1749. // which one is the primary selection (the one that's scrolled into
  1750. // view, that getCursor returns, etc).
  1751. function Selection(ranges, primIndex) {
  1752. this.ranges = ranges;
  1753. this.primIndex = primIndex;
  1754. }
  1755. Selection.prototype = {
  1756. primary: function() { return this.ranges[this.primIndex]; },
  1757. equals: function(other) {
  1758. if (other == this) return true;
  1759. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1760. for (var i = 0; i < this.ranges.length; i++) {
  1761. var here = this.ranges[i], there = other.ranges[i];
  1762. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1763. }
  1764. return true;
  1765. },
  1766. deepCopy: function() {
  1767. for (var out = [], i = 0; i < this.ranges.length; i++)
  1768. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1769. return new Selection(out, this.primIndex);
  1770. },
  1771. somethingSelected: function() {
  1772. for (var i = 0; i < this.ranges.length; i++)
  1773. if (!this.ranges[i].empty()) return true;
  1774. return false;
  1775. },
  1776. contains: function(pos, end) {
  1777. if (!end) end = pos;
  1778. for (var i = 0; i < this.ranges.length; i++) {
  1779. var range = this.ranges[i];
  1780. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1781. return i;
  1782. }
  1783. return -1;
  1784. }
  1785. };
  1786. function Range(anchor, head) {
  1787. this.anchor = anchor; this.head = head;
  1788. }
  1789. Range.prototype = {
  1790. from: function() { return minPos(this.anchor, this.head); },
  1791. to: function() { return maxPos(this.anchor, this.head); },
  1792. empty: function() {
  1793. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1794. }
  1795. };
  1796. // Take an unsorted, potentially overlapping set of ranges, and
  1797. // build a selection out of it. 'Consumes' ranges array (modifying
  1798. // it).
  1799. function normalizeSelection(ranges, primIndex) {
  1800. var prim = ranges[primIndex];
  1801. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1802. primIndex = indexOf(ranges, prim);
  1803. for (var i = 1; i < ranges.length; i++) {
  1804. var cur = ranges[i], prev = ranges[i - 1];
  1805. if (cmp(prev.to(), cur.from()) >= 0) {
  1806. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1807. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1808. if (i <= primIndex) --primIndex;
  1809. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1810. }
  1811. }
  1812. return new Selection(ranges, primIndex);
  1813. }
  1814. function simpleSelection(anchor, head) {
  1815. return new Selection([new Range(anchor, head || anchor)], 0);
  1816. }
  1817. // Most of the external API clips given positions to make sure they
  1818. // actually exist within the document.
  1819. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1820. function clipPos(doc, pos) {
  1821. if (pos.line < doc.first) return Pos(doc.first, 0);
  1822. var last = doc.first + doc.size - 1;
  1823. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1824. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1825. }
  1826. function clipToLen(pos, linelen) {
  1827. var ch = pos.ch;
  1828. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1829. else if (ch < 0) return Pos(pos.line, 0);
  1830. else return pos;
  1831. }
  1832. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1833. function clipPosArray(doc, array) {
  1834. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1835. return out;
  1836. }
  1837. // SELECTION UPDATES
  1838. // The 'scroll' parameter given to many of these indicated whether
  1839. // the new cursor position should be scrolled into view after
  1840. // modifying the selection.
  1841. // If shift is held or the extend flag is set, extends a range to
  1842. // include a given position (and optionally a second position).
  1843. // Otherwise, simply returns the range between the given positions.
  1844. // Used for cursor motion and such.
  1845. function extendRange(doc, range, head, other) {
  1846. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1847. var anchor = range.anchor;
  1848. if (other) {
  1849. var posBefore = cmp(head, anchor) < 0;
  1850. if (posBefore != (cmp(other, anchor) < 0)) {
  1851. anchor = head;
  1852. head = other;
  1853. } else if (posBefore != (cmp(head, other) < 0)) {
  1854. head = other;
  1855. }
  1856. }
  1857. return new Range(anchor, head);
  1858. } else {
  1859. return new Range(other || head, head);
  1860. }
  1861. }
  1862. // Extend the primary selection range, discard the rest.
  1863. function extendSelection(doc, head, other, options) {
  1864. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1865. }
  1866. // Extend all selections (pos is an array of selections with length
  1867. // equal the number of selections)
  1868. function extendSelections(doc, heads, options) {
  1869. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1870. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1871. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1872. setSelection(doc, newSel, options);
  1873. }
  1874. // Updates a single range in the selection.
  1875. function replaceOneSelection(doc, i, range, options) {
  1876. var ranges = doc.sel.ranges.slice(0);
  1877. ranges[i] = range;
  1878. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1879. }
  1880. // Reset the selection to a single range.
  1881. function setSimpleSelection(doc, anchor, head, options) {
  1882. setSelection(doc, simpleSelection(anchor, head), options);
  1883. }
  1884. // Give beforeSelectionChange handlers a change to influence a
  1885. // selection update.
  1886. function filterSelectionChange(doc, sel) {
  1887. var obj = {
  1888. ranges: sel.ranges,
  1889. update: function(ranges) {
  1890. this.ranges = [];
  1891. for (var i = 0; i < ranges.length; i++)
  1892. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1893. clipPos(doc, ranges[i].head));
  1894. }
  1895. };
  1896. signal(doc, "beforeSelectionChange", doc, obj);
  1897. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1898. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1899. else return sel;
  1900. }
  1901. function setSelectionReplaceHistory(doc, sel, options) {
  1902. var done = doc.history.done, last = lst(done);
  1903. if (last && last.ranges) {
  1904. done[done.length - 1] = sel;
  1905. setSelectionNoUndo(doc, sel, options);
  1906. } else {
  1907. setSelection(doc, sel, options);
  1908. }
  1909. }
  1910. // Set a new selection.
  1911. function setSelection(doc, sel, options) {
  1912. setSelectionNoUndo(doc, sel, options);
  1913. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1914. }
  1915. function setSelectionNoUndo(doc, sel, options) {
  1916. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1917. sel = filterSelectionChange(doc, sel);
  1918. var bias = options && options.bias ||
  1919. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1920. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1921. if (!(options && options.scroll === false) && doc.cm)
  1922. ensureCursorVisible(doc.cm);
  1923. }
  1924. function setSelectionInner(doc, sel) {
  1925. if (sel.equals(doc.sel)) return;
  1926. doc.sel = sel;
  1927. if (doc.cm) {
  1928. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1929. signalCursorActivity(doc.cm);
  1930. }
  1931. signalLater(doc, "cursorActivity", doc);
  1932. }
  1933. // Verify that the selection does not partially select any atomic
  1934. // marked ranges.
  1935. function reCheckSelection(doc) {
  1936. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1937. }
  1938. // Return a selection that does not partially select any atomic
  1939. // ranges.
  1940. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1941. var out;
  1942. for (var i = 0; i < sel.ranges.length; i++) {
  1943. var range = sel.ranges[i];
  1944. var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
  1945. var newHead = skipAtomic(doc, range.head, bias, mayClear);
  1946. if (out || newAnchor != range.anchor || newHead != range.head) {
  1947. if (!out) out = sel.ranges.slice(0, i);
  1948. out[i] = new Range(newAnchor, newHead);
  1949. }
  1950. }
  1951. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1952. }
  1953. // Ensure a given position is not inside an atomic range.
  1954. function skipAtomic(doc, pos, bias, mayClear) {
  1955. var flipped = false, curPos = pos;
  1956. var dir = bias || 1;
  1957. doc.cantEdit = false;
  1958. search: for (;;) {
  1959. var line = getLine(doc, curPos.line);
  1960. if (line.markedSpans) {
  1961. for (var i = 0; i < line.markedSpans.length; ++i) {
  1962. var sp = line.markedSpans[i], m = sp.marker;
  1963. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  1964. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  1965. if (mayClear) {
  1966. signal(m, "beforeCursorEnter");
  1967. if (m.explicitlyCleared) {
  1968. if (!line.markedSpans) break;
  1969. else {--i; continue;}
  1970. }
  1971. }
  1972. if (!m.atomic) continue;
  1973. var newPos = m.find(dir < 0 ? -1 : 1);
  1974. if (cmp(newPos, curPos) == 0) {
  1975. newPos.ch += dir;
  1976. if (newPos.ch < 0) {
  1977. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  1978. else newPos = null;
  1979. } else if (newPos.ch > line.text.length) {
  1980. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  1981. else newPos = null;
  1982. }
  1983. if (!newPos) {
  1984. if (flipped) {
  1985. // Driven in a corner -- no valid cursor position found at all
  1986. // -- try again *with* clearing, if we didn't already
  1987. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  1988. // Otherwise, turn off editing until further notice, and return the start of the doc
  1989. doc.cantEdit = true;
  1990. return Pos(doc.first, 0);
  1991. }
  1992. flipped = true; newPos = pos; dir = -dir;
  1993. }
  1994. }
  1995. curPos = newPos;
  1996. continue search;
  1997. }
  1998. }
  1999. }
  2000. return curPos;
  2001. }
  2002. }
  2003. // SELECTION DRAWING
  2004. function updateSelection(cm) {
  2005. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2006. }
  2007. function prepareSelection(cm, primary) {
  2008. var doc = cm.doc, result = {};
  2009. var curFragment = result.cursors = document.createDocumentFragment();
  2010. var selFragment = result.selection = document.createDocumentFragment();
  2011. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2012. if (primary === false && i == doc.sel.primIndex) continue;
  2013. var range = doc.sel.ranges[i];
  2014. var collapsed = range.empty();
  2015. if (collapsed || cm.options.showCursorWhenSelecting)
  2016. drawSelectionCursor(cm, range, curFragment);
  2017. if (!collapsed)
  2018. drawSelectionRange(cm, range, selFragment);
  2019. }
  2020. return result;
  2021. }
  2022. // Draws a cursor for the given range
  2023. function drawSelectionCursor(cm, range, output) {
  2024. var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2025. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2026. cursor.style.left = pos.left + "px";
  2027. cursor.style.top = pos.top + "px";
  2028. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2029. if (pos.other) {
  2030. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2031. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2032. otherCursor.style.display = "";
  2033. otherCursor.style.left = pos.other.left + "px";
  2034. otherCursor.style.top = pos.other.top + "px";
  2035. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2036. }
  2037. }
  2038. // Draws the given range as a highlighted selection
  2039. function drawSelectionRange(cm, range, output) {
  2040. var display = cm.display, doc = cm.doc;
  2041. var fragment = document.createDocumentFragment();
  2042. var padding = paddingH(cm.display), leftSide = padding.left;
  2043. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2044. function add(left, top, width, bottom) {
  2045. if (top < 0) top = 0;
  2046. top = Math.round(top);
  2047. bottom = Math.round(bottom);
  2048. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  2049. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  2050. "px; height: " + (bottom - top) + "px"));
  2051. }
  2052. function drawForLine(line, fromArg, toArg) {
  2053. var lineObj = getLine(doc, line);
  2054. var lineLen = lineObj.text.length;
  2055. var start, end;
  2056. function coords(ch, bias) {
  2057. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2058. }
  2059. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  2060. var leftPos = coords(from, "left"), rightPos, left, right;
  2061. if (from == to) {
  2062. rightPos = leftPos;
  2063. left = right = leftPos.left;
  2064. } else {
  2065. rightPos = coords(to - 1, "right");
  2066. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2067. left = leftPos.left;
  2068. right = rightPos.right;
  2069. }
  2070. if (fromArg == null && from == 0) left = leftSide;
  2071. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2072. add(left, leftPos.top, null, leftPos.bottom);
  2073. left = leftSide;
  2074. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2075. }
  2076. if (toArg == null && to == lineLen) right = rightSide;
  2077. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2078. start = leftPos;
  2079. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2080. end = rightPos;
  2081. if (left < leftSide + 1) left = leftSide;
  2082. add(left, rightPos.top, right - left, rightPos.bottom);
  2083. });
  2084. return {start: start, end: end};
  2085. }
  2086. var sFrom = range.from(), sTo = range.to();
  2087. if (sFrom.line == sTo.line) {
  2088. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2089. } else {
  2090. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2091. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2092. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2093. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2094. if (singleVLine) {
  2095. if (leftEnd.top < rightStart.top - 2) {
  2096. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2097. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2098. } else {
  2099. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2100. }
  2101. }
  2102. if (leftEnd.bottom < rightStart.top)
  2103. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2104. }
  2105. output.appendChild(fragment);
  2106. }
  2107. // Cursor-blinking
  2108. function restartBlink(cm) {
  2109. if (!cm.state.focused) return;
  2110. var display = cm.display;
  2111. clearInterval(display.blinker);
  2112. var on = true;
  2113. display.cursorDiv.style.visibility = "";
  2114. if (cm.options.cursorBlinkRate > 0)
  2115. display.blinker = setInterval(function() {
  2116. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2117. }, cm.options.cursorBlinkRate);
  2118. else if (cm.options.cursorBlinkRate < 0)
  2119. display.cursorDiv.style.visibility = "hidden";
  2120. }
  2121. // HIGHLIGHT WORKER
  2122. function startWorker(cm, time) {
  2123. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2124. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2125. }
  2126. function highlightWorker(cm) {
  2127. var doc = cm.doc;
  2128. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2129. if (doc.frontier >= cm.display.viewTo) return;
  2130. var end = +new Date + cm.options.workTime;
  2131. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2132. var changedLines = [];
  2133. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  2134. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2135. var oldStyles = line.styles;
  2136. var highlighted = highlightLine(cm, line, state, true);
  2137. line.styles = highlighted.styles;
  2138. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2139. if (newCls) line.styleClasses = newCls;
  2140. else if (oldCls) line.styleClasses = null;
  2141. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2142. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2143. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2144. if (ischange) changedLines.push(doc.frontier);
  2145. line.stateAfter = copyState(doc.mode, state);
  2146. } else {
  2147. processLine(cm, line.text, state);
  2148. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2149. }
  2150. ++doc.frontier;
  2151. if (+new Date > end) {
  2152. startWorker(cm, cm.options.workDelay);
  2153. return true;
  2154. }
  2155. });
  2156. if (changedLines.length) runInOp(cm, function() {
  2157. for (var i = 0; i < changedLines.length; i++)
  2158. regLineChange(cm, changedLines[i], "text");
  2159. });
  2160. }
  2161. // Finds the line to start with when starting a parse. Tries to
  2162. // find a line with a stateAfter, so that it can start with a
  2163. // valid state. If that fails, it returns the line with the
  2164. // smallest indentation, which tends to need the least context to
  2165. // parse correctly.
  2166. function findStartLine(cm, n, precise) {
  2167. var minindent, minline, doc = cm.doc;
  2168. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2169. for (var search = n; search > lim; --search) {
  2170. if (search <= doc.first) return doc.first;
  2171. var line = getLine(doc, search - 1);
  2172. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2173. var indented = countColumn(line.text, null, cm.options.tabSize);
  2174. if (minline == null || minindent > indented) {
  2175. minline = search - 1;
  2176. minindent = indented;
  2177. }
  2178. }
  2179. return minline;
  2180. }
  2181. function getStateBefore(cm, n, precise) {
  2182. var doc = cm.doc, display = cm.display;
  2183. if (!doc.mode.startState) return true;
  2184. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  2185. if (!state) state = startState(doc.mode);
  2186. else state = copyState(doc.mode, state);
  2187. doc.iter(pos, n, function(line) {
  2188. processLine(cm, line.text, state);
  2189. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2190. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2191. ++pos;
  2192. });
  2193. if (precise) doc.frontier = pos;
  2194. return state;
  2195. }
  2196. // POSITION MEASUREMENT
  2197. function paddingTop(display) {return display.lineSpace.offsetTop;}
  2198. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  2199. function paddingH(display) {
  2200. if (display.cachedPaddingH) return display.cachedPaddingH;
  2201. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2202. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2203. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2204. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2205. return data;
  2206. }
  2207. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2208. function displayWidth(cm) {
  2209. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2210. }
  2211. function displayHeight(cm) {
  2212. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2213. }
  2214. // Ensure the lineView.wrapping.heights array is populated. This is
  2215. // an array of bottom offsets for the lines that make up a drawn
  2216. // line. When lineWrapping is on, there might be more than one
  2217. // height.
  2218. function ensureLineHeights(cm, lineView, rect) {
  2219. var wrapping = cm.options.lineWrapping;
  2220. var curWidth = wrapping && displayWidth(cm);
  2221. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2222. var heights = lineView.measure.heights = [];
  2223. if (wrapping) {
  2224. lineView.measure.width = curWidth;
  2225. var rects = lineView.text.firstChild.getClientRects();
  2226. for (var i = 0; i < rects.length - 1; i++) {
  2227. var cur = rects[i], next = rects[i + 1];
  2228. if (Math.abs(cur.bottom - next.bottom) > 2)
  2229. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2230. }
  2231. }
  2232. heights.push(rect.bottom - rect.top);
  2233. }
  2234. }
  2235. // Find a line map (mapping character offsets to text nodes) and a
  2236. // measurement cache for the given line number. (A line view might
  2237. // contain multiple lines when collapsed ranges are present.)
  2238. function mapFromLineView(lineView, line, lineN) {
  2239. if (lineView.line == line)
  2240. return {map: lineView.measure.map, cache: lineView.measure.cache};
  2241. for (var i = 0; i < lineView.rest.length; i++)
  2242. if (lineView.rest[i] == line)
  2243. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  2244. for (var i = 0; i < lineView.rest.length; i++)
  2245. if (lineNo(lineView.rest[i]) > lineN)
  2246. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  2247. }
  2248. // Render a line into the hidden node display.externalMeasured. Used
  2249. // when measurement is needed for a line that's not in the viewport.
  2250. function updateExternalMeasurement(cm, line) {
  2251. line = visualLine(line);
  2252. var lineN = lineNo(line);
  2253. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2254. view.lineN = lineN;
  2255. var built = view.built = buildLineContent(cm, view);
  2256. view.text = built.pre;
  2257. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2258. return view;
  2259. }
  2260. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2261. // for a given character.
  2262. function measureChar(cm, line, ch, bias) {
  2263. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2264. }
  2265. // Find a line view that corresponds to the given line number.
  2266. function findViewForLine(cm, lineN) {
  2267. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2268. return cm.display.view[findViewIndex(cm, lineN)];
  2269. var ext = cm.display.externalMeasured;
  2270. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2271. return ext;
  2272. }
  2273. // Measurement can be split in two steps, the set-up work that
  2274. // applies to the whole line, and the measurement of the actual
  2275. // character. Functions like coordsChar, that need to do a lot of
  2276. // measurements in a row, can thus ensure that the set-up work is
  2277. // only done once.
  2278. function prepareMeasureForLine(cm, line) {
  2279. var lineN = lineNo(line);
  2280. var view = findViewForLine(cm, lineN);
  2281. if (view && !view.text)
  2282. view = null;
  2283. else if (view && view.changes)
  2284. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2285. if (!view)
  2286. view = updateExternalMeasurement(cm, line);
  2287. var info = mapFromLineView(view, line, lineN);
  2288. return {
  2289. line: line, view: view, rect: null,
  2290. map: info.map, cache: info.cache, before: info.before,
  2291. hasHeights: false
  2292. };
  2293. }
  2294. // Given a prepared measurement object, measures the position of an
  2295. // actual character (or fetches it from the cache).
  2296. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2297. if (prepared.before) ch = -1;
  2298. var key = ch + (bias || ""), found;
  2299. if (prepared.cache.hasOwnProperty(key)) {
  2300. found = prepared.cache[key];
  2301. } else {
  2302. if (!prepared.rect)
  2303. prepared.rect = prepared.view.text.getBoundingClientRect();
  2304. if (!prepared.hasHeights) {
  2305. ensureLineHeights(cm, prepared.view, prepared.rect);
  2306. prepared.hasHeights = true;
  2307. }
  2308. found = measureCharInner(cm, prepared, ch, bias);
  2309. if (!found.bogus) prepared.cache[key] = found;
  2310. }
  2311. return {left: found.left, right: found.right,
  2312. top: varHeight ? found.rtop : found.top,
  2313. bottom: varHeight ? found.rbottom : found.bottom};
  2314. }
  2315. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2316. function nodeAndOffsetInLineMap(map, ch, bias) {
  2317. var node, start, end, collapse;
  2318. // First, search the line map for the text node corresponding to,
  2319. // or closest to, the target character.
  2320. for (var i = 0; i < map.length; i += 3) {
  2321. var mStart = map[i], mEnd = map[i + 1];
  2322. if (ch < mStart) {
  2323. start = 0; end = 1;
  2324. collapse = "left";
  2325. } else if (ch < mEnd) {
  2326. start = ch - mStart;
  2327. end = start + 1;
  2328. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2329. end = mEnd - mStart;
  2330. start = end - 1;
  2331. if (ch >= mEnd) collapse = "right";
  2332. }
  2333. if (start != null) {
  2334. node = map[i + 2];
  2335. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2336. collapse = bias;
  2337. if (bias == "left" && start == 0)
  2338. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2339. node = map[(i -= 3) + 2];
  2340. collapse = "left";
  2341. }
  2342. if (bias == "right" && start == mEnd - mStart)
  2343. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2344. node = map[(i += 3) + 2];
  2345. collapse = "right";
  2346. }
  2347. break;
  2348. }
  2349. }
  2350. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  2351. }
  2352. function measureCharInner(cm, prepared, ch, bias) {
  2353. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2354. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2355. var rect;
  2356. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2357. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2358. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  2359. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  2360. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2361. rect = node.parentNode.getBoundingClientRect();
  2362. } else if (ie && cm.options.lineWrapping) {
  2363. var rects = range(node, start, end).getClientRects();
  2364. if (rects.length)
  2365. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2366. else
  2367. rect = nullRect;
  2368. } else {
  2369. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  2370. }
  2371. if (rect.left || rect.right || start == 0) break;
  2372. end = start;
  2373. start = start - 1;
  2374. collapse = "right";
  2375. }
  2376. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2377. } else { // If it is a widget, simply get the box for the whole widget.
  2378. if (start > 0) collapse = bias = "right";
  2379. var rects;
  2380. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2381. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2382. else
  2383. rect = node.getBoundingClientRect();
  2384. }
  2385. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2386. var rSpan = node.parentNode.getClientRects()[0];
  2387. if (rSpan)
  2388. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  2389. else
  2390. rect = nullRect;
  2391. }
  2392. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2393. var mid = (rtop + rbot) / 2;
  2394. var heights = prepared.view.measure.heights;
  2395. for (var i = 0; i < heights.length - 1; i++)
  2396. if (mid < heights[i]) break;
  2397. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2398. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2399. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2400. top: top, bottom: bot};
  2401. if (!rect.left && !rect.right) result.bogus = true;
  2402. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2403. return result;
  2404. }
  2405. // Work around problem with bounding client rects on ranges being
  2406. // returned incorrectly when zoomed on IE10 and below.
  2407. function maybeUpdateRectForZooming(measure, rect) {
  2408. if (!window.screen || screen.logicalXDPI == null ||
  2409. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2410. return rect;
  2411. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2412. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2413. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2414. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  2415. }
  2416. function clearLineMeasurementCacheFor(lineView) {
  2417. if (lineView.measure) {
  2418. lineView.measure.cache = {};
  2419. lineView.measure.heights = null;
  2420. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2421. lineView.measure.caches[i] = {};
  2422. }
  2423. }
  2424. function clearLineMeasurementCache(cm) {
  2425. cm.display.externalMeasure = null;
  2426. removeChildren(cm.display.lineMeasure);
  2427. for (var i = 0; i < cm.display.view.length; i++)
  2428. clearLineMeasurementCacheFor(cm.display.view[i]);
  2429. }
  2430. function clearCaches(cm) {
  2431. clearLineMeasurementCache(cm);
  2432. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2433. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2434. cm.display.lineNumChars = null;
  2435. }
  2436. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2437. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2438. // Converts a {top, bottom, left, right} box from line-local
  2439. // coordinates into another coordinate system. Context may be one of
  2440. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2441. // or "page".
  2442. function intoCoordSystem(cm, lineObj, rect, context) {
  2443. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2444. var size = widgetHeight(lineObj.widgets[i]);
  2445. rect.top += size; rect.bottom += size;
  2446. }
  2447. if (context == "line") return rect;
  2448. if (!context) context = "local";
  2449. var yOff = heightAtLine(lineObj);
  2450. if (context == "local") yOff += paddingTop(cm.display);
  2451. else yOff -= cm.display.viewOffset;
  2452. if (context == "page" || context == "window") {
  2453. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2454. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2455. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2456. rect.left += xOff; rect.right += xOff;
  2457. }
  2458. rect.top += yOff; rect.bottom += yOff;
  2459. return rect;
  2460. }
  2461. // Coverts a box from "div" coords to another coordinate system.
  2462. // Context may be "window", "page", "div", or "local"/null.
  2463. function fromCoordSystem(cm, coords, context) {
  2464. if (context == "div") return coords;
  2465. var left = coords.left, top = coords.top;
  2466. // First move into "page" coordinate system
  2467. if (context == "page") {
  2468. left -= pageScrollX();
  2469. top -= pageScrollY();
  2470. } else if (context == "local" || !context) {
  2471. var localBox = cm.display.sizer.getBoundingClientRect();
  2472. left += localBox.left;
  2473. top += localBox.top;
  2474. }
  2475. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2476. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  2477. }
  2478. function charCoords(cm, pos, context, lineObj, bias) {
  2479. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2480. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2481. }
  2482. // Returns a box for a given cursor position, which may have an
  2483. // 'other' property containing the position of the secondary cursor
  2484. // on a bidi boundary.
  2485. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2486. lineObj = lineObj || getLine(cm.doc, pos.line);
  2487. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2488. function get(ch, right) {
  2489. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2490. if (right) m.left = m.right; else m.right = m.left;
  2491. return intoCoordSystem(cm, lineObj, m, context);
  2492. }
  2493. function getBidi(ch, partPos) {
  2494. var part = order[partPos], right = part.level % 2;
  2495. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2496. part = order[--partPos];
  2497. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2498. right = true;
  2499. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2500. part = order[++partPos];
  2501. ch = bidiLeft(part) - part.level % 2;
  2502. right = false;
  2503. }
  2504. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2505. return get(ch, right);
  2506. }
  2507. var order = getOrder(lineObj), ch = pos.ch;
  2508. if (!order) return get(ch);
  2509. var partPos = getBidiPartAt(order, ch);
  2510. var val = getBidi(ch, partPos);
  2511. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2512. return val;
  2513. }
  2514. // Used to cheaply estimate the coordinates for a position. Used for
  2515. // intermediate scroll updates.
  2516. function estimateCoords(cm, pos) {
  2517. var left = 0, pos = clipPos(cm.doc, pos);
  2518. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2519. var lineObj = getLine(cm.doc, pos.line);
  2520. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2521. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  2522. }
  2523. // Positions returned by coordsChar contain some extra information.
  2524. // xRel is the relative x position of the input coordinates compared
  2525. // to the found position (so xRel > 0 means the coordinates are to
  2526. // the right of the character position, for example). When outside
  2527. // is true, that means the coordinates lie outside the line's
  2528. // vertical range.
  2529. function PosWithInfo(line, ch, outside, xRel) {
  2530. var pos = Pos(line, ch);
  2531. pos.xRel = xRel;
  2532. if (outside) pos.outside = true;
  2533. return pos;
  2534. }
  2535. // Compute the character position closest to the given coordinates.
  2536. // Input must be lineSpace-local ("div" coordinate system).
  2537. function coordsChar(cm, x, y) {
  2538. var doc = cm.doc;
  2539. y += cm.display.viewOffset;
  2540. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2541. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2542. if (lineN > last)
  2543. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2544. if (x < 0) x = 0;
  2545. var lineObj = getLine(doc, lineN);
  2546. for (;;) {
  2547. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2548. var merged = collapsedSpanAtEnd(lineObj);
  2549. var mergedPos = merged && merged.find(0, true);
  2550. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2551. lineN = lineNo(lineObj = mergedPos.to.line);
  2552. else
  2553. return found;
  2554. }
  2555. }
  2556. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2557. var innerOff = y - heightAtLine(lineObj);
  2558. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2559. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2560. function getX(ch) {
  2561. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2562. wrongLine = true;
  2563. if (innerOff > sp.bottom) return sp.left - adjust;
  2564. else if (innerOff < sp.top) return sp.left + adjust;
  2565. else wrongLine = false;
  2566. return sp.left;
  2567. }
  2568. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2569. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2570. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2571. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2572. // Do a binary search between these bounds.
  2573. for (;;) {
  2574. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2575. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2576. var xDiff = x - (ch == from ? fromX : toX);
  2577. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  2578. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  2579. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2580. return pos;
  2581. }
  2582. var step = Math.ceil(dist / 2), middle = from + step;
  2583. if (bidi) {
  2584. middle = from;
  2585. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2586. }
  2587. var middleX = getX(middle);
  2588. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  2589. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  2590. }
  2591. }
  2592. var measureText;
  2593. // Compute the default text height.
  2594. function textHeight(display) {
  2595. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2596. if (measureText == null) {
  2597. measureText = elt("pre");
  2598. // Measure a bunch of lines, for browsers that compute
  2599. // fractional heights.
  2600. for (var i = 0; i < 49; ++i) {
  2601. measureText.appendChild(document.createTextNode("x"));
  2602. measureText.appendChild(elt("br"));
  2603. }
  2604. measureText.appendChild(document.createTextNode("x"));
  2605. }
  2606. removeChildrenAndAdd(display.measure, measureText);
  2607. var height = measureText.offsetHeight / 50;
  2608. if (height > 3) display.cachedTextHeight = height;
  2609. removeChildren(display.measure);
  2610. return height || 1;
  2611. }
  2612. // Compute the default character width.
  2613. function charWidth(display) {
  2614. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2615. var anchor = elt("span", "xxxxxxxxxx");
  2616. var pre = elt("pre", [anchor]);
  2617. removeChildrenAndAdd(display.measure, pre);
  2618. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2619. if (width > 2) display.cachedCharWidth = width;
  2620. return width || 10;
  2621. }
  2622. // OPERATIONS
  2623. // Operations are used to wrap a series of changes to the editor
  2624. // state in such a way that each change won't have to update the
  2625. // cursor and display (which would be awkward, slow, and
  2626. // error-prone). Instead, display updates are batched and then all
  2627. // combined and executed at once.
  2628. var operationGroup = null;
  2629. var nextOpId = 0;
  2630. // Start a new operation.
  2631. function startOperation(cm) {
  2632. cm.curOp = {
  2633. cm: cm,
  2634. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2635. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2636. forceUpdate: false, // Used to force a redraw
  2637. updateInput: null, // Whether to reset the input textarea
  2638. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2639. changeObjs: null, // Accumulated changes, for firing change events
  2640. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2641. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2642. selectionChanged: false, // Whether the selection needs to be redrawn
  2643. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2644. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2645. scrollToPos: null, // Used to scroll to a specific position
  2646. focus: false,
  2647. id: ++nextOpId // Unique ID
  2648. };
  2649. if (operationGroup) {
  2650. operationGroup.ops.push(cm.curOp);
  2651. } else {
  2652. cm.curOp.ownsGroup = operationGroup = {
  2653. ops: [cm.curOp],
  2654. delayedCallbacks: []
  2655. };
  2656. }
  2657. }
  2658. function fireCallbacksForOps(group) {
  2659. // Calls delayed callbacks and cursorActivity handlers until no
  2660. // new ones appear
  2661. var callbacks = group.delayedCallbacks, i = 0;
  2662. do {
  2663. for (; i < callbacks.length; i++)
  2664. callbacks[i]();
  2665. for (var j = 0; j < group.ops.length; j++) {
  2666. var op = group.ops[j];
  2667. if (op.cursorActivityHandlers)
  2668. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2669. op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);
  2670. }
  2671. } while (i < callbacks.length);
  2672. }
  2673. // Finish an operation, updating the display and signalling delayed events
  2674. function endOperation(cm) {
  2675. var op = cm.curOp, group = op.ownsGroup;
  2676. if (!group) return;
  2677. try { fireCallbacksForOps(group); }
  2678. finally {
  2679. operationGroup = null;
  2680. for (var i = 0; i < group.ops.length; i++)
  2681. group.ops[i].cm.curOp = null;
  2682. endOperations(group);
  2683. }
  2684. }
  2685. // The DOM updates done when an operation finishes are batched so
  2686. // that the minimum number of relayouts are required.
  2687. function endOperations(group) {
  2688. var ops = group.ops;
  2689. for (var i = 0; i < ops.length; i++) // Read DOM
  2690. endOperation_R1(ops[i]);
  2691. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2692. endOperation_W1(ops[i]);
  2693. for (var i = 0; i < ops.length; i++) // Read DOM
  2694. endOperation_R2(ops[i]);
  2695. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2696. endOperation_W2(ops[i]);
  2697. for (var i = 0; i < ops.length; i++) // Read DOM
  2698. endOperation_finish(ops[i]);
  2699. }
  2700. function endOperation_R1(op) {
  2701. var cm = op.cm, display = cm.display;
  2702. maybeClipScrollbars(cm);
  2703. if (op.updateMaxLine) findMaxLine(cm);
  2704. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2705. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2706. op.scrollToPos.to.line >= display.viewTo) ||
  2707. display.maxLineChanged && cm.options.lineWrapping;
  2708. op.update = op.mustUpdate &&
  2709. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  2710. }
  2711. function endOperation_W1(op) {
  2712. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2713. }
  2714. function endOperation_R2(op) {
  2715. var cm = op.cm, display = cm.display;
  2716. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2717. op.barMeasure = measureForScrollbars(cm);
  2718. // If the max line changed since it was last measured, measure it,
  2719. // and ensure the document's width matches it.
  2720. // updateDisplay_W2 will use these properties to do the actual resizing
  2721. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2722. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2723. cm.display.sizerWidth = op.adjustWidthTo;
  2724. op.barMeasure.scrollWidth =
  2725. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2726. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2727. }
  2728. if (op.updatedDisplay || op.selectionChanged)
  2729. op.preparedSelection = display.input.prepareSelection();
  2730. }
  2731. function endOperation_W2(op) {
  2732. var cm = op.cm;
  2733. if (op.adjustWidthTo != null) {
  2734. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2735. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2736. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2737. cm.display.maxLineChanged = false;
  2738. }
  2739. if (op.preparedSelection)
  2740. cm.display.input.showSelection(op.preparedSelection);
  2741. if (op.updatedDisplay)
  2742. setDocumentHeight(cm, op.barMeasure);
  2743. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2744. updateScrollbars(cm, op.barMeasure);
  2745. if (op.selectionChanged) restartBlink(cm);
  2746. if (cm.state.focused && op.updateInput)
  2747. cm.display.input.reset(op.typing);
  2748. if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
  2749. }
  2750. function endOperation_finish(op) {
  2751. var cm = op.cm, display = cm.display, doc = cm.doc;
  2752. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2753. // Abort mouse wheel delta measurement, when scrolling explicitly
  2754. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2755. display.wheelStartX = display.wheelStartY = null;
  2756. // Propagate the scroll position to the actual DOM scroller
  2757. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2758. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2759. display.scrollbars.setScrollTop(doc.scrollTop);
  2760. display.scroller.scrollTop = doc.scrollTop;
  2761. }
  2762. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2763. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
  2764. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2765. display.scroller.scrollLeft = doc.scrollLeft;
  2766. alignHorizontally(cm);
  2767. }
  2768. // If we need to scroll a specific position into view, do so.
  2769. if (op.scrollToPos) {
  2770. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2771. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2772. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2773. }
  2774. // Fire events for markers that are hidden/unidden by editing or
  2775. // undoing
  2776. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2777. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2778. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2779. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2780. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2781. if (display.wrapper.offsetHeight)
  2782. doc.scrollTop = cm.display.scroller.scrollTop;
  2783. // Fire change events, and delayed event handlers
  2784. if (op.changeObjs)
  2785. signal(cm, "changes", cm, op.changeObjs);
  2786. if (op.update)
  2787. op.update.finish();
  2788. }
  2789. // Run the given function in an operation
  2790. function runInOp(cm, f) {
  2791. if (cm.curOp) return f();
  2792. startOperation(cm);
  2793. try { return f(); }
  2794. finally { endOperation(cm); }
  2795. }
  2796. // Wraps a function in an operation. Returns the wrapped function.
  2797. function operation(cm, f) {
  2798. return function() {
  2799. if (cm.curOp) return f.apply(cm, arguments);
  2800. startOperation(cm);
  2801. try { return f.apply(cm, arguments); }
  2802. finally { endOperation(cm); }
  2803. };
  2804. }
  2805. // Used to add methods to editor and doc instances, wrapping them in
  2806. // operations.
  2807. function methodOp(f) {
  2808. return function() {
  2809. if (this.curOp) return f.apply(this, arguments);
  2810. startOperation(this);
  2811. try { return f.apply(this, arguments); }
  2812. finally { endOperation(this); }
  2813. };
  2814. }
  2815. function docMethodOp(f) {
  2816. return function() {
  2817. var cm = this.cm;
  2818. if (!cm || cm.curOp) return f.apply(this, arguments);
  2819. startOperation(cm);
  2820. try { return f.apply(this, arguments); }
  2821. finally { endOperation(cm); }
  2822. };
  2823. }
  2824. // VIEW TRACKING
  2825. // These objects are used to represent the visible (currently drawn)
  2826. // part of the document. A LineView may correspond to multiple
  2827. // logical lines, if those are connected by collapsed ranges.
  2828. function LineView(doc, line, lineN) {
  2829. // The starting line
  2830. this.line = line;
  2831. // Continuing lines, if any
  2832. this.rest = visualLineContinued(line);
  2833. // Number of logical lines in this visual line
  2834. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2835. this.node = this.text = null;
  2836. this.hidden = lineIsHidden(doc, line);
  2837. }
  2838. // Create a range of LineView objects for the given lines.
  2839. function buildViewArray(cm, from, to) {
  2840. var array = [], nextPos;
  2841. for (var pos = from; pos < to; pos = nextPos) {
  2842. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2843. nextPos = pos + view.size;
  2844. array.push(view);
  2845. }
  2846. return array;
  2847. }
  2848. // Updates the display.view data structure for a given change to the
  2849. // document. From and to are in pre-change coordinates. Lendiff is
  2850. // the amount of lines added or subtracted by the change. This is
  2851. // used for changes that span multiple lines, or change the way
  2852. // lines are divided into visual lines. regLineChange (below)
  2853. // registers single-line changes.
  2854. function regChange(cm, from, to, lendiff) {
  2855. if (from == null) from = cm.doc.first;
  2856. if (to == null) to = cm.doc.first + cm.doc.size;
  2857. if (!lendiff) lendiff = 0;
  2858. var display = cm.display;
  2859. if (lendiff && to < display.viewTo &&
  2860. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2861. display.updateLineNumbers = from;
  2862. cm.curOp.viewChanged = true;
  2863. if (from >= display.viewTo) { // Change after
  2864. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2865. resetView(cm);
  2866. } else if (to <= display.viewFrom) { // Change before
  2867. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2868. resetView(cm);
  2869. } else {
  2870. display.viewFrom += lendiff;
  2871. display.viewTo += lendiff;
  2872. }
  2873. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2874. resetView(cm);
  2875. } else if (from <= display.viewFrom) { // Top overlap
  2876. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2877. if (cut) {
  2878. display.view = display.view.slice(cut.index);
  2879. display.viewFrom = cut.lineN;
  2880. display.viewTo += lendiff;
  2881. } else {
  2882. resetView(cm);
  2883. }
  2884. } else if (to >= display.viewTo) { // Bottom overlap
  2885. var cut = viewCuttingPoint(cm, from, from, -1);
  2886. if (cut) {
  2887. display.view = display.view.slice(0, cut.index);
  2888. display.viewTo = cut.lineN;
  2889. } else {
  2890. resetView(cm);
  2891. }
  2892. } else { // Gap in the middle
  2893. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2894. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2895. if (cutTop && cutBot) {
  2896. display.view = display.view.slice(0, cutTop.index)
  2897. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2898. .concat(display.view.slice(cutBot.index));
  2899. display.viewTo += lendiff;
  2900. } else {
  2901. resetView(cm);
  2902. }
  2903. }
  2904. var ext = display.externalMeasured;
  2905. if (ext) {
  2906. if (to < ext.lineN)
  2907. ext.lineN += lendiff;
  2908. else if (from < ext.lineN + ext.size)
  2909. display.externalMeasured = null;
  2910. }
  2911. }
  2912. // Register a change to a single line. Type must be one of "text",
  2913. // "gutter", "class", "widget"
  2914. function regLineChange(cm, line, type) {
  2915. cm.curOp.viewChanged = true;
  2916. var display = cm.display, ext = cm.display.externalMeasured;
  2917. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2918. display.externalMeasured = null;
  2919. if (line < display.viewFrom || line >= display.viewTo) return;
  2920. var lineView = display.view[findViewIndex(cm, line)];
  2921. if (lineView.node == null) return;
  2922. var arr = lineView.changes || (lineView.changes = []);
  2923. if (indexOf(arr, type) == -1) arr.push(type);
  2924. }
  2925. // Clear the view.
  2926. function resetView(cm) {
  2927. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2928. cm.display.view = [];
  2929. cm.display.viewOffset = 0;
  2930. }
  2931. // Find the view element corresponding to a given line. Return null
  2932. // when the line isn't visible.
  2933. function findViewIndex(cm, n) {
  2934. if (n >= cm.display.viewTo) return null;
  2935. n -= cm.display.viewFrom;
  2936. if (n < 0) return null;
  2937. var view = cm.display.view;
  2938. for (var i = 0; i < view.length; i++) {
  2939. n -= view[i].size;
  2940. if (n < 0) return i;
  2941. }
  2942. }
  2943. function viewCuttingPoint(cm, oldN, newN, dir) {
  2944. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2945. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2946. return {index: index, lineN: newN};
  2947. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2948. n += view[i].size;
  2949. if (n != oldN) {
  2950. if (dir > 0) {
  2951. if (index == view.length - 1) return null;
  2952. diff = (n + view[index].size) - oldN;
  2953. index++;
  2954. } else {
  2955. diff = n - oldN;
  2956. }
  2957. oldN += diff; newN += diff;
  2958. }
  2959. while (visualLineNo(cm.doc, newN) != newN) {
  2960. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  2961. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2962. index += dir;
  2963. }
  2964. return {index: index, lineN: newN};
  2965. }
  2966. // Force the view to cover a given range, adding empty view element
  2967. // or clipping off existing ones as needed.
  2968. function adjustView(cm, from, to) {
  2969. var display = cm.display, view = display.view;
  2970. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2971. display.view = buildViewArray(cm, from, to);
  2972. display.viewFrom = from;
  2973. } else {
  2974. if (display.viewFrom > from)
  2975. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  2976. else if (display.viewFrom < from)
  2977. display.view = display.view.slice(findViewIndex(cm, from));
  2978. display.viewFrom = from;
  2979. if (display.viewTo < to)
  2980. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  2981. else if (display.viewTo > to)
  2982. display.view = display.view.slice(0, findViewIndex(cm, to));
  2983. }
  2984. display.viewTo = to;
  2985. }
  2986. // Count the number of lines in the view whose DOM representation is
  2987. // out of date (or nonexistent).
  2988. function countDirtyView(cm) {
  2989. var view = cm.display.view, dirty = 0;
  2990. for (var i = 0; i < view.length; i++) {
  2991. var lineView = view[i];
  2992. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  2993. }
  2994. return dirty;
  2995. }
  2996. // EVENT HANDLERS
  2997. // Attach the necessary event handlers when initializing the editor
  2998. function registerEventHandlers(cm) {
  2999. var d = cm.display;
  3000. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  3001. // Older IE's will not fire a second mousedown for a double click
  3002. if (ie && ie_version < 11)
  3003. on(d.scroller, "dblclick", operation(cm, function(e) {
  3004. if (signalDOMEvent(cm, e)) return;
  3005. var pos = posFromMouse(cm, e);
  3006. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  3007. e_preventDefault(e);
  3008. var word = cm.findWordAt(pos);
  3009. extendSelection(cm.doc, word.anchor, word.head);
  3010. }));
  3011. else
  3012. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  3013. // Some browsers fire contextmenu *after* opening the menu, at
  3014. // which point we can't mess with it anymore. Context menu is
  3015. // handled in onMouseDown for these browsers.
  3016. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  3017. // Used to suppress mouse event handling when a touch happens
  3018. var touchFinished, prevTouch = {end: 0};
  3019. function finishTouch() {
  3020. if (d.activeTouch) {
  3021. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  3022. prevTouch = d.activeTouch;
  3023. prevTouch.end = +new Date;
  3024. }
  3025. };
  3026. function isMouseLikeTouchEvent(e) {
  3027. if (e.touches.length != 1) return false;
  3028. var touch = e.touches[0];
  3029. return touch.radiusX <= 1 && touch.radiusY <= 1;
  3030. }
  3031. function farAway(touch, other) {
  3032. if (other.left == null) return true;
  3033. var dx = other.left - touch.left, dy = other.top - touch.top;
  3034. return dx * dx + dy * dy > 20 * 20;
  3035. }
  3036. on(d.scroller, "touchstart", function(e) {
  3037. if (!isMouseLikeTouchEvent(e)) {
  3038. clearTimeout(touchFinished);
  3039. var now = +new Date;
  3040. d.activeTouch = {start: now, moved: false,
  3041. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  3042. if (e.touches.length == 1) {
  3043. d.activeTouch.left = e.touches[0].pageX;
  3044. d.activeTouch.top = e.touches[0].pageY;
  3045. }
  3046. }
  3047. });
  3048. on(d.scroller, "touchmove", function() {
  3049. if (d.activeTouch) d.activeTouch.moved = true;
  3050. });
  3051. on(d.scroller, "touchend", function(e) {
  3052. var touch = d.activeTouch;
  3053. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3054. !touch.moved && new Date - touch.start < 300) {
  3055. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3056. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3057. range = new Range(pos, pos);
  3058. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3059. range = cm.findWordAt(pos);
  3060. else // Triple tap
  3061. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3062. cm.setSelection(range.anchor, range.head);
  3063. cm.focus();
  3064. e_preventDefault(e);
  3065. }
  3066. finishTouch();
  3067. });
  3068. on(d.scroller, "touchcancel", finishTouch);
  3069. // Sync scrolling between fake scrollbars and real scrollable
  3070. // area, ensure viewport is updated when scrolling.
  3071. on(d.scroller, "scroll", function() {
  3072. if (d.scroller.clientHeight) {
  3073. setScrollTop(cm, d.scroller.scrollTop);
  3074. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3075. signal(cm, "scroll", cm);
  3076. }
  3077. });
  3078. // Listen to wheel events in order to try and update the viewport on time.
  3079. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  3080. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  3081. // Prevent wrapper from ever scrolling
  3082. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3083. d.dragFunctions = {
  3084. simple: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  3085. start: function(e){onDragStart(cm, e);},
  3086. drop: operation(cm, onDrop)
  3087. };
  3088. var inp = d.input.getField();
  3089. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  3090. on(inp, "keydown", operation(cm, onKeyDown));
  3091. on(inp, "keypress", operation(cm, onKeyPress));
  3092. on(inp, "focus", bind(onFocus, cm));
  3093. on(inp, "blur", bind(onBlur, cm));
  3094. }
  3095. function dragDropChanged(cm, value, old) {
  3096. var wasOn = old && old != CodeMirror.Init;
  3097. if (!value != !wasOn) {
  3098. var funcs = cm.display.dragFunctions;
  3099. var toggle = value ? on : off;
  3100. toggle(cm.display.scroller, "dragstart", funcs.start);
  3101. toggle(cm.display.scroller, "dragenter", funcs.simple);
  3102. toggle(cm.display.scroller, "dragover", funcs.simple);
  3103. toggle(cm.display.scroller, "drop", funcs.drop);
  3104. }
  3105. }
  3106. // Called when the window resizes
  3107. function onResize(cm) {
  3108. var d = cm.display;
  3109. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3110. return;
  3111. // Might be a text scaling operation, clear size caches.
  3112. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3113. d.scrollbarsClipped = false;
  3114. cm.setSize();
  3115. }
  3116. // MOUSE EVENTS
  3117. // Return true when the given mouse event happened in a widget
  3118. function eventInWidget(display, e) {
  3119. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3120. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3121. (n.parentNode == display.sizer && n != display.mover))
  3122. return true;
  3123. }
  3124. }
  3125. // Given a mouse event, find the corresponding position. If liberal
  3126. // is false, it checks whether a gutter or scrollbar was clicked,
  3127. // and returns null if it was. forRect is used by rectangular
  3128. // selections, and tries to estimate a character position even for
  3129. // coordinates beyond the right of the text.
  3130. function posFromMouse(cm, e, liberal, forRect) {
  3131. var display = cm.display;
  3132. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3133. var x, y, space = display.lineSpace.getBoundingClientRect();
  3134. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3135. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3136. catch (e) { return null; }
  3137. var coords = coordsChar(cm, x, y), line;
  3138. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3139. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3140. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3141. }
  3142. return coords;
  3143. }
  3144. // A mouse down can be a single click, double click, triple click,
  3145. // start of selection drag, start of text drag, new cursor
  3146. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3147. // middle-click-paste. Or it might be a click on something we should
  3148. // not interfere with, such as a scrollbar or widget.
  3149. function onMouseDown(e) {
  3150. var cm = this, display = cm.display;
  3151. if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
  3152. display.shift = e.shiftKey;
  3153. if (eventInWidget(display, e)) {
  3154. if (!webkit) {
  3155. // Briefly turn off draggability, to allow widgets to do
  3156. // normal dragging things.
  3157. display.scroller.draggable = false;
  3158. setTimeout(function(){display.scroller.draggable = true;}, 100);
  3159. }
  3160. return;
  3161. }
  3162. if (clickInGutter(cm, e)) return;
  3163. var start = posFromMouse(cm, e);
  3164. window.focus();
  3165. switch (e_button(e)) {
  3166. case 1:
  3167. if (start)
  3168. leftButtonDown(cm, e, start);
  3169. else if (e_target(e) == display.scroller)
  3170. e_preventDefault(e);
  3171. break;
  3172. case 2:
  3173. if (webkit) cm.state.lastMiddleDown = +new Date;
  3174. if (start) extendSelection(cm.doc, start);
  3175. setTimeout(function() {display.input.focus();}, 20);
  3176. e_preventDefault(e);
  3177. break;
  3178. case 3:
  3179. if (captureRightClick) onContextMenu(cm, e);
  3180. else delayBlurEvent(cm);
  3181. break;
  3182. }
  3183. }
  3184. var lastClick, lastDoubleClick;
  3185. function leftButtonDown(cm, e, start) {
  3186. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3187. else cm.curOp.focus = activeElt();
  3188. var now = +new Date, type;
  3189. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3190. type = "triple";
  3191. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3192. type = "double";
  3193. lastDoubleClick = {time: now, pos: start};
  3194. } else {
  3195. type = "single";
  3196. lastClick = {time: now, pos: start};
  3197. }
  3198. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3199. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
  3200. type == "single" && (contained = sel.contains(start)) > -1 &&
  3201. !sel.ranges[contained].empty())
  3202. leftButtonStartDrag(cm, e, start, modifier);
  3203. else
  3204. leftButtonSelect(cm, e, start, type, modifier);
  3205. }
  3206. // Start a text drag. When it ends, see if any dragging actually
  3207. // happen, and treat as a click if it didn't.
  3208. function leftButtonStartDrag(cm, e, start, modifier) {
  3209. var display = cm.display, startTime = +new Date;
  3210. var dragEnd = operation(cm, function(e2) {
  3211. if (webkit) display.scroller.draggable = false;
  3212. cm.state.draggingText = false;
  3213. off(document, "mouseup", dragEnd);
  3214. off(display.scroller, "drop", dragEnd);
  3215. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3216. e_preventDefault(e2);
  3217. if (!modifier && +new Date - 200 < startTime)
  3218. extendSelection(cm.doc, start);
  3219. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  3220. if (webkit || ie && ie_version == 9)
  3221. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  3222. else
  3223. display.input.focus();
  3224. }
  3225. });
  3226. // Let the drag handler handle this.
  3227. if (webkit) display.scroller.draggable = true;
  3228. cm.state.draggingText = dragEnd;
  3229. // IE's approach to draggable
  3230. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3231. on(document, "mouseup", dragEnd);
  3232. on(display.scroller, "drop", dragEnd);
  3233. }
  3234. // Normal selection, as opposed to text dragging.
  3235. function leftButtonSelect(cm, e, start, type, addNew) {
  3236. var display = cm.display, doc = cm.doc;
  3237. e_preventDefault(e);
  3238. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3239. if (addNew && !e.shiftKey) {
  3240. ourIndex = doc.sel.contains(start);
  3241. if (ourIndex > -1)
  3242. ourRange = ranges[ourIndex];
  3243. else
  3244. ourRange = new Range(start, start);
  3245. } else {
  3246. ourRange = doc.sel.primary();
  3247. ourIndex = doc.sel.primIndex;
  3248. }
  3249. if (e.altKey) {
  3250. type = "rect";
  3251. if (!addNew) ourRange = new Range(start, start);
  3252. start = posFromMouse(cm, e, true, true);
  3253. ourIndex = -1;
  3254. } else if (type == "double") {
  3255. var word = cm.findWordAt(start);
  3256. if (cm.display.shift || doc.extend)
  3257. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3258. else
  3259. ourRange = word;
  3260. } else if (type == "triple") {
  3261. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3262. if (cm.display.shift || doc.extend)
  3263. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3264. else
  3265. ourRange = line;
  3266. } else {
  3267. ourRange = extendRange(doc, ourRange, start);
  3268. }
  3269. if (!addNew) {
  3270. ourIndex = 0;
  3271. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3272. startSel = doc.sel;
  3273. } else if (ourIndex == -1) {
  3274. ourIndex = ranges.length;
  3275. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3276. {scroll: false, origin: "*mouse"});
  3277. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  3278. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
  3279. startSel = doc.sel;
  3280. } else {
  3281. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3282. }
  3283. var lastPos = start;
  3284. function extendTo(pos) {
  3285. if (cmp(lastPos, pos) == 0) return;
  3286. lastPos = pos;
  3287. if (type == "rect") {
  3288. var ranges = [], tabSize = cm.options.tabSize;
  3289. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3290. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3291. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3292. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3293. line <= end; line++) {
  3294. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3295. if (left == right)
  3296. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3297. else if (text.length > leftPos)
  3298. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3299. }
  3300. if (!ranges.length) ranges.push(new Range(start, start));
  3301. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3302. {origin: "*mouse", scroll: false});
  3303. cm.scrollIntoView(pos);
  3304. } else {
  3305. var oldRange = ourRange;
  3306. var anchor = oldRange.anchor, head = pos;
  3307. if (type != "single") {
  3308. if (type == "double")
  3309. var range = cm.findWordAt(pos);
  3310. else
  3311. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3312. if (cmp(range.anchor, anchor) > 0) {
  3313. head = range.head;
  3314. anchor = minPos(oldRange.from(), range.anchor);
  3315. } else {
  3316. head = range.anchor;
  3317. anchor = maxPos(oldRange.to(), range.head);
  3318. }
  3319. }
  3320. var ranges = startSel.ranges.slice(0);
  3321. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3322. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3323. }
  3324. }
  3325. var editorSize = display.wrapper.getBoundingClientRect();
  3326. // Used to ensure timeout re-tries don't fire when another extend
  3327. // happened in the meantime (clearTimeout isn't reliable -- at
  3328. // least on Chrome, the timeouts still happen even when cleared,
  3329. // if the clear happens after their scheduled firing time).
  3330. var counter = 0;
  3331. function extend(e) {
  3332. var curCount = ++counter;
  3333. var cur = posFromMouse(cm, e, true, type == "rect");
  3334. if (!cur) return;
  3335. if (cmp(cur, lastPos) != 0) {
  3336. cm.curOp.focus = activeElt();
  3337. extendTo(cur);
  3338. var visible = visibleLines(display, doc);
  3339. if (cur.line >= visible.to || cur.line < visible.from)
  3340. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  3341. } else {
  3342. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3343. if (outside) setTimeout(operation(cm, function() {
  3344. if (counter != curCount) return;
  3345. display.scroller.scrollTop += outside;
  3346. extend(e);
  3347. }), 50);
  3348. }
  3349. }
  3350. function done(e) {
  3351. counter = Infinity;
  3352. e_preventDefault(e);
  3353. display.input.focus();
  3354. off(document, "mousemove", move);
  3355. off(document, "mouseup", up);
  3356. doc.history.lastSelOrigin = null;
  3357. }
  3358. var move = operation(cm, function(e) {
  3359. if (!e_button(e)) done(e);
  3360. else extend(e);
  3361. });
  3362. var up = operation(cm, done);
  3363. on(document, "mousemove", move);
  3364. on(document, "mouseup", up);
  3365. }
  3366. // Determines whether an event happened in the gutter, and fires the
  3367. // handlers for the corresponding event.
  3368. function gutterEvent(cm, e, type, prevent, signalfn) {
  3369. try { var mX = e.clientX, mY = e.clientY; }
  3370. catch(e) { return false; }
  3371. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3372. if (prevent) e_preventDefault(e);
  3373. var display = cm.display;
  3374. var lineBox = display.lineDiv.getBoundingClientRect();
  3375. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3376. mY -= lineBox.top - display.viewOffset;
  3377. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3378. var g = display.gutters.childNodes[i];
  3379. if (g && g.getBoundingClientRect().right >= mX) {
  3380. var line = lineAtHeight(cm.doc, mY);
  3381. var gutter = cm.options.gutters[i];
  3382. signalfn(cm, type, cm, line, gutter, e);
  3383. return e_defaultPrevented(e);
  3384. }
  3385. }
  3386. }
  3387. function clickInGutter(cm, e) {
  3388. return gutterEvent(cm, e, "gutterClick", true, signalLater);
  3389. }
  3390. // Kludge to work around strange IE behavior where it'll sometimes
  3391. // re-fire a series of drag-related events right after the drop (#1551)
  3392. var lastDrop = 0;
  3393. function onDrop(e) {
  3394. var cm = this;
  3395. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3396. return;
  3397. e_preventDefault(e);
  3398. if (ie) lastDrop = +new Date;
  3399. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3400. if (!pos || isReadOnly(cm)) return;
  3401. // Might be a file drop, in which case we simply extract the text
  3402. // and insert it.
  3403. if (files && files.length && window.FileReader && window.File) {
  3404. var n = files.length, text = Array(n), read = 0;
  3405. var loadFile = function(file, i) {
  3406. var reader = new FileReader;
  3407. reader.onload = operation(cm, function() {
  3408. text[i] = reader.result;
  3409. if (++read == n) {
  3410. pos = clipPos(cm.doc, pos);
  3411. var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
  3412. makeChange(cm.doc, change);
  3413. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3414. }
  3415. });
  3416. reader.readAsText(file);
  3417. };
  3418. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3419. } else { // Normal drop
  3420. // Don't do a replace if the drop happened inside of the selected text.
  3421. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3422. cm.state.draggingText(e);
  3423. // Ensure the editor is re-focused
  3424. setTimeout(function() {cm.display.input.focus();}, 20);
  3425. return;
  3426. }
  3427. try {
  3428. var text = e.dataTransfer.getData("Text");
  3429. if (text) {
  3430. if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
  3431. var selected = cm.listSelections();
  3432. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3433. if (selected) for (var i = 0; i < selected.length; ++i)
  3434. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3435. cm.replaceSelection(text, "around", "paste");
  3436. cm.display.input.focus();
  3437. }
  3438. }
  3439. catch(e){}
  3440. }
  3441. }
  3442. function onDragStart(cm, e) {
  3443. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3444. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3445. e.dataTransfer.setData("Text", cm.getSelection());
  3446. // Use dummy image instead of default browsers image.
  3447. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3448. if (e.dataTransfer.setDragImage && !safari) {
  3449. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3450. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3451. if (presto) {
  3452. img.width = img.height = 1;
  3453. cm.display.wrapper.appendChild(img);
  3454. // Force a relayout, or Opera won't use our image for some obscure reason
  3455. img._top = img.offsetTop;
  3456. }
  3457. e.dataTransfer.setDragImage(img, 0, 0);
  3458. if (presto) img.parentNode.removeChild(img);
  3459. }
  3460. }
  3461. // SCROLL EVENTS
  3462. // Sync the scrollable area and scrollbars, ensure the viewport
  3463. // covers the visible area.
  3464. function setScrollTop(cm, val) {
  3465. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3466. cm.doc.scrollTop = val;
  3467. if (!gecko) updateDisplaySimple(cm, {top: val});
  3468. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3469. cm.display.scrollbars.setScrollTop(val);
  3470. if (gecko) updateDisplaySimple(cm);
  3471. startWorker(cm, 100);
  3472. }
  3473. // Sync scroller and scrollbar, ensure the gutter elements are
  3474. // aligned.
  3475. function setScrollLeft(cm, val, isScroller) {
  3476. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3477. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3478. cm.doc.scrollLeft = val;
  3479. alignHorizontally(cm);
  3480. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3481. cm.display.scrollbars.setScrollLeft(val);
  3482. }
  3483. // Since the delta values reported on mouse wheel events are
  3484. // unstandardized between browsers and even browser versions, and
  3485. // generally horribly unpredictable, this code starts by measuring
  3486. // the scroll effect that the first few mouse wheel events have,
  3487. // and, from that, detects the way it can convert deltas to pixel
  3488. // offsets afterwards.
  3489. //
  3490. // The reason we want to know the amount a wheel event will scroll
  3491. // is that it gives us a chance to update the display before the
  3492. // actual scrolling happens, reducing flickering.
  3493. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3494. // Fill in a browser-detected starting value on browsers where we
  3495. // know one. These don't have to be accurate -- the result of them
  3496. // being wrong would just be a slight flicker on the first wheel
  3497. // scroll (if it is large enough).
  3498. if (ie) wheelPixelsPerUnit = -.53;
  3499. else if (gecko) wheelPixelsPerUnit = 15;
  3500. else if (chrome) wheelPixelsPerUnit = -.7;
  3501. else if (safari) wheelPixelsPerUnit = -1/3;
  3502. var wheelEventDelta = function(e) {
  3503. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3504. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3505. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3506. else if (dy == null) dy = e.wheelDelta;
  3507. return {x: dx, y: dy};
  3508. };
  3509. CodeMirror.wheelEventPixels = function(e) {
  3510. var delta = wheelEventDelta(e);
  3511. delta.x *= wheelPixelsPerUnit;
  3512. delta.y *= wheelPixelsPerUnit;
  3513. return delta;
  3514. };
  3515. function onScrollWheel(cm, e) {
  3516. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3517. var display = cm.display, scroll = display.scroller;
  3518. // Quit if there's nothing to scroll here
  3519. if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
  3520. dy && scroll.scrollHeight > scroll.clientHeight)) return;
  3521. // Webkit browsers on OS X abort momentum scrolls when the target
  3522. // of the scroll event is removed from the scrollable element.
  3523. // This hack (see related code in patchDisplay) makes sure the
  3524. // element is kept around.
  3525. if (dy && mac && webkit) {
  3526. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3527. for (var i = 0; i < view.length; i++) {
  3528. if (view[i].node == cur) {
  3529. cm.display.currentWheelTarget = cur;
  3530. break outer;
  3531. }
  3532. }
  3533. }
  3534. }
  3535. // On some browsers, horizontal scrolling will cause redraws to
  3536. // happen before the gutter has been realigned, causing it to
  3537. // wriggle around in a most unseemly way. When we have an
  3538. // estimated pixels/delta value, we just handle horizontal
  3539. // scrolling entirely here. It'll be slightly off from native, but
  3540. // better than glitching out.
  3541. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3542. if (dy)
  3543. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3544. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3545. e_preventDefault(e);
  3546. display.wheelStartX = null; // Abort measurement, if in progress
  3547. return;
  3548. }
  3549. // 'Project' the visible viewport to cover the area that is being
  3550. // scrolled into view (if we know enough to estimate it).
  3551. if (dy && wheelPixelsPerUnit != null) {
  3552. var pixels = dy * wheelPixelsPerUnit;
  3553. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3554. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3555. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3556. updateDisplaySimple(cm, {top: top, bottom: bot});
  3557. }
  3558. if (wheelSamples < 20) {
  3559. if (display.wheelStartX == null) {
  3560. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3561. display.wheelDX = dx; display.wheelDY = dy;
  3562. setTimeout(function() {
  3563. if (display.wheelStartX == null) return;
  3564. var movedX = scroll.scrollLeft - display.wheelStartX;
  3565. var movedY = scroll.scrollTop - display.wheelStartY;
  3566. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3567. (movedX && display.wheelDX && movedX / display.wheelDX);
  3568. display.wheelStartX = display.wheelStartY = null;
  3569. if (!sample) return;
  3570. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3571. ++wheelSamples;
  3572. }, 200);
  3573. } else {
  3574. display.wheelDX += dx; display.wheelDY += dy;
  3575. }
  3576. }
  3577. }
  3578. // KEY EVENTS
  3579. // Run a handler that was bound to a key.
  3580. function doHandleBinding(cm, bound, dropShift) {
  3581. if (typeof bound == "string") {
  3582. bound = commands[bound];
  3583. if (!bound) return false;
  3584. }
  3585. // Ensure previous input has been read, so that the handler sees a
  3586. // consistent view of the document
  3587. cm.display.input.ensurePolled();
  3588. var prevShift = cm.display.shift, done = false;
  3589. try {
  3590. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  3591. if (dropShift) cm.display.shift = false;
  3592. done = bound(cm) != Pass;
  3593. } finally {
  3594. cm.display.shift = prevShift;
  3595. cm.state.suppressEdits = false;
  3596. }
  3597. return done;
  3598. }
  3599. function lookupKeyForEditor(cm, name, handle) {
  3600. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3601. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3602. if (result) return result;
  3603. }
  3604. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3605. || lookupKey(name, cm.options.keyMap, handle, cm);
  3606. }
  3607. var stopSeq = new Delayed;
  3608. function dispatchKey(cm, name, e, handle) {
  3609. var seq = cm.state.keySeq;
  3610. if (seq) {
  3611. if (isModifierKey(name)) return "handled";
  3612. stopSeq.set(50, function() {
  3613. if (cm.state.keySeq == seq) {
  3614. cm.state.keySeq = null;
  3615. cm.display.input.reset();
  3616. }
  3617. });
  3618. name = seq + " " + name;
  3619. }
  3620. var result = lookupKeyForEditor(cm, name, handle);
  3621. if (result == "multi")
  3622. cm.state.keySeq = name;
  3623. if (result == "handled")
  3624. signalLater(cm, "keyHandled", cm, name, e);
  3625. if (result == "handled" || result == "multi") {
  3626. e_preventDefault(e);
  3627. restartBlink(cm);
  3628. }
  3629. if (seq && !result && /\'$/.test(name)) {
  3630. e_preventDefault(e);
  3631. return true;
  3632. }
  3633. return !!result;
  3634. }
  3635. // Handle a key from the keydown event.
  3636. function handleKeyBinding(cm, e) {
  3637. var name = keyName(e, true);
  3638. if (!name) return false;
  3639. if (e.shiftKey && !cm.state.keySeq) {
  3640. // First try to resolve full name (including 'Shift-'). Failing
  3641. // that, see if there is a cursor-motion command (starting with
  3642. // 'go') bound to the keyname without 'Shift-'.
  3643. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3644. || dispatchKey(cm, name, e, function(b) {
  3645. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3646. return doHandleBinding(cm, b);
  3647. });
  3648. } else {
  3649. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3650. }
  3651. }
  3652. // Handle a key from the keypress event
  3653. function handleCharBinding(cm, e, ch) {
  3654. return dispatchKey(cm, "'" + ch + "'", e,
  3655. function(b) { return doHandleBinding(cm, b, true); });
  3656. }
  3657. var lastStoppedKey = null;
  3658. function onKeyDown(e) {
  3659. var cm = this;
  3660. cm.curOp.focus = activeElt();
  3661. if (signalDOMEvent(cm, e)) return;
  3662. // IE does strange things with escape.
  3663. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3664. var code = e.keyCode;
  3665. cm.display.shift = code == 16 || e.shiftKey;
  3666. var handled = handleKeyBinding(cm, e);
  3667. if (presto) {
  3668. lastStoppedKey = handled ? code : null;
  3669. // Opera has no cut event... we try to at least catch the key combo
  3670. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3671. cm.replaceSelection("", null, "cut");
  3672. }
  3673. // Turn mouse into crosshair when Alt is held on Mac.
  3674. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3675. showCrossHair(cm);
  3676. }
  3677. function showCrossHair(cm) {
  3678. var lineDiv = cm.display.lineDiv;
  3679. addClass(lineDiv, "CodeMirror-crosshair");
  3680. function up(e) {
  3681. if (e.keyCode == 18 || !e.altKey) {
  3682. rmClass(lineDiv, "CodeMirror-crosshair");
  3683. off(document, "keyup", up);
  3684. off(document, "mouseover", up);
  3685. }
  3686. }
  3687. on(document, "keyup", up);
  3688. on(document, "mouseover", up);
  3689. }
  3690. function onKeyUp(e) {
  3691. if (e.keyCode == 16) this.doc.sel.shift = false;
  3692. signalDOMEvent(this, e);
  3693. }
  3694. function onKeyPress(e) {
  3695. var cm = this;
  3696. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3697. var keyCode = e.keyCode, charCode = e.charCode;
  3698. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3699. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3700. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3701. if (handleCharBinding(cm, e, ch)) return;
  3702. cm.display.input.onKeyPress(e);
  3703. }
  3704. // FOCUS/BLUR EVENTS
  3705. function delayBlurEvent(cm) {
  3706. cm.state.delayingBlurEvent = true;
  3707. setTimeout(function() {
  3708. if (cm.state.delayingBlurEvent) {
  3709. cm.state.delayingBlurEvent = false;
  3710. onBlur(cm);
  3711. }
  3712. }, 100);
  3713. }
  3714. function onFocus(cm) {
  3715. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  3716. if (cm.options.readOnly == "nocursor") return;
  3717. if (!cm.state.focused) {
  3718. signal(cm, "focus", cm);
  3719. cm.state.focused = true;
  3720. addClass(cm.display.wrapper, "CodeMirror-focused");
  3721. // This test prevents this from firing when a context
  3722. // menu is closed (since the input reset would kill the
  3723. // select-all detection hack)
  3724. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3725. cm.display.input.reset();
  3726. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  3727. }
  3728. cm.display.input.receivedFocus();
  3729. }
  3730. restartBlink(cm);
  3731. }
  3732. function onBlur(cm) {
  3733. if (cm.state.delayingBlurEvent) return;
  3734. if (cm.state.focused) {
  3735. signal(cm, "blur", cm);
  3736. cm.state.focused = false;
  3737. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3738. }
  3739. clearInterval(cm.display.blinker);
  3740. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3741. }
  3742. // CONTEXT MENU HANDLING
  3743. // To make the context menu work, we need to briefly unhide the
  3744. // textarea (making it as unobtrusive as possible) to let the
  3745. // right-click take effect on it.
  3746. function onContextMenu(cm, e) {
  3747. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3748. cm.display.input.onContextMenu(e);
  3749. }
  3750. function contextMenuInGutter(cm, e) {
  3751. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3752. return gutterEvent(cm, e, "gutterContextMenu", false, signal);
  3753. }
  3754. // UPDATING
  3755. // Compute the position of the end of a change (its 'to' property
  3756. // refers to the pre-change end).
  3757. var changeEnd = CodeMirror.changeEnd = function(change) {
  3758. if (!change.text) return change.to;
  3759. return Pos(change.from.line + change.text.length - 1,
  3760. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3761. };
  3762. // Adjust a position to refer to the post-change position of the
  3763. // same text, or the end of the change if the change covers it.
  3764. function adjustForChange(pos, change) {
  3765. if (cmp(pos, change.from) < 0) return pos;
  3766. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3767. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3768. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3769. return Pos(line, ch);
  3770. }
  3771. function computeSelAfterChange(doc, change) {
  3772. var out = [];
  3773. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3774. var range = doc.sel.ranges[i];
  3775. out.push(new Range(adjustForChange(range.anchor, change),
  3776. adjustForChange(range.head, change)));
  3777. }
  3778. return normalizeSelection(out, doc.sel.primIndex);
  3779. }
  3780. function offsetPos(pos, old, nw) {
  3781. if (pos.line == old.line)
  3782. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3783. else
  3784. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3785. }
  3786. // Used by replaceSelections to allow moving the selection to the
  3787. // start or around the replaced test. Hint may be "start" or "around".
  3788. function computeReplacedSel(doc, changes, hint) {
  3789. var out = [];
  3790. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3791. for (var i = 0; i < changes.length; i++) {
  3792. var change = changes[i];
  3793. var from = offsetPos(change.from, oldPrev, newPrev);
  3794. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3795. oldPrev = change.to;
  3796. newPrev = to;
  3797. if (hint == "around") {
  3798. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3799. out[i] = new Range(inv ? to : from, inv ? from : to);
  3800. } else {
  3801. out[i] = new Range(from, from);
  3802. }
  3803. }
  3804. return new Selection(out, doc.sel.primIndex);
  3805. }
  3806. // Allow "beforeChange" event handlers to influence a change
  3807. function filterChange(doc, change, update) {
  3808. var obj = {
  3809. canceled: false,
  3810. from: change.from,
  3811. to: change.to,
  3812. text: change.text,
  3813. origin: change.origin,
  3814. cancel: function() { this.canceled = true; }
  3815. };
  3816. if (update) obj.update = function(from, to, text, origin) {
  3817. if (from) this.from = clipPos(doc, from);
  3818. if (to) this.to = clipPos(doc, to);
  3819. if (text) this.text = text;
  3820. if (origin !== undefined) this.origin = origin;
  3821. };
  3822. signal(doc, "beforeChange", doc, obj);
  3823. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3824. if (obj.canceled) return null;
  3825. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3826. }
  3827. // Apply a change to a document, and add it to the document's
  3828. // history, and propagating it to all linked documents.
  3829. function makeChange(doc, change, ignoreReadOnly) {
  3830. if (doc.cm) {
  3831. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3832. if (doc.cm.state.suppressEdits) return;
  3833. }
  3834. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3835. change = filterChange(doc, change, true);
  3836. if (!change) return;
  3837. }
  3838. // Possibly split or suppress the update based on the presence
  3839. // of read-only spans in its range.
  3840. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3841. if (split) {
  3842. for (var i = split.length - 1; i >= 0; --i)
  3843. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3844. } else {
  3845. makeChangeInner(doc, change);
  3846. }
  3847. }
  3848. function makeChangeInner(doc, change) {
  3849. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3850. var selAfter = computeSelAfterChange(doc, change);
  3851. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3852. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3853. var rebased = [];
  3854. linkedDocs(doc, function(doc, sharedHist) {
  3855. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3856. rebaseHist(doc.history, change);
  3857. rebased.push(doc.history);
  3858. }
  3859. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3860. });
  3861. }
  3862. // Revert a change stored in a document's history.
  3863. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3864. if (doc.cm && doc.cm.state.suppressEdits) return;
  3865. var hist = doc.history, event, selAfter = doc.sel;
  3866. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3867. // Verify that there is a useable event (so that ctrl-z won't
  3868. // needlessly clear selection events)
  3869. for (var i = 0; i < source.length; i++) {
  3870. event = source[i];
  3871. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3872. break;
  3873. }
  3874. if (i == source.length) return;
  3875. hist.lastOrigin = hist.lastSelOrigin = null;
  3876. for (;;) {
  3877. event = source.pop();
  3878. if (event.ranges) {
  3879. pushSelectionToHistory(event, dest);
  3880. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3881. setSelection(doc, event, {clearRedo: false});
  3882. return;
  3883. }
  3884. selAfter = event;
  3885. }
  3886. else break;
  3887. }
  3888. // Build up a reverse change object to add to the opposite history
  3889. // stack (redo when undoing, and vice versa).
  3890. var antiChanges = [];
  3891. pushSelectionToHistory(selAfter, dest);
  3892. dest.push({changes: antiChanges, generation: hist.generation});
  3893. hist.generation = event.generation || ++hist.maxGeneration;
  3894. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3895. for (var i = event.changes.length - 1; i >= 0; --i) {
  3896. var change = event.changes[i];
  3897. change.origin = type;
  3898. if (filter && !filterChange(doc, change, false)) {
  3899. source.length = 0;
  3900. return;
  3901. }
  3902. antiChanges.push(historyChangeFromChange(doc, change));
  3903. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3904. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3905. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  3906. var rebased = [];
  3907. // Propagate to the linked documents
  3908. linkedDocs(doc, function(doc, sharedHist) {
  3909. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3910. rebaseHist(doc.history, change);
  3911. rebased.push(doc.history);
  3912. }
  3913. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  3914. });
  3915. }
  3916. }
  3917. // Sub-views need their line numbers shifted when text is added
  3918. // above or below them in the parent document.
  3919. function shiftDoc(doc, distance) {
  3920. if (distance == 0) return;
  3921. doc.first += distance;
  3922. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  3923. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  3924. Pos(range.head.line + distance, range.head.ch));
  3925. }), doc.sel.primIndex);
  3926. if (doc.cm) {
  3927. regChange(doc.cm, doc.first, doc.first - distance, distance);
  3928. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  3929. regLineChange(doc.cm, l, "gutter");
  3930. }
  3931. }
  3932. // More lower-level change function, handling only a single document
  3933. // (not linked ones).
  3934. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  3935. if (doc.cm && !doc.cm.curOp)
  3936. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  3937. if (change.to.line < doc.first) {
  3938. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  3939. return;
  3940. }
  3941. if (change.from.line > doc.lastLine()) return;
  3942. // Clip the change to the size of this doc
  3943. if (change.from.line < doc.first) {
  3944. var shift = change.text.length - 1 - (doc.first - change.from.line);
  3945. shiftDoc(doc, shift);
  3946. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  3947. text: [lst(change.text)], origin: change.origin};
  3948. }
  3949. var last = doc.lastLine();
  3950. if (change.to.line > last) {
  3951. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  3952. text: [change.text[0]], origin: change.origin};
  3953. }
  3954. change.removed = getBetween(doc, change.from, change.to);
  3955. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  3956. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  3957. else updateDoc(doc, change, spans);
  3958. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  3959. }
  3960. // Handle the interaction of a change to a document with the editor
  3961. // that this document is part of.
  3962. function makeChangeSingleDocInEditor(cm, change, spans) {
  3963. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  3964. var recomputeMaxLength = false, checkWidthStart = from.line;
  3965. if (!cm.options.lineWrapping) {
  3966. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  3967. doc.iter(checkWidthStart, to.line + 1, function(line) {
  3968. if (line == display.maxLine) {
  3969. recomputeMaxLength = true;
  3970. return true;
  3971. }
  3972. });
  3973. }
  3974. if (doc.sel.contains(change.from, change.to) > -1)
  3975. signalCursorActivity(cm);
  3976. updateDoc(doc, change, spans, estimateHeight(cm));
  3977. if (!cm.options.lineWrapping) {
  3978. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  3979. var len = lineLength(line);
  3980. if (len > display.maxLineLength) {
  3981. display.maxLine = line;
  3982. display.maxLineLength = len;
  3983. display.maxLineChanged = true;
  3984. recomputeMaxLength = false;
  3985. }
  3986. });
  3987. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  3988. }
  3989. // Adjust frontier, schedule worker
  3990. doc.frontier = Math.min(doc.frontier, from.line);
  3991. startWorker(cm, 400);
  3992. var lendiff = change.text.length - (to.line - from.line) - 1;
  3993. // Remember that these lines changed, for updating the display
  3994. if (change.full)
  3995. regChange(cm);
  3996. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  3997. regLineChange(cm, from.line, "text");
  3998. else
  3999. regChange(cm, from.line, to.line + 1, lendiff);
  4000. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4001. if (changeHandler || changesHandler) {
  4002. var obj = {
  4003. from: from, to: to,
  4004. text: change.text,
  4005. removed: change.removed,
  4006. origin: change.origin
  4007. };
  4008. if (changeHandler) signalLater(cm, "change", cm, obj);
  4009. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  4010. }
  4011. cm.display.selForContextMenu = null;
  4012. }
  4013. function replaceRange(doc, code, from, to, origin) {
  4014. if (!to) to = from;
  4015. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  4016. if (typeof code == "string") code = splitLines(code);
  4017. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4018. }
  4019. // SCROLLING THINGS INTO VIEW
  4020. // If an editor sits on the top or bottom of the window, partially
  4021. // scrolled out of view, this ensures that the cursor is visible.
  4022. function maybeScrollWindow(cm, coords) {
  4023. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  4024. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4025. if (coords.top + box.top < 0) doScroll = true;
  4026. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  4027. if (doScroll != null && !phantom) {
  4028. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  4029. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  4030. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  4031. coords.left + "px; width: 2px;");
  4032. cm.display.lineSpace.appendChild(scrollNode);
  4033. scrollNode.scrollIntoView(doScroll);
  4034. cm.display.lineSpace.removeChild(scrollNode);
  4035. }
  4036. }
  4037. // Scroll a given position into view (immediately), verifying that
  4038. // it actually became visible (as line heights are accurately
  4039. // measured, the position of something may 'drift' during drawing).
  4040. function scrollPosIntoView(cm, pos, end, margin) {
  4041. if (margin == null) margin = 0;
  4042. for (var limit = 0; limit < 5; limit++) {
  4043. var changed = false, coords = cursorCoords(cm, pos);
  4044. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4045. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  4046. Math.min(coords.top, endCoords.top) - margin,
  4047. Math.max(coords.left, endCoords.left),
  4048. Math.max(coords.bottom, endCoords.bottom) + margin);
  4049. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4050. if (scrollPos.scrollTop != null) {
  4051. setScrollTop(cm, scrollPos.scrollTop);
  4052. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  4053. }
  4054. if (scrollPos.scrollLeft != null) {
  4055. setScrollLeft(cm, scrollPos.scrollLeft);
  4056. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  4057. }
  4058. if (!changed) break;
  4059. }
  4060. return coords;
  4061. }
  4062. // Scroll a given set of coordinates into view (immediately).
  4063. function scrollIntoView(cm, x1, y1, x2, y2) {
  4064. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  4065. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  4066. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  4067. }
  4068. // Calculate a new scroll position needed to scroll the given
  4069. // rectangle into view. Returns an object with scrollTop and
  4070. // scrollLeft properties. When these are undefined, the
  4071. // vertical/horizontal position does not need to be adjusted.
  4072. function calculateScrollPos(cm, x1, y1, x2, y2) {
  4073. var display = cm.display, snapMargin = textHeight(cm.display);
  4074. if (y1 < 0) y1 = 0;
  4075. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4076. var screen = displayHeight(cm), result = {};
  4077. if (y2 - y1 > screen) y2 = y1 + screen;
  4078. var docBottom = cm.doc.height + paddingVert(display);
  4079. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4080. if (y1 < screentop) {
  4081. result.scrollTop = atTop ? 0 : y1;
  4082. } else if (y2 > screentop + screen) {
  4083. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4084. if (newTop != screentop) result.scrollTop = newTop;
  4085. }
  4086. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4087. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4088. var tooWide = x2 - x1 > screenw;
  4089. if (tooWide) x2 = x1 + screenw;
  4090. if (x1 < 10)
  4091. result.scrollLeft = 0;
  4092. else if (x1 < screenleft)
  4093. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4094. else if (x2 > screenw + screenleft - 3)
  4095. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4096. return result;
  4097. }
  4098. // Store a relative adjustment to the scroll position in the current
  4099. // operation (to be applied when the operation finishes).
  4100. function addToScrollPos(cm, left, top) {
  4101. if (left != null || top != null) resolveScrollToPos(cm);
  4102. if (left != null)
  4103. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4104. if (top != null)
  4105. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4106. }
  4107. // Make sure that at the end of the operation the current cursor is
  4108. // shown.
  4109. function ensureCursorVisible(cm) {
  4110. resolveScrollToPos(cm);
  4111. var cur = cm.getCursor(), from = cur, to = cur;
  4112. if (!cm.options.lineWrapping) {
  4113. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4114. to = Pos(cur.line, cur.ch + 1);
  4115. }
  4116. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  4117. }
  4118. // When an operation has its scrollToPos property set, and another
  4119. // scroll action is applied before the end of the operation, this
  4120. // 'simulates' scrolling that position into view in a cheap way, so
  4121. // that the effect of intermediate scroll commands is not ignored.
  4122. function resolveScrollToPos(cm) {
  4123. var range = cm.curOp.scrollToPos;
  4124. if (range) {
  4125. cm.curOp.scrollToPos = null;
  4126. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4127. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4128. Math.min(from.top, to.top) - range.margin,
  4129. Math.max(from.right, to.right),
  4130. Math.max(from.bottom, to.bottom) + range.margin);
  4131. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4132. }
  4133. }
  4134. // API UTILITIES
  4135. // Indent the given line. The how parameter can be "smart",
  4136. // "add"/null, "subtract", or "prev". When aggressive is false
  4137. // (typically set to true for forced single-line indents), empty
  4138. // lines are not indented, and places where the mode returns Pass
  4139. // are left alone.
  4140. function indentLine(cm, n, how, aggressive) {
  4141. var doc = cm.doc, state;
  4142. if (how == null) how = "add";
  4143. if (how == "smart") {
  4144. // Fall back to "prev" when the mode doesn't have an indentation
  4145. // method.
  4146. if (!doc.mode.indent) how = "prev";
  4147. else state = getStateBefore(cm, n);
  4148. }
  4149. var tabSize = cm.options.tabSize;
  4150. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4151. if (line.stateAfter) line.stateAfter = null;
  4152. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4153. if (!aggressive && !/\S/.test(line.text)) {
  4154. indentation = 0;
  4155. how = "not";
  4156. } else if (how == "smart") {
  4157. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4158. if (indentation == Pass || indentation > 150) {
  4159. if (!aggressive) return;
  4160. how = "prev";
  4161. }
  4162. }
  4163. if (how == "prev") {
  4164. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  4165. else indentation = 0;
  4166. } else if (how == "add") {
  4167. indentation = curSpace + cm.options.indentUnit;
  4168. } else if (how == "subtract") {
  4169. indentation = curSpace - cm.options.indentUnit;
  4170. } else if (typeof how == "number") {
  4171. indentation = curSpace + how;
  4172. }
  4173. indentation = Math.max(0, indentation);
  4174. var indentString = "", pos = 0;
  4175. if (cm.options.indentWithTabs)
  4176. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  4177. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4178. if (indentString != curSpaceString) {
  4179. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4180. line.stateAfter = null;
  4181. return true;
  4182. } else {
  4183. // Ensure that, if the cursor was in the whitespace at the start
  4184. // of the line, it is moved to the end of that space.
  4185. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4186. var range = doc.sel.ranges[i];
  4187. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4188. var pos = Pos(n, curSpaceString.length);
  4189. replaceOneSelection(doc, i, new Range(pos, pos));
  4190. break;
  4191. }
  4192. }
  4193. }
  4194. }
  4195. // Utility for applying a change to a line by handle or number,
  4196. // returning the number and optionally registering the line as
  4197. // changed.
  4198. function changeLine(doc, handle, changeType, op) {
  4199. var no = handle, line = handle;
  4200. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4201. else no = lineNo(handle);
  4202. if (no == null) return null;
  4203. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4204. return line;
  4205. }
  4206. // Helper for deleting text near the selection(s), used to implement
  4207. // backspace, delete, and similar functionality.
  4208. function deleteNearSelection(cm, compute) {
  4209. var ranges = cm.doc.sel.ranges, kill = [];
  4210. // Build up a set of ranges to kill first, merging overlapping
  4211. // ranges.
  4212. for (var i = 0; i < ranges.length; i++) {
  4213. var toKill = compute(ranges[i]);
  4214. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4215. var replaced = kill.pop();
  4216. if (cmp(replaced.from, toKill.from) < 0) {
  4217. toKill.from = replaced.from;
  4218. break;
  4219. }
  4220. }
  4221. kill.push(toKill);
  4222. }
  4223. // Next, remove those actual ranges.
  4224. runInOp(cm, function() {
  4225. for (var i = kill.length - 1; i >= 0; i--)
  4226. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4227. ensureCursorVisible(cm);
  4228. });
  4229. }
  4230. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4231. // right), unit can be "char", "column" (like char, but doesn't
  4232. // cross line boundaries), "word" (across next word), or "group" (to
  4233. // the start of next group of word or non-word-non-whitespace
  4234. // chars). The visually param controls whether, in right-to-left
  4235. // text, direction 1 means to move towards the next index in the
  4236. // string, or towards the character to the right of the current
  4237. // position. The resulting position will have a hitSide=true
  4238. // property if it reached the end of the document.
  4239. function findPosH(doc, pos, dir, unit, visually) {
  4240. var line = pos.line, ch = pos.ch, origDir = dir;
  4241. var lineObj = getLine(doc, line);
  4242. var possible = true;
  4243. function findNextLine() {
  4244. var l = line + dir;
  4245. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  4246. line = l;
  4247. return lineObj = getLine(doc, l);
  4248. }
  4249. function moveOnce(boundToLine) {
  4250. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4251. if (next == null) {
  4252. if (!boundToLine && findNextLine()) {
  4253. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4254. else ch = dir < 0 ? lineObj.text.length : 0;
  4255. } else return (possible = false);
  4256. } else ch = next;
  4257. return true;
  4258. }
  4259. if (unit == "char") moveOnce();
  4260. else if (unit == "column") moveOnce(true);
  4261. else if (unit == "word" || unit == "group") {
  4262. var sawType = null, group = unit == "group";
  4263. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4264. for (var first = true;; first = false) {
  4265. if (dir < 0 && !moveOnce(!first)) break;
  4266. var cur = lineObj.text.charAt(ch) || "\n";
  4267. var type = isWordChar(cur, helper) ? "w"
  4268. : group && cur == "\n" ? "n"
  4269. : !group || /\s/.test(cur) ? null
  4270. : "p";
  4271. if (group && !first && !type) type = "s";
  4272. if (sawType && sawType != type) {
  4273. if (dir < 0) {dir = 1; moveOnce();}
  4274. break;
  4275. }
  4276. if (type) sawType = type;
  4277. if (dir > 0 && !moveOnce(!first)) break;
  4278. }
  4279. }
  4280. var result = skipAtomic(doc, Pos(line, ch), origDir, true);
  4281. if (!possible) result.hitSide = true;
  4282. return result;
  4283. }
  4284. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4285. // "page" or "line". The resulting position will have a hitSide=true
  4286. // property if it reached the end of the document.
  4287. function findPosV(cm, pos, dir, unit) {
  4288. var doc = cm.doc, x = pos.left, y;
  4289. if (unit == "page") {
  4290. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4291. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4292. } else if (unit == "line") {
  4293. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4294. }
  4295. for (;;) {
  4296. var target = coordsChar(cm, x, y);
  4297. if (!target.outside) break;
  4298. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4299. y += dir * 5;
  4300. }
  4301. return target;
  4302. }
  4303. // EDITOR METHODS
  4304. // The publicly visible API. Note that methodOp(f) means
  4305. // 'wrap f in an operation, performed on its `this` parameter'.
  4306. // This is not the complete set of editor methods. Most of the
  4307. // methods defined on the Doc type are also injected into
  4308. // CodeMirror.prototype, for backwards compatibility and
  4309. // convenience.
  4310. CodeMirror.prototype = {
  4311. constructor: CodeMirror,
  4312. focus: function(){window.focus(); this.display.input.focus();},
  4313. setOption: function(option, value) {
  4314. var options = this.options, old = options[option];
  4315. if (options[option] == value && option != "mode") return;
  4316. options[option] = value;
  4317. if (optionHandlers.hasOwnProperty(option))
  4318. operation(this, optionHandlers[option])(this, value, old);
  4319. },
  4320. getOption: function(option) {return this.options[option];},
  4321. getDoc: function() {return this.doc;},
  4322. addKeyMap: function(map, bottom) {
  4323. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4324. },
  4325. removeKeyMap: function(map) {
  4326. var maps = this.state.keyMaps;
  4327. for (var i = 0; i < maps.length; ++i)
  4328. if (maps[i] == map || maps[i].name == map) {
  4329. maps.splice(i, 1);
  4330. return true;
  4331. }
  4332. },
  4333. addOverlay: methodOp(function(spec, options) {
  4334. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4335. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4336. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  4337. this.state.modeGen++;
  4338. regChange(this);
  4339. }),
  4340. removeOverlay: methodOp(function(spec) {
  4341. var overlays = this.state.overlays;
  4342. for (var i = 0; i < overlays.length; ++i) {
  4343. var cur = overlays[i].modeSpec;
  4344. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4345. overlays.splice(i, 1);
  4346. this.state.modeGen++;
  4347. regChange(this);
  4348. return;
  4349. }
  4350. }
  4351. }),
  4352. indentLine: methodOp(function(n, dir, aggressive) {
  4353. if (typeof dir != "string" && typeof dir != "number") {
  4354. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4355. else dir = dir ? "add" : "subtract";
  4356. }
  4357. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4358. }),
  4359. indentSelection: methodOp(function(how) {
  4360. var ranges = this.doc.sel.ranges, end = -1;
  4361. for (var i = 0; i < ranges.length; i++) {
  4362. var range = ranges[i];
  4363. if (!range.empty()) {
  4364. var from = range.from(), to = range.to();
  4365. var start = Math.max(end, from.line);
  4366. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4367. for (var j = start; j < end; ++j)
  4368. indentLine(this, j, how);
  4369. var newRanges = this.doc.sel.ranges;
  4370. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4371. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4372. } else if (range.head.line > end) {
  4373. indentLine(this, range.head.line, how, true);
  4374. end = range.head.line;
  4375. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4376. }
  4377. }
  4378. }),
  4379. // Fetch the parser token for a given character. Useful for hacks
  4380. // that want to inspect the mode state (say, for completion).
  4381. getTokenAt: function(pos, precise) {
  4382. return takeToken(this, pos, precise);
  4383. },
  4384. getLineTokens: function(line, precise) {
  4385. return takeToken(this, Pos(line), precise, true);
  4386. },
  4387. getTokenTypeAt: function(pos) {
  4388. pos = clipPos(this.doc, pos);
  4389. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4390. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4391. var type;
  4392. if (ch == 0) type = styles[2];
  4393. else for (;;) {
  4394. var mid = (before + after) >> 1;
  4395. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4396. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4397. else { type = styles[mid * 2 + 2]; break; }
  4398. }
  4399. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4400. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4401. },
  4402. getModeAt: function(pos) {
  4403. var mode = this.doc.mode;
  4404. if (!mode.innerMode) return mode;
  4405. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4406. },
  4407. getHelper: function(pos, type) {
  4408. return this.getHelpers(pos, type)[0];
  4409. },
  4410. getHelpers: function(pos, type) {
  4411. var found = [];
  4412. if (!helpers.hasOwnProperty(type)) return found;
  4413. var help = helpers[type], mode = this.getModeAt(pos);
  4414. if (typeof mode[type] == "string") {
  4415. if (help[mode[type]]) found.push(help[mode[type]]);
  4416. } else if (mode[type]) {
  4417. for (var i = 0; i < mode[type].length; i++) {
  4418. var val = help[mode[type][i]];
  4419. if (val) found.push(val);
  4420. }
  4421. } else if (mode.helperType && help[mode.helperType]) {
  4422. found.push(help[mode.helperType]);
  4423. } else if (help[mode.name]) {
  4424. found.push(help[mode.name]);
  4425. }
  4426. for (var i = 0; i < help._global.length; i++) {
  4427. var cur = help._global[i];
  4428. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4429. found.push(cur.val);
  4430. }
  4431. return found;
  4432. },
  4433. getStateAfter: function(line, precise) {
  4434. var doc = this.doc;
  4435. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  4436. return getStateBefore(this, line + 1, precise);
  4437. },
  4438. cursorCoords: function(start, mode) {
  4439. var pos, range = this.doc.sel.primary();
  4440. if (start == null) pos = range.head;
  4441. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4442. else pos = start ? range.from() : range.to();
  4443. return cursorCoords(this, pos, mode || "page");
  4444. },
  4445. charCoords: function(pos, mode) {
  4446. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4447. },
  4448. coordsChar: function(coords, mode) {
  4449. coords = fromCoordSystem(this, coords, mode || "page");
  4450. return coordsChar(this, coords.left, coords.top);
  4451. },
  4452. lineAtHeight: function(height, mode) {
  4453. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  4454. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4455. },
  4456. heightAtLine: function(line, mode) {
  4457. var end = false, lineObj;
  4458. if (typeof line == "number") {
  4459. var last = this.doc.first + this.doc.size - 1;
  4460. if (line < this.doc.first) line = this.doc.first;
  4461. else if (line > last) { line = last; end = true; }
  4462. lineObj = getLine(this.doc, line);
  4463. } else {
  4464. lineObj = line;
  4465. }
  4466. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  4467. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4468. },
  4469. defaultTextHeight: function() { return textHeight(this.display); },
  4470. defaultCharWidth: function() { return charWidth(this.display); },
  4471. setGutterMarker: methodOp(function(line, gutterID, value) {
  4472. return changeLine(this.doc, line, "gutter", function(line) {
  4473. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4474. markers[gutterID] = value;
  4475. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4476. return true;
  4477. });
  4478. }),
  4479. clearGutter: methodOp(function(gutterID) {
  4480. var cm = this, doc = cm.doc, i = doc.first;
  4481. doc.iter(function(line) {
  4482. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4483. line.gutterMarkers[gutterID] = null;
  4484. regLineChange(cm, i, "gutter");
  4485. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4486. }
  4487. ++i;
  4488. });
  4489. }),
  4490. lineInfo: function(line) {
  4491. if (typeof line == "number") {
  4492. if (!isLine(this.doc, line)) return null;
  4493. var n = line;
  4494. line = getLine(this.doc, line);
  4495. if (!line) return null;
  4496. } else {
  4497. var n = lineNo(line);
  4498. if (n == null) return null;
  4499. }
  4500. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4501. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4502. widgets: line.widgets};
  4503. },
  4504. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  4505. addWidget: function(pos, node, scroll, vert, horiz) {
  4506. var display = this.display;
  4507. pos = cursorCoords(this, clipPos(this.doc, pos));
  4508. var top = pos.bottom, left = pos.left;
  4509. node.style.position = "absolute";
  4510. node.setAttribute("cm-ignore-events", "true");
  4511. this.display.input.setUneditable(node);
  4512. display.sizer.appendChild(node);
  4513. if (vert == "over") {
  4514. top = pos.top;
  4515. } else if (vert == "above" || vert == "near") {
  4516. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4517. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4518. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4519. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4520. top = pos.top - node.offsetHeight;
  4521. else if (pos.bottom + node.offsetHeight <= vspace)
  4522. top = pos.bottom;
  4523. if (left + node.offsetWidth > hspace)
  4524. left = hspace - node.offsetWidth;
  4525. }
  4526. node.style.top = top + "px";
  4527. node.style.left = node.style.right = "";
  4528. if (horiz == "right") {
  4529. left = display.sizer.clientWidth - node.offsetWidth;
  4530. node.style.right = "0px";
  4531. } else {
  4532. if (horiz == "left") left = 0;
  4533. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4534. node.style.left = left + "px";
  4535. }
  4536. if (scroll)
  4537. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4538. },
  4539. triggerOnKeyDown: methodOp(onKeyDown),
  4540. triggerOnKeyPress: methodOp(onKeyPress),
  4541. triggerOnKeyUp: onKeyUp,
  4542. execCommand: function(cmd) {
  4543. if (commands.hasOwnProperty(cmd))
  4544. return commands[cmd](this);
  4545. },
  4546. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  4547. findPosH: function(from, amount, unit, visually) {
  4548. var dir = 1;
  4549. if (amount < 0) { dir = -1; amount = -amount; }
  4550. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4551. cur = findPosH(this.doc, cur, dir, unit, visually);
  4552. if (cur.hitSide) break;
  4553. }
  4554. return cur;
  4555. },
  4556. moveH: methodOp(function(dir, unit) {
  4557. var cm = this;
  4558. cm.extendSelectionsBy(function(range) {
  4559. if (cm.display.shift || cm.doc.extend || range.empty())
  4560. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4561. else
  4562. return dir < 0 ? range.from() : range.to();
  4563. }, sel_move);
  4564. }),
  4565. deleteH: methodOp(function(dir, unit) {
  4566. var sel = this.doc.sel, doc = this.doc;
  4567. if (sel.somethingSelected())
  4568. doc.replaceSelection("", null, "+delete");
  4569. else
  4570. deleteNearSelection(this, function(range) {
  4571. var other = findPosH(doc, range.head, dir, unit, false);
  4572. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4573. });
  4574. }),
  4575. findPosV: function(from, amount, unit, goalColumn) {
  4576. var dir = 1, x = goalColumn;
  4577. if (amount < 0) { dir = -1; amount = -amount; }
  4578. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4579. var coords = cursorCoords(this, cur, "div");
  4580. if (x == null) x = coords.left;
  4581. else coords.left = x;
  4582. cur = findPosV(this, coords, dir, unit);
  4583. if (cur.hitSide) break;
  4584. }
  4585. return cur;
  4586. },
  4587. moveV: methodOp(function(dir, unit) {
  4588. var cm = this, doc = this.doc, goals = [];
  4589. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4590. doc.extendSelectionsBy(function(range) {
  4591. if (collapse)
  4592. return dir < 0 ? range.from() : range.to();
  4593. var headPos = cursorCoords(cm, range.head, "div");
  4594. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4595. goals.push(headPos.left);
  4596. var pos = findPosV(cm, headPos, dir, unit);
  4597. if (unit == "page" && range == doc.sel.primary())
  4598. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4599. return pos;
  4600. }, sel_move);
  4601. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4602. doc.sel.ranges[i].goalColumn = goals[i];
  4603. }),
  4604. // Find the word at the given position (as returned by coordsChar).
  4605. findWordAt: function(pos) {
  4606. var doc = this.doc, line = getLine(doc, pos.line).text;
  4607. var start = pos.ch, end = pos.ch;
  4608. if (line) {
  4609. var helper = this.getHelper(pos, "wordChars");
  4610. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4611. var startChar = line.charAt(start);
  4612. var check = isWordChar(startChar, helper)
  4613. ? function(ch) { return isWordChar(ch, helper); }
  4614. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4615. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4616. while (start > 0 && check(line.charAt(start - 1))) --start;
  4617. while (end < line.length && check(line.charAt(end))) ++end;
  4618. }
  4619. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4620. },
  4621. toggleOverwrite: function(value) {
  4622. if (value != null && value == this.state.overwrite) return;
  4623. if (this.state.overwrite = !this.state.overwrite)
  4624. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4625. else
  4626. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4627. signal(this, "overwriteToggle", this, this.state.overwrite);
  4628. },
  4629. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  4630. scrollTo: methodOp(function(x, y) {
  4631. if (x != null || y != null) resolveScrollToPos(this);
  4632. if (x != null) this.curOp.scrollLeft = x;
  4633. if (y != null) this.curOp.scrollTop = y;
  4634. }),
  4635. getScrollInfo: function() {
  4636. var scroller = this.display.scroller;
  4637. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4638. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4639. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4640. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4641. },
  4642. scrollIntoView: methodOp(function(range, margin) {
  4643. if (range == null) {
  4644. range = {from: this.doc.sel.primary().head, to: null};
  4645. if (margin == null) margin = this.options.cursorScrollMargin;
  4646. } else if (typeof range == "number") {
  4647. range = {from: Pos(range, 0), to: null};
  4648. } else if (range.from == null) {
  4649. range = {from: range, to: null};
  4650. }
  4651. if (!range.to) range.to = range.from;
  4652. range.margin = margin || 0;
  4653. if (range.from.line != null) {
  4654. resolveScrollToPos(this);
  4655. this.curOp.scrollToPos = range;
  4656. } else {
  4657. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4658. Math.min(range.from.top, range.to.top) - range.margin,
  4659. Math.max(range.from.right, range.to.right),
  4660. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4661. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4662. }
  4663. }),
  4664. setSize: methodOp(function(width, height) {
  4665. var cm = this;
  4666. function interpret(val) {
  4667. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4668. }
  4669. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4670. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4671. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4672. var lineNo = cm.display.viewFrom;
  4673. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4674. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4675. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4676. ++lineNo;
  4677. });
  4678. cm.curOp.forceUpdate = true;
  4679. signal(cm, "refresh", this);
  4680. }),
  4681. operation: function(f){return runInOp(this, f);},
  4682. refresh: methodOp(function() {
  4683. var oldHeight = this.display.cachedTextHeight;
  4684. regChange(this);
  4685. this.curOp.forceUpdate = true;
  4686. clearCaches(this);
  4687. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4688. updateGutterSpace(this);
  4689. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4690. estimateLineHeights(this);
  4691. signal(this, "refresh", this);
  4692. }),
  4693. swapDoc: methodOp(function(doc) {
  4694. var old = this.doc;
  4695. old.cm = null;
  4696. attachDoc(this, doc);
  4697. clearCaches(this);
  4698. this.display.input.reset();
  4699. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4700. this.curOp.forceScroll = true;
  4701. signalLater(this, "swapDoc", this, old);
  4702. return old;
  4703. }),
  4704. getInputField: function(){return this.display.input.getField();},
  4705. getWrapperElement: function(){return this.display.wrapper;},
  4706. getScrollerElement: function(){return this.display.scroller;},
  4707. getGutterElement: function(){return this.display.gutters;}
  4708. };
  4709. eventMixin(CodeMirror);
  4710. // OPTION DEFAULTS
  4711. // The default configuration options.
  4712. var defaults = CodeMirror.defaults = {};
  4713. // Functions to run when options are changed.
  4714. var optionHandlers = CodeMirror.optionHandlers = {};
  4715. function option(name, deflt, handle, notOnInit) {
  4716. CodeMirror.defaults[name] = deflt;
  4717. if (handle) optionHandlers[name] =
  4718. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4719. }
  4720. // Passed to option handlers when there is no old value.
  4721. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4722. // These two are, on init, called from the constructor because they
  4723. // have to be initialized before the editor can start at all.
  4724. option("value", "", function(cm, val) {
  4725. cm.setValue(val);
  4726. }, true);
  4727. option("mode", null, function(cm, val) {
  4728. cm.doc.modeOption = val;
  4729. loadMode(cm);
  4730. }, true);
  4731. option("indentUnit", 2, loadMode, true);
  4732. option("indentWithTabs", false);
  4733. option("smartIndent", true);
  4734. option("tabSize", 4, function(cm) {
  4735. resetModeState(cm);
  4736. clearCaches(cm);
  4737. regChange(cm);
  4738. }, true);
  4739. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  4740. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4741. if (old != CodeMirror.Init) cm.refresh();
  4742. });
  4743. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4744. option("electricChars", true);
  4745. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  4746. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4747. }, true);
  4748. option("rtlMoveVisually", !windows);
  4749. option("wholeLineUpdateBefore", true);
  4750. option("theme", "default", function(cm) {
  4751. themeChanged(cm);
  4752. guttersChanged(cm);
  4753. }, true);
  4754. option("keyMap", "default", function(cm, val, old) {
  4755. var next = getKeyMap(val);
  4756. var prev = old != CodeMirror.Init && getKeyMap(old);
  4757. if (prev && prev.detach) prev.detach(cm, next);
  4758. if (next.attach) next.attach(cm, prev || null);
  4759. });
  4760. option("extraKeys", null);
  4761. option("lineWrapping", false, wrappingChanged, true);
  4762. option("gutters", [], function(cm) {
  4763. setGuttersForLineNumbers(cm.options);
  4764. guttersChanged(cm);
  4765. }, true);
  4766. option("fixedGutter", true, function(cm, val) {
  4767. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4768. cm.refresh();
  4769. }, true);
  4770. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4771. option("scrollbarStyle", "native", function(cm) {
  4772. initScrollbars(cm);
  4773. updateScrollbars(cm);
  4774. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4775. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4776. }, true);
  4777. option("lineNumbers", false, function(cm) {
  4778. setGuttersForLineNumbers(cm.options);
  4779. guttersChanged(cm);
  4780. }, true);
  4781. option("firstLineNumber", 1, guttersChanged, true);
  4782. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4783. option("showCursorWhenSelecting", false, updateSelection, true);
  4784. option("resetSelectionOnContextMenu", true);
  4785. option("lineWiseCopyCut", true);
  4786. option("readOnly", false, function(cm, val) {
  4787. if (val == "nocursor") {
  4788. onBlur(cm);
  4789. cm.display.input.blur();
  4790. cm.display.disabled = true;
  4791. } else {
  4792. cm.display.disabled = false;
  4793. if (!val) cm.display.input.reset();
  4794. }
  4795. });
  4796. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  4797. option("dragDrop", true, dragDropChanged);
  4798. option("cursorBlinkRate", 530);
  4799. option("cursorScrollMargin", 0);
  4800. option("cursorHeight", 1, updateSelection, true);
  4801. option("singleCursorHeightPerLine", true, updateSelection, true);
  4802. option("workTime", 100);
  4803. option("workDelay", 100);
  4804. option("flattenSpans", true, resetModeState, true);
  4805. option("addModeClass", false, resetModeState, true);
  4806. option("pollInterval", 100);
  4807. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4808. option("historyEventDelay", 1250);
  4809. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4810. option("maxHighlightLength", 10000, resetModeState, true);
  4811. option("moveInputWithCursor", true, function(cm, val) {
  4812. if (!val) cm.display.input.resetPosition();
  4813. });
  4814. option("tabindex", null, function(cm, val) {
  4815. cm.display.input.getField().tabIndex = val || "";
  4816. });
  4817. option("autofocus", null);
  4818. // MODE DEFINITION AND QUERYING
  4819. // Known modes, by name and by MIME
  4820. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4821. // Extra arguments are stored as the mode's dependencies, which is
  4822. // used by (legacy) mechanisms like loadmode.js to automatically
  4823. // load a mode. (Preferred mechanism is the require/define calls.)
  4824. CodeMirror.defineMode = function(name, mode) {
  4825. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4826. if (arguments.length > 2)
  4827. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4828. modes[name] = mode;
  4829. };
  4830. CodeMirror.defineMIME = function(mime, spec) {
  4831. mimeModes[mime] = spec;
  4832. };
  4833. // Given a MIME type, a {name, ...options} config object, or a name
  4834. // string, return a mode config object.
  4835. CodeMirror.resolveMode = function(spec) {
  4836. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4837. spec = mimeModes[spec];
  4838. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4839. var found = mimeModes[spec.name];
  4840. if (typeof found == "string") found = {name: found};
  4841. spec = createObj(found, spec);
  4842. spec.name = found.name;
  4843. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4844. return CodeMirror.resolveMode("application/xml");
  4845. }
  4846. if (typeof spec == "string") return {name: spec};
  4847. else return spec || {name: "null"};
  4848. };
  4849. // Given a mode spec (anything that resolveMode accepts), find and
  4850. // initialize an actual mode object.
  4851. CodeMirror.getMode = function(options, spec) {
  4852. var spec = CodeMirror.resolveMode(spec);
  4853. var mfactory = modes[spec.name];
  4854. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4855. var modeObj = mfactory(options, spec);
  4856. if (modeExtensions.hasOwnProperty(spec.name)) {
  4857. var exts = modeExtensions[spec.name];
  4858. for (var prop in exts) {
  4859. if (!exts.hasOwnProperty(prop)) continue;
  4860. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4861. modeObj[prop] = exts[prop];
  4862. }
  4863. }
  4864. modeObj.name = spec.name;
  4865. if (spec.helperType) modeObj.helperType = spec.helperType;
  4866. if (spec.modeProps) for (var prop in spec.modeProps)
  4867. modeObj[prop] = spec.modeProps[prop];
  4868. return modeObj;
  4869. };
  4870. // Minimal default mode.
  4871. CodeMirror.defineMode("null", function() {
  4872. return {token: function(stream) {stream.skipToEnd();}};
  4873. });
  4874. CodeMirror.defineMIME("text/plain", "null");
  4875. // This can be used to attach properties to mode objects from
  4876. // outside the actual mode definition.
  4877. var modeExtensions = CodeMirror.modeExtensions = {};
  4878. CodeMirror.extendMode = function(mode, properties) {
  4879. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4880. copyObj(properties, exts);
  4881. };
  4882. // EXTENSIONS
  4883. CodeMirror.defineExtension = function(name, func) {
  4884. CodeMirror.prototype[name] = func;
  4885. };
  4886. CodeMirror.defineDocExtension = function(name, func) {
  4887. Doc.prototype[name] = func;
  4888. };
  4889. CodeMirror.defineOption = option;
  4890. var initHooks = [];
  4891. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  4892. var helpers = CodeMirror.helpers = {};
  4893. CodeMirror.registerHelper = function(type, name, value) {
  4894. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  4895. helpers[type][name] = value;
  4896. };
  4897. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  4898. CodeMirror.registerHelper(type, name, value);
  4899. helpers[type]._global.push({pred: predicate, val: value});
  4900. };
  4901. // MODE STATE HANDLING
  4902. // Utility functions for working with state. Exported because nested
  4903. // modes need to do this for their inner modes.
  4904. var copyState = CodeMirror.copyState = function(mode, state) {
  4905. if (state === true) return state;
  4906. if (mode.copyState) return mode.copyState(state);
  4907. var nstate = {};
  4908. for (var n in state) {
  4909. var val = state[n];
  4910. if (val instanceof Array) val = val.concat([]);
  4911. nstate[n] = val;
  4912. }
  4913. return nstate;
  4914. };
  4915. var startState = CodeMirror.startState = function(mode, a1, a2) {
  4916. return mode.startState ? mode.startState(a1, a2) : true;
  4917. };
  4918. // Given a mode and a state (for that mode), find the inner mode and
  4919. // state at the position that the state refers to.
  4920. CodeMirror.innerMode = function(mode, state) {
  4921. while (mode.innerMode) {
  4922. var info = mode.innerMode(state);
  4923. if (!info || info.mode == mode) break;
  4924. state = info.state;
  4925. mode = info.mode;
  4926. }
  4927. return info || {mode: mode, state: state};
  4928. };
  4929. // STANDARD COMMANDS
  4930. // Commands are parameter-less actions that can be performed on an
  4931. // editor, mostly used for keybindings.
  4932. var commands = CodeMirror.commands = {
  4933. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  4934. singleSelection: function(cm) {
  4935. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  4936. },
  4937. killLine: function(cm) {
  4938. deleteNearSelection(cm, function(range) {
  4939. if (range.empty()) {
  4940. var len = getLine(cm.doc, range.head.line).text.length;
  4941. if (range.head.ch == len && range.head.line < cm.lastLine())
  4942. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  4943. else
  4944. return {from: range.head, to: Pos(range.head.line, len)};
  4945. } else {
  4946. return {from: range.from(), to: range.to()};
  4947. }
  4948. });
  4949. },
  4950. deleteLine: function(cm) {
  4951. deleteNearSelection(cm, function(range) {
  4952. return {from: Pos(range.from().line, 0),
  4953. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  4954. });
  4955. },
  4956. delLineLeft: function(cm) {
  4957. deleteNearSelection(cm, function(range) {
  4958. return {from: Pos(range.from().line, 0), to: range.from()};
  4959. });
  4960. },
  4961. delWrappedLineLeft: function(cm) {
  4962. deleteNearSelection(cm, function(range) {
  4963. var top = cm.charCoords(range.head, "div").top + 5;
  4964. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  4965. return {from: leftPos, to: range.from()};
  4966. });
  4967. },
  4968. delWrappedLineRight: function(cm) {
  4969. deleteNearSelection(cm, function(range) {
  4970. var top = cm.charCoords(range.head, "div").top + 5;
  4971. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4972. return {from: range.from(), to: rightPos };
  4973. });
  4974. },
  4975. undo: function(cm) {cm.undo();},
  4976. redo: function(cm) {cm.redo();},
  4977. undoSelection: function(cm) {cm.undoSelection();},
  4978. redoSelection: function(cm) {cm.redoSelection();},
  4979. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  4980. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  4981. goLineStart: function(cm) {
  4982. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  4983. {origin: "+move", bias: 1});
  4984. },
  4985. goLineStartSmart: function(cm) {
  4986. cm.extendSelectionsBy(function(range) {
  4987. return lineStartSmart(cm, range.head);
  4988. }, {origin: "+move", bias: 1});
  4989. },
  4990. goLineEnd: function(cm) {
  4991. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  4992. {origin: "+move", bias: -1});
  4993. },
  4994. goLineRight: function(cm) {
  4995. cm.extendSelectionsBy(function(range) {
  4996. var top = cm.charCoords(range.head, "div").top + 5;
  4997. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4998. }, sel_move);
  4999. },
  5000. goLineLeft: function(cm) {
  5001. cm.extendSelectionsBy(function(range) {
  5002. var top = cm.charCoords(range.head, "div").top + 5;
  5003. return cm.coordsChar({left: 0, top: top}, "div");
  5004. }, sel_move);
  5005. },
  5006. goLineLeftSmart: function(cm) {
  5007. cm.extendSelectionsBy(function(range) {
  5008. var top = cm.charCoords(range.head, "div").top + 5;
  5009. var pos = cm.coordsChar({left: 0, top: top}, "div");
  5010. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  5011. return pos;
  5012. }, sel_move);
  5013. },
  5014. goLineUp: function(cm) {cm.moveV(-1, "line");},
  5015. goLineDown: function(cm) {cm.moveV(1, "line");},
  5016. goPageUp: function(cm) {cm.moveV(-1, "page");},
  5017. goPageDown: function(cm) {cm.moveV(1, "page");},
  5018. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  5019. goCharRight: function(cm) {cm.moveH(1, "char");},
  5020. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  5021. goColumnRight: function(cm) {cm.moveH(1, "column");},
  5022. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  5023. goGroupRight: function(cm) {cm.moveH(1, "group");},
  5024. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  5025. goWordRight: function(cm) {cm.moveH(1, "word");},
  5026. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  5027. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  5028. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  5029. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  5030. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  5031. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  5032. indentAuto: function(cm) {cm.indentSelection("smart");},
  5033. indentMore: function(cm) {cm.indentSelection("add");},
  5034. indentLess: function(cm) {cm.indentSelection("subtract");},
  5035. insertTab: function(cm) {cm.replaceSelection("\t");},
  5036. insertSoftTab: function(cm) {
  5037. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  5038. for (var i = 0; i < ranges.length; i++) {
  5039. var pos = ranges[i].from();
  5040. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  5041. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  5042. }
  5043. cm.replaceSelections(spaces);
  5044. },
  5045. defaultTab: function(cm) {
  5046. if (cm.somethingSelected()) cm.indentSelection("add");
  5047. else cm.execCommand("insertTab");
  5048. },
  5049. transposeChars: function(cm) {
  5050. runInOp(cm, function() {
  5051. var ranges = cm.listSelections(), newSel = [];
  5052. for (var i = 0; i < ranges.length; i++) {
  5053. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  5054. if (line) {
  5055. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  5056. if (cur.ch > 0) {
  5057. cur = new Pos(cur.line, cur.ch + 1);
  5058. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5059. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  5060. } else if (cur.line > cm.doc.first) {
  5061. var prev = getLine(cm.doc, cur.line - 1).text;
  5062. if (prev)
  5063. cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
  5064. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  5065. }
  5066. }
  5067. newSel.push(new Range(cur, cur));
  5068. }
  5069. cm.setSelections(newSel);
  5070. });
  5071. },
  5072. newlineAndIndent: function(cm) {
  5073. runInOp(cm, function() {
  5074. var len = cm.listSelections().length;
  5075. for (var i = 0; i < len; i++) {
  5076. var range = cm.listSelections()[i];
  5077. cm.replaceRange("\n", range.anchor, range.head, "+input");
  5078. cm.indentLine(range.from().line + 1, null, true);
  5079. ensureCursorVisible(cm);
  5080. }
  5081. });
  5082. },
  5083. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  5084. };
  5085. // STANDARD KEYMAPS
  5086. var keyMap = CodeMirror.keyMap = {};
  5087. keyMap.basic = {
  5088. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5089. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5090. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5091. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5092. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5093. "Esc": "singleSelection"
  5094. };
  5095. // Note that the save and find-related commands aren't defined by
  5096. // default. User code or addons can define them. Unknown commands
  5097. // are simply ignored.
  5098. keyMap.pcDefault = {
  5099. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5100. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5101. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5102. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5103. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5104. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5105. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5106. fallthrough: "basic"
  5107. };
  5108. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5109. keyMap.emacsy = {
  5110. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5111. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5112. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5113. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  5114. };
  5115. keyMap.macDefault = {
  5116. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5117. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5118. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5119. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5120. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5121. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5122. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5123. fallthrough: ["basic", "emacsy"]
  5124. };
  5125. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5126. // KEYMAP DISPATCH
  5127. function normalizeKeyName(name) {
  5128. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5129. var alt, ctrl, shift, cmd;
  5130. for (var i = 0; i < parts.length - 1; i++) {
  5131. var mod = parts[i];
  5132. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5133. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5134. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5135. else if (/^s(hift)$/i.test(mod)) shift = true;
  5136. else throw new Error("Unrecognized modifier name: " + mod);
  5137. }
  5138. if (alt) name = "Alt-" + name;
  5139. if (ctrl) name = "Ctrl-" + name;
  5140. if (cmd) name = "Cmd-" + name;
  5141. if (shift) name = "Shift-" + name;
  5142. return name;
  5143. }
  5144. // This is a kludge to keep keymaps mostly working as raw objects
  5145. // (backwards compatibility) while at the same time support features
  5146. // like normalization and multi-stroke key bindings. It compiles a
  5147. // new normalized keymap, and then updates the old object to reflect
  5148. // this.
  5149. CodeMirror.normalizeKeyMap = function(keymap) {
  5150. var copy = {};
  5151. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5152. var value = keymap[keyname];
  5153. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5154. if (value == "...") { delete keymap[keyname]; continue; }
  5155. var keys = map(keyname.split(" "), normalizeKeyName);
  5156. for (var i = 0; i < keys.length; i++) {
  5157. var val, name;
  5158. if (i == keys.length - 1) {
  5159. name = keys.join(" ");
  5160. val = value;
  5161. } else {
  5162. name = keys.slice(0, i + 1).join(" ");
  5163. val = "...";
  5164. }
  5165. var prev = copy[name];
  5166. if (!prev) copy[name] = val;
  5167. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5168. }
  5169. delete keymap[keyname];
  5170. }
  5171. for (var prop in copy) keymap[prop] = copy[prop];
  5172. return keymap;
  5173. };
  5174. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  5175. map = getKeyMap(map);
  5176. var found = map.call ? map.call(key, context) : map[key];
  5177. if (found === false) return "nothing";
  5178. if (found === "...") return "multi";
  5179. if (found != null && handle(found)) return "handled";
  5180. if (map.fallthrough) {
  5181. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5182. return lookupKey(key, map.fallthrough, handle, context);
  5183. for (var i = 0; i < map.fallthrough.length; i++) {
  5184. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5185. if (result) return result;
  5186. }
  5187. }
  5188. };
  5189. // Modifier key presses don't count as 'real' key presses for the
  5190. // purpose of keymap fallthrough.
  5191. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  5192. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5193. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5194. };
  5195. // Look up the name of a key as indicated by an event object.
  5196. var keyName = CodeMirror.keyName = function(event, noShift) {
  5197. if (presto && event.keyCode == 34 && event["char"]) return false;
  5198. var base = keyNames[event.keyCode], name = base;
  5199. if (name == null || event.altGraphKey) return false;
  5200. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5201. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5202. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5203. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5204. return name;
  5205. };
  5206. function getKeyMap(val) {
  5207. return typeof val == "string" ? keyMap[val] : val;
  5208. }
  5209. // FROMTEXTAREA
  5210. CodeMirror.fromTextArea = function(textarea, options) {
  5211. options = options ? copyObj(options) : {};
  5212. options.value = textarea.value;
  5213. if (!options.tabindex && textarea.tabIndex)
  5214. options.tabindex = textarea.tabIndex;
  5215. if (!options.placeholder && textarea.placeholder)
  5216. options.placeholder = textarea.placeholder;
  5217. // Set autofocus to true if this textarea is focused, or if it has
  5218. // autofocus and no other element is focused.
  5219. if (options.autofocus == null) {
  5220. var hasFocus = activeElt();
  5221. options.autofocus = hasFocus == textarea ||
  5222. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5223. }
  5224. function save() {textarea.value = cm.getValue();}
  5225. if (textarea.form) {
  5226. on(textarea.form, "submit", save);
  5227. // Deplorable hack to make the submit method do the right thing.
  5228. if (!options.leaveSubmitMethodAlone) {
  5229. var form = textarea.form, realSubmit = form.submit;
  5230. try {
  5231. var wrappedSubmit = form.submit = function() {
  5232. save();
  5233. form.submit = realSubmit;
  5234. form.submit();
  5235. form.submit = wrappedSubmit;
  5236. };
  5237. } catch(e) {}
  5238. }
  5239. }
  5240. options.finishInit = function(cm) {
  5241. cm.save = save;
  5242. cm.getTextArea = function() { return textarea; };
  5243. cm.toTextArea = function() {
  5244. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5245. save();
  5246. textarea.parentNode.removeChild(cm.getWrapperElement());
  5247. textarea.style.display = "";
  5248. if (textarea.form) {
  5249. off(textarea.form, "submit", save);
  5250. if (typeof textarea.form.submit == "function")
  5251. textarea.form.submit = realSubmit;
  5252. }
  5253. };
  5254. };
  5255. textarea.style.display = "none";
  5256. var cm = CodeMirror(function(node) {
  5257. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5258. }, options);
  5259. return cm;
  5260. };
  5261. // STRING STREAM
  5262. // Fed to the mode parsers, provides helper functions to make
  5263. // parsers more succinct.
  5264. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  5265. this.pos = this.start = 0;
  5266. this.string = string;
  5267. this.tabSize = tabSize || 8;
  5268. this.lastColumnPos = this.lastColumnValue = 0;
  5269. this.lineStart = 0;
  5270. };
  5271. StringStream.prototype = {
  5272. eol: function() {return this.pos >= this.string.length;},
  5273. sol: function() {return this.pos == this.lineStart;},
  5274. peek: function() {return this.string.charAt(this.pos) || undefined;},
  5275. next: function() {
  5276. if (this.pos < this.string.length)
  5277. return this.string.charAt(this.pos++);
  5278. },
  5279. eat: function(match) {
  5280. var ch = this.string.charAt(this.pos);
  5281. if (typeof match == "string") var ok = ch == match;
  5282. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5283. if (ok) {++this.pos; return ch;}
  5284. },
  5285. eatWhile: function(match) {
  5286. var start = this.pos;
  5287. while (this.eat(match)){}
  5288. return this.pos > start;
  5289. },
  5290. eatSpace: function() {
  5291. var start = this.pos;
  5292. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  5293. return this.pos > start;
  5294. },
  5295. skipToEnd: function() {this.pos = this.string.length;},
  5296. skipTo: function(ch) {
  5297. var found = this.string.indexOf(ch, this.pos);
  5298. if (found > -1) {this.pos = found; return true;}
  5299. },
  5300. backUp: function(n) {this.pos -= n;},
  5301. column: function() {
  5302. if (this.lastColumnPos < this.start) {
  5303. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5304. this.lastColumnPos = this.start;
  5305. }
  5306. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5307. },
  5308. indentation: function() {
  5309. return countColumn(this.string, null, this.tabSize) -
  5310. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5311. },
  5312. match: function(pattern, consume, caseInsensitive) {
  5313. if (typeof pattern == "string") {
  5314. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  5315. var substr = this.string.substr(this.pos, pattern.length);
  5316. if (cased(substr) == cased(pattern)) {
  5317. if (consume !== false) this.pos += pattern.length;
  5318. return true;
  5319. }
  5320. } else {
  5321. var match = this.string.slice(this.pos).match(pattern);
  5322. if (match && match.index > 0) return null;
  5323. if (match && consume !== false) this.pos += match[0].length;
  5324. return match;
  5325. }
  5326. },
  5327. current: function(){return this.string.slice(this.start, this.pos);},
  5328. hideFirstChars: function(n, inner) {
  5329. this.lineStart += n;
  5330. try { return inner(); }
  5331. finally { this.lineStart -= n; }
  5332. }
  5333. };
  5334. // TEXTMARKERS
  5335. // Created with markText and setBookmark methods. A TextMarker is a
  5336. // handle that can be used to clear or find a marked position in the
  5337. // document. Line objects hold arrays (markedSpans) containing
  5338. // {from, to, marker} object pointing to such marker objects, and
  5339. // indicating that such a marker is present on that line. Multiple
  5340. // lines may point to the same marker when it spans across lines.
  5341. // The spans will have null for their from/to properties when the
  5342. // marker continues beyond the start/end of the line. Markers have
  5343. // links back to the lines they currently touch.
  5344. var nextMarkerId = 0;
  5345. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  5346. this.lines = [];
  5347. this.type = type;
  5348. this.doc = doc;
  5349. this.id = ++nextMarkerId;
  5350. };
  5351. eventMixin(TextMarker);
  5352. // Clear the marker.
  5353. TextMarker.prototype.clear = function() {
  5354. if (this.explicitlyCleared) return;
  5355. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5356. if (withOp) startOperation(cm);
  5357. if (hasHandler(this, "clear")) {
  5358. var found = this.find();
  5359. if (found) signalLater(this, "clear", found.from, found.to);
  5360. }
  5361. var min = null, max = null;
  5362. for (var i = 0; i < this.lines.length; ++i) {
  5363. var line = this.lines[i];
  5364. var span = getMarkedSpanFor(line.markedSpans, this);
  5365. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5366. else if (cm) {
  5367. if (span.to != null) max = lineNo(line);
  5368. if (span.from != null) min = lineNo(line);
  5369. }
  5370. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5371. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5372. updateLineHeight(line, textHeight(cm.display));
  5373. }
  5374. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5375. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5376. if (len > cm.display.maxLineLength) {
  5377. cm.display.maxLine = visual;
  5378. cm.display.maxLineLength = len;
  5379. cm.display.maxLineChanged = true;
  5380. }
  5381. }
  5382. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5383. this.lines.length = 0;
  5384. this.explicitlyCleared = true;
  5385. if (this.atomic && this.doc.cantEdit) {
  5386. this.doc.cantEdit = false;
  5387. if (cm) reCheckSelection(cm.doc);
  5388. }
  5389. if (cm) signalLater(cm, "markerCleared", cm, this);
  5390. if (withOp) endOperation(cm);
  5391. if (this.parent) this.parent.clear();
  5392. };
  5393. // Find the position of the marker in the document. Returns a {from,
  5394. // to} object by default. Side can be passed to get a specific side
  5395. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5396. // Pos objects returned contain a line object, rather than a line
  5397. // number (used to prevent looking up the same line twice).
  5398. TextMarker.prototype.find = function(side, lineObj) {
  5399. if (side == null && this.type == "bookmark") side = 1;
  5400. var from, to;
  5401. for (var i = 0; i < this.lines.length; ++i) {
  5402. var line = this.lines[i];
  5403. var span = getMarkedSpanFor(line.markedSpans, this);
  5404. if (span.from != null) {
  5405. from = Pos(lineObj ? line : lineNo(line), span.from);
  5406. if (side == -1) return from;
  5407. }
  5408. if (span.to != null) {
  5409. to = Pos(lineObj ? line : lineNo(line), span.to);
  5410. if (side == 1) return to;
  5411. }
  5412. }
  5413. return from && {from: from, to: to};
  5414. };
  5415. // Signals that the marker's widget changed, and surrounding layout
  5416. // should be recomputed.
  5417. TextMarker.prototype.changed = function() {
  5418. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5419. if (!pos || !cm) return;
  5420. runInOp(cm, function() {
  5421. var line = pos.line, lineN = lineNo(pos.line);
  5422. var view = findViewForLine(cm, lineN);
  5423. if (view) {
  5424. clearLineMeasurementCacheFor(view);
  5425. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5426. }
  5427. cm.curOp.updateMaxLine = true;
  5428. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5429. var oldHeight = widget.height;
  5430. widget.height = null;
  5431. var dHeight = widgetHeight(widget) - oldHeight;
  5432. if (dHeight)
  5433. updateLineHeight(line, line.height + dHeight);
  5434. }
  5435. });
  5436. };
  5437. TextMarker.prototype.attachLine = function(line) {
  5438. if (!this.lines.length && this.doc.cm) {
  5439. var op = this.doc.cm.curOp;
  5440. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5441. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5442. }
  5443. this.lines.push(line);
  5444. };
  5445. TextMarker.prototype.detachLine = function(line) {
  5446. this.lines.splice(indexOf(this.lines, line), 1);
  5447. if (!this.lines.length && this.doc.cm) {
  5448. var op = this.doc.cm.curOp;
  5449. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5450. }
  5451. };
  5452. // Collapsed markers have unique ids, in order to be able to order
  5453. // them, which is needed for uniquely determining an outer marker
  5454. // when they overlap (they may nest, but not partially overlap).
  5455. var nextMarkerId = 0;
  5456. // Create a marker, wire it up to the right lines, and
  5457. function markText(doc, from, to, options, type) {
  5458. // Shared markers (across linked documents) are handled separately
  5459. // (markTextShared will call out to this again, once per
  5460. // document).
  5461. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5462. // Ensure we are in an operation.
  5463. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5464. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5465. if (options) copyObj(options, marker, false);
  5466. // Don't connect empty markers unless clearWhenEmpty is false
  5467. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5468. return marker;
  5469. if (marker.replacedWith) {
  5470. // Showing up as a widget implies collapsed (widget replaces text)
  5471. marker.collapsed = true;
  5472. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5473. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5474. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5475. }
  5476. if (marker.collapsed) {
  5477. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5478. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5479. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5480. sawCollapsedSpans = true;
  5481. }
  5482. if (marker.addToHistory)
  5483. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  5484. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5485. doc.iter(curLine, to.line + 1, function(line) {
  5486. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5487. updateMaxLine = true;
  5488. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5489. addMarkedSpan(line, new MarkedSpan(marker,
  5490. curLine == from.line ? from.ch : null,
  5491. curLine == to.line ? to.ch : null));
  5492. ++curLine;
  5493. });
  5494. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5495. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  5496. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5497. });
  5498. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  5499. if (marker.readOnly) {
  5500. sawReadOnlySpans = true;
  5501. if (doc.history.done.length || doc.history.undone.length)
  5502. doc.clearHistory();
  5503. }
  5504. if (marker.collapsed) {
  5505. marker.id = ++nextMarkerId;
  5506. marker.atomic = true;
  5507. }
  5508. if (cm) {
  5509. // Sync editor state
  5510. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5511. if (marker.collapsed)
  5512. regChange(cm, from.line, to.line + 1);
  5513. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5514. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5515. if (marker.atomic) reCheckSelection(cm.doc);
  5516. signalLater(cm, "markerAdded", cm, marker);
  5517. }
  5518. return marker;
  5519. }
  5520. // SHARED TEXTMARKERS
  5521. // A shared marker spans multiple linked documents. It is
  5522. // implemented as a meta-marker-object controlling multiple normal
  5523. // markers.
  5524. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  5525. this.markers = markers;
  5526. this.primary = primary;
  5527. for (var i = 0; i < markers.length; ++i)
  5528. markers[i].parent = this;
  5529. };
  5530. eventMixin(SharedTextMarker);
  5531. SharedTextMarker.prototype.clear = function() {
  5532. if (this.explicitlyCleared) return;
  5533. this.explicitlyCleared = true;
  5534. for (var i = 0; i < this.markers.length; ++i)
  5535. this.markers[i].clear();
  5536. signalLater(this, "clear");
  5537. };
  5538. SharedTextMarker.prototype.find = function(side, lineObj) {
  5539. return this.primary.find(side, lineObj);
  5540. };
  5541. function markTextShared(doc, from, to, options, type) {
  5542. options = copyObj(options);
  5543. options.shared = false;
  5544. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5545. var widget = options.widgetNode;
  5546. linkedDocs(doc, function(doc) {
  5547. if (widget) options.widgetNode = widget.cloneNode(true);
  5548. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5549. for (var i = 0; i < doc.linked.length; ++i)
  5550. if (doc.linked[i].isParent) return;
  5551. primary = lst(markers);
  5552. });
  5553. return new SharedTextMarker(markers, primary);
  5554. }
  5555. function findSharedMarkers(doc) {
  5556. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5557. function(m) { return m.parent; });
  5558. }
  5559. function copySharedMarkers(doc, markers) {
  5560. for (var i = 0; i < markers.length; i++) {
  5561. var marker = markers[i], pos = marker.find();
  5562. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5563. if (cmp(mFrom, mTo)) {
  5564. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5565. marker.markers.push(subMark);
  5566. subMark.parent = marker;
  5567. }
  5568. }
  5569. }
  5570. function detachSharedMarkers(markers) {
  5571. for (var i = 0; i < markers.length; i++) {
  5572. var marker = markers[i], linked = [marker.primary.doc];;
  5573. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5574. for (var j = 0; j < marker.markers.length; j++) {
  5575. var subMarker = marker.markers[j];
  5576. if (indexOf(linked, subMarker.doc) == -1) {
  5577. subMarker.parent = null;
  5578. marker.markers.splice(j--, 1);
  5579. }
  5580. }
  5581. }
  5582. }
  5583. // TEXTMARKER SPANS
  5584. function MarkedSpan(marker, from, to) {
  5585. this.marker = marker;
  5586. this.from = from; this.to = to;
  5587. }
  5588. // Search an array of spans for a span matching the given marker.
  5589. function getMarkedSpanFor(spans, marker) {
  5590. if (spans) for (var i = 0; i < spans.length; ++i) {
  5591. var span = spans[i];
  5592. if (span.marker == marker) return span;
  5593. }
  5594. }
  5595. // Remove a span from an array, returning undefined if no spans are
  5596. // left (we don't store arrays for lines without spans).
  5597. function removeMarkedSpan(spans, span) {
  5598. for (var r, i = 0; i < spans.length; ++i)
  5599. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5600. return r;
  5601. }
  5602. // Add a span to a line.
  5603. function addMarkedSpan(line, span) {
  5604. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5605. span.marker.attachLine(line);
  5606. }
  5607. // Used for the algorithm that adjusts markers for a change in the
  5608. // document. These functions cut an array of spans at a given
  5609. // character position, returning an array of remaining chunks (or
  5610. // undefined if nothing remains).
  5611. function markedSpansBefore(old, startCh, isInsert) {
  5612. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5613. var span = old[i], marker = span.marker;
  5614. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5615. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5616. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5617. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5618. }
  5619. }
  5620. return nw;
  5621. }
  5622. function markedSpansAfter(old, endCh, isInsert) {
  5623. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5624. var span = old[i], marker = span.marker;
  5625. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5626. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5627. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5628. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5629. span.to == null ? null : span.to - endCh));
  5630. }
  5631. }
  5632. return nw;
  5633. }
  5634. // Given a change object, compute the new set of marker spans that
  5635. // cover the line in which the change took place. Removes spans
  5636. // entirely within the change, reconnects spans belonging to the
  5637. // same marker that appear on both sides of the change, and cuts off
  5638. // spans partially within the change. Returns an array of span
  5639. // arrays with one element for each line in (after) the change.
  5640. function stretchSpansOverChange(doc, change) {
  5641. if (change.full) return null;
  5642. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5643. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5644. if (!oldFirst && !oldLast) return null;
  5645. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5646. // Get the spans that 'stick out' on both sides
  5647. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5648. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5649. // Next, merge those two ends
  5650. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5651. if (first) {
  5652. // Fix up .to properties of first
  5653. for (var i = 0; i < first.length; ++i) {
  5654. var span = first[i];
  5655. if (span.to == null) {
  5656. var found = getMarkedSpanFor(last, span.marker);
  5657. if (!found) span.to = startCh;
  5658. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5659. }
  5660. }
  5661. }
  5662. if (last) {
  5663. // Fix up .from in last (or move them into first in case of sameLine)
  5664. for (var i = 0; i < last.length; ++i) {
  5665. var span = last[i];
  5666. if (span.to != null) span.to += offset;
  5667. if (span.from == null) {
  5668. var found = getMarkedSpanFor(first, span.marker);
  5669. if (!found) {
  5670. span.from = offset;
  5671. if (sameLine) (first || (first = [])).push(span);
  5672. }
  5673. } else {
  5674. span.from += offset;
  5675. if (sameLine) (first || (first = [])).push(span);
  5676. }
  5677. }
  5678. }
  5679. // Make sure we didn't create any zero-length spans
  5680. if (first) first = clearEmptySpans(first);
  5681. if (last && last != first) last = clearEmptySpans(last);
  5682. var newMarkers = [first];
  5683. if (!sameLine) {
  5684. // Fill gap with whole-line-spans
  5685. var gap = change.text.length - 2, gapMarkers;
  5686. if (gap > 0 && first)
  5687. for (var i = 0; i < first.length; ++i)
  5688. if (first[i].to == null)
  5689. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5690. for (var i = 0; i < gap; ++i)
  5691. newMarkers.push(gapMarkers);
  5692. newMarkers.push(last);
  5693. }
  5694. return newMarkers;
  5695. }
  5696. // Remove spans that are empty and don't have a clearWhenEmpty
  5697. // option of false.
  5698. function clearEmptySpans(spans) {
  5699. for (var i = 0; i < spans.length; ++i) {
  5700. var span = spans[i];
  5701. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5702. spans.splice(i--, 1);
  5703. }
  5704. if (!spans.length) return null;
  5705. return spans;
  5706. }
  5707. // Used for un/re-doing changes from the history. Combines the
  5708. // result of computing the existing spans with the set of spans that
  5709. // existed in the history (so that deleting around a span and then
  5710. // undoing brings back the span).
  5711. function mergeOldSpans(doc, change) {
  5712. var old = getOldSpans(doc, change);
  5713. var stretched = stretchSpansOverChange(doc, change);
  5714. if (!old) return stretched;
  5715. if (!stretched) return old;
  5716. for (var i = 0; i < old.length; ++i) {
  5717. var oldCur = old[i], stretchCur = stretched[i];
  5718. if (oldCur && stretchCur) {
  5719. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5720. var span = stretchCur[j];
  5721. for (var k = 0; k < oldCur.length; ++k)
  5722. if (oldCur[k].marker == span.marker) continue spans;
  5723. oldCur.push(span);
  5724. }
  5725. } else if (stretchCur) {
  5726. old[i] = stretchCur;
  5727. }
  5728. }
  5729. return old;
  5730. }
  5731. // Used to 'clip' out readOnly ranges when making a change.
  5732. function removeReadOnlyRanges(doc, from, to) {
  5733. var markers = null;
  5734. doc.iter(from.line, to.line + 1, function(line) {
  5735. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5736. var mark = line.markedSpans[i].marker;
  5737. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5738. (markers || (markers = [])).push(mark);
  5739. }
  5740. });
  5741. if (!markers) return null;
  5742. var parts = [{from: from, to: to}];
  5743. for (var i = 0; i < markers.length; ++i) {
  5744. var mk = markers[i], m = mk.find(0);
  5745. for (var j = 0; j < parts.length; ++j) {
  5746. var p = parts[j];
  5747. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5748. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5749. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5750. newParts.push({from: p.from, to: m.from});
  5751. if (dto > 0 || !mk.inclusiveRight && !dto)
  5752. newParts.push({from: m.to, to: p.to});
  5753. parts.splice.apply(parts, newParts);
  5754. j += newParts.length - 1;
  5755. }
  5756. }
  5757. return parts;
  5758. }
  5759. // Connect or disconnect spans from a line.
  5760. function detachMarkedSpans(line) {
  5761. var spans = line.markedSpans;
  5762. if (!spans) return;
  5763. for (var i = 0; i < spans.length; ++i)
  5764. spans[i].marker.detachLine(line);
  5765. line.markedSpans = null;
  5766. }
  5767. function attachMarkedSpans(line, spans) {
  5768. if (!spans) return;
  5769. for (var i = 0; i < spans.length; ++i)
  5770. spans[i].marker.attachLine(line);
  5771. line.markedSpans = spans;
  5772. }
  5773. // Helpers used when computing which overlapping collapsed span
  5774. // counts as the larger one.
  5775. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5776. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5777. // Returns a number indicating which of two overlapping collapsed
  5778. // spans is larger (and thus includes the other). Falls back to
  5779. // comparing ids when the spans cover exactly the same range.
  5780. function compareCollapsedMarkers(a, b) {
  5781. var lenDiff = a.lines.length - b.lines.length;
  5782. if (lenDiff != 0) return lenDiff;
  5783. var aPos = a.find(), bPos = b.find();
  5784. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5785. if (fromCmp) return -fromCmp;
  5786. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5787. if (toCmp) return toCmp;
  5788. return b.id - a.id;
  5789. }
  5790. // Find out whether a line ends or starts in a collapsed span. If
  5791. // so, return the marker for that span.
  5792. function collapsedSpanAtSide(line, start) {
  5793. var sps = sawCollapsedSpans && line.markedSpans, found;
  5794. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5795. sp = sps[i];
  5796. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5797. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5798. found = sp.marker;
  5799. }
  5800. return found;
  5801. }
  5802. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5803. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5804. // Test whether there exists a collapsed span that partially
  5805. // overlaps (covers the start or end, but not both) of a new span.
  5806. // Such overlap is not allowed.
  5807. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5808. var line = getLine(doc, lineNo);
  5809. var sps = sawCollapsedSpans && line.markedSpans;
  5810. if (sps) for (var i = 0; i < sps.length; ++i) {
  5811. var sp = sps[i];
  5812. if (!sp.marker.collapsed) continue;
  5813. var found = sp.marker.find(0);
  5814. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5815. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5816. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5817. if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
  5818. fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
  5819. return true;
  5820. }
  5821. }
  5822. // A visual line is a line as drawn on the screen. Folding, for
  5823. // example, can cause multiple logical lines to appear on the same
  5824. // visual line. This finds the start of the visual line that the
  5825. // given line is part of (usually that is the line itself).
  5826. function visualLine(line) {
  5827. var merged;
  5828. while (merged = collapsedSpanAtStart(line))
  5829. line = merged.find(-1, true).line;
  5830. return line;
  5831. }
  5832. // Returns an array of logical lines that continue the visual line
  5833. // started by the argument, or undefined if there are no such lines.
  5834. function visualLineContinued(line) {
  5835. var merged, lines;
  5836. while (merged = collapsedSpanAtEnd(line)) {
  5837. line = merged.find(1, true).line;
  5838. (lines || (lines = [])).push(line);
  5839. }
  5840. return lines;
  5841. }
  5842. // Get the line number of the start of the visual line that the
  5843. // given line number is part of.
  5844. function visualLineNo(doc, lineN) {
  5845. var line = getLine(doc, lineN), vis = visualLine(line);
  5846. if (line == vis) return lineN;
  5847. return lineNo(vis);
  5848. }
  5849. // Get the line number of the start of the next visual line after
  5850. // the given line.
  5851. function visualLineEndNo(doc, lineN) {
  5852. if (lineN > doc.lastLine()) return lineN;
  5853. var line = getLine(doc, lineN), merged;
  5854. if (!lineIsHidden(doc, line)) return lineN;
  5855. while (merged = collapsedSpanAtEnd(line))
  5856. line = merged.find(1, true).line;
  5857. return lineNo(line) + 1;
  5858. }
  5859. // Compute whether a line is hidden. Lines count as hidden when they
  5860. // are part of a visual line that starts with another line, or when
  5861. // they are entirely covered by collapsed, non-widget span.
  5862. function lineIsHidden(doc, line) {
  5863. var sps = sawCollapsedSpans && line.markedSpans;
  5864. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5865. sp = sps[i];
  5866. if (!sp.marker.collapsed) continue;
  5867. if (sp.from == null) return true;
  5868. if (sp.marker.widgetNode) continue;
  5869. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5870. return true;
  5871. }
  5872. }
  5873. function lineIsHiddenInner(doc, line, span) {
  5874. if (span.to == null) {
  5875. var end = span.marker.find(1, true);
  5876. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5877. }
  5878. if (span.marker.inclusiveRight && span.to == line.text.length)
  5879. return true;
  5880. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5881. sp = line.markedSpans[i];
  5882. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5883. (sp.to == null || sp.to != span.from) &&
  5884. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5885. lineIsHiddenInner(doc, line, sp)) return true;
  5886. }
  5887. }
  5888. // LINE WIDGETS
  5889. // Line widgets are block elements displayed above or below a line.
  5890. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  5891. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  5892. this[opt] = options[opt];
  5893. this.doc = doc;
  5894. this.node = node;
  5895. };
  5896. eventMixin(LineWidget);
  5897. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5898. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5899. addToScrollPos(cm, null, diff);
  5900. }
  5901. LineWidget.prototype.clear = function() {
  5902. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5903. if (no == null || !ws) return;
  5904. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  5905. if (!ws.length) line.widgets = null;
  5906. var height = widgetHeight(this);
  5907. updateLineHeight(line, Math.max(0, line.height - height));
  5908. if (cm) runInOp(cm, function() {
  5909. adjustScrollWhenAboveVisible(cm, line, -height);
  5910. regLineChange(cm, no, "widget");
  5911. });
  5912. };
  5913. LineWidget.prototype.changed = function() {
  5914. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5915. this.height = null;
  5916. var diff = widgetHeight(this) - oldH;
  5917. if (!diff) return;
  5918. updateLineHeight(line, line.height + diff);
  5919. if (cm) runInOp(cm, function() {
  5920. cm.curOp.forceUpdate = true;
  5921. adjustScrollWhenAboveVisible(cm, line, diff);
  5922. });
  5923. };
  5924. function widgetHeight(widget) {
  5925. if (widget.height != null) return widget.height;
  5926. var cm = widget.doc.cm;
  5927. if (!cm) return 0;
  5928. if (!contains(document.body, widget.node)) {
  5929. var parentStyle = "position: relative;";
  5930. if (widget.coverGutter)
  5931. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  5932. if (widget.noHScroll)
  5933. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  5934. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  5935. }
  5936. return widget.height = widget.node.offsetHeight;
  5937. }
  5938. function addLineWidget(doc, handle, node, options) {
  5939. var widget = new LineWidget(doc, node, options);
  5940. var cm = doc.cm;
  5941. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  5942. changeLine(doc, handle, "widget", function(line) {
  5943. var widgets = line.widgets || (line.widgets = []);
  5944. if (widget.insertAt == null) widgets.push(widget);
  5945. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  5946. widget.line = line;
  5947. if (cm && !lineIsHidden(doc, line)) {
  5948. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5949. updateLineHeight(line, line.height + widgetHeight(widget));
  5950. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  5951. cm.curOp.forceUpdate = true;
  5952. }
  5953. return true;
  5954. });
  5955. return widget;
  5956. }
  5957. // LINE DATA STRUCTURE
  5958. // Line objects. These hold state related to a line, including
  5959. // highlighting info (the styles array).
  5960. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  5961. this.text = text;
  5962. attachMarkedSpans(this, markedSpans);
  5963. this.height = estimateHeight ? estimateHeight(this) : 1;
  5964. };
  5965. eventMixin(Line);
  5966. Line.prototype.lineNo = function() { return lineNo(this); };
  5967. // Change the content (text, markers) of a line. Automatically
  5968. // invalidates cached information and tries to re-estimate the
  5969. // line's height.
  5970. function updateLine(line, text, markedSpans, estimateHeight) {
  5971. line.text = text;
  5972. if (line.stateAfter) line.stateAfter = null;
  5973. if (line.styles) line.styles = null;
  5974. if (line.order != null) line.order = null;
  5975. detachMarkedSpans(line);
  5976. attachMarkedSpans(line, markedSpans);
  5977. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  5978. if (estHeight != line.height) updateLineHeight(line, estHeight);
  5979. }
  5980. // Detach a line from the document tree and its markers.
  5981. function cleanUpLine(line) {
  5982. line.parent = null;
  5983. detachMarkedSpans(line);
  5984. }
  5985. function extractLineClasses(type, output) {
  5986. if (type) for (;;) {
  5987. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  5988. if (!lineClass) break;
  5989. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  5990. var prop = lineClass[1] ? "bgClass" : "textClass";
  5991. if (output[prop] == null)
  5992. output[prop] = lineClass[2];
  5993. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  5994. output[prop] += " " + lineClass[2];
  5995. }
  5996. return type;
  5997. }
  5998. function callBlankLine(mode, state) {
  5999. if (mode.blankLine) return mode.blankLine(state);
  6000. if (!mode.innerMode) return;
  6001. var inner = CodeMirror.innerMode(mode, state);
  6002. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  6003. }
  6004. function readToken(mode, stream, state, inner) {
  6005. for (var i = 0; i < 10; i++) {
  6006. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  6007. var style = mode.token(stream, state);
  6008. if (stream.pos > stream.start) return style;
  6009. }
  6010. throw new Error("Mode " + mode.name + " failed to advance stream.");
  6011. }
  6012. // Utility for getTokenAt and getLineTokens
  6013. function takeToken(cm, pos, precise, asArray) {
  6014. function getObj(copy) {
  6015. return {start: stream.start, end: stream.pos,
  6016. string: stream.current(),
  6017. type: style || null,
  6018. state: copy ? copyState(doc.mode, state) : state};
  6019. }
  6020. var doc = cm.doc, mode = doc.mode, style;
  6021. pos = clipPos(doc, pos);
  6022. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  6023. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  6024. if (asArray) tokens = [];
  6025. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  6026. stream.start = stream.pos;
  6027. style = readToken(mode, stream, state);
  6028. if (asArray) tokens.push(getObj(true));
  6029. }
  6030. return asArray ? tokens : getObj();
  6031. }
  6032. // Run the given mode's parser over a line, calling f for each token.
  6033. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  6034. var flattenSpans = mode.flattenSpans;
  6035. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  6036. var curStart = 0, curStyle = null;
  6037. var stream = new StringStream(text, cm.options.tabSize), style;
  6038. var inner = cm.options.addModeClass && [null];
  6039. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  6040. while (!stream.eol()) {
  6041. if (stream.pos > cm.options.maxHighlightLength) {
  6042. flattenSpans = false;
  6043. if (forceToEnd) processLine(cm, text, state, stream.pos);
  6044. stream.pos = text.length;
  6045. style = null;
  6046. } else {
  6047. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  6048. }
  6049. if (inner) {
  6050. var mName = inner[0].name;
  6051. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  6052. }
  6053. if (!flattenSpans || curStyle != style) {
  6054. while (curStart < stream.start) {
  6055. curStart = Math.min(stream.start, curStart + 50000);
  6056. f(curStart, curStyle);
  6057. }
  6058. curStyle = style;
  6059. }
  6060. stream.start = stream.pos;
  6061. }
  6062. while (curStart < stream.pos) {
  6063. // Webkit seems to refuse to render text nodes longer than 57444 characters
  6064. var pos = Math.min(stream.pos, curStart + 50000);
  6065. f(pos, curStyle);
  6066. curStart = pos;
  6067. }
  6068. }
  6069. // Compute a style array (an array starting with a mode generation
  6070. // -- for invalidation -- followed by pairs of end positions and
  6071. // style strings), which is used to highlight the tokens on the
  6072. // line.
  6073. function highlightLine(cm, line, state, forceToEnd) {
  6074. // A styles array always starts with a number identifying the
  6075. // mode/overlays that it is based on (for easy invalidation).
  6076. var st = [cm.state.modeGen], lineClasses = {};
  6077. // Compute the base array of styles
  6078. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  6079. st.push(end, style);
  6080. }, lineClasses, forceToEnd);
  6081. // Run overlays, adjust style array.
  6082. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6083. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6084. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  6085. var start = i;
  6086. // Ensure there's a token end at the current position, and that i points at it
  6087. while (at < end) {
  6088. var i_end = st[i];
  6089. if (i_end > end)
  6090. st.splice(i, 1, end, st[i+1], i_end);
  6091. i += 2;
  6092. at = Math.min(end, i_end);
  6093. }
  6094. if (!style) return;
  6095. if (overlay.opaque) {
  6096. st.splice(start, i - start, end, "cm-overlay " + style);
  6097. i = start + 2;
  6098. } else {
  6099. for (; start < i; start += 2) {
  6100. var cur = st[start+1];
  6101. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6102. }
  6103. }
  6104. }, lineClasses);
  6105. }
  6106. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  6107. }
  6108. function getLineStyles(cm, line, updateFrontier) {
  6109. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6110. var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  6111. line.styles = result.styles;
  6112. if (result.classes) line.styleClasses = result.classes;
  6113. else if (line.styleClasses) line.styleClasses = null;
  6114. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6115. }
  6116. return line.styles;
  6117. }
  6118. // Lightweight form of highlight -- proceed over this line and
  6119. // update state, but don't save a style array. Used for lines that
  6120. // aren't currently visible.
  6121. function processLine(cm, text, state, startAt) {
  6122. var mode = cm.doc.mode;
  6123. var stream = new StringStream(text, cm.options.tabSize);
  6124. stream.start = stream.pos = startAt || 0;
  6125. if (text == "") callBlankLine(mode, state);
  6126. while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
  6127. readToken(mode, stream, state);
  6128. stream.start = stream.pos;
  6129. }
  6130. }
  6131. // Convert a style as returned by a mode (either null, or a string
  6132. // containing one or more styles) to a CSS style. This is cached,
  6133. // and also looks for line-wide styles.
  6134. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6135. function interpretTokenStyle(style, options) {
  6136. if (!style || /^\s*$/.test(style)) return null;
  6137. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6138. return cache[style] ||
  6139. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6140. }
  6141. // Render the DOM representation of the text of a line. Also builds
  6142. // up a 'line map', which points at the DOM nodes that represent
  6143. // specific stretches of text, and is used by the measuring code.
  6144. // The returned object contains the DOM node, this map, and
  6145. // information about line-wide styles that were set by the mode.
  6146. function buildLineContent(cm, lineView) {
  6147. // The padding-right forces the element to have a 'border', which
  6148. // is needed on Webkit to be able to get line-level bounding
  6149. // rectangles for it (in measureChar).
  6150. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6151. var builder = {pre: elt("pre", [content]), content: content,
  6152. col: 0, pos: 0, cm: cm,
  6153. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  6154. lineView.measure = {};
  6155. // Iterate over the logical lines that make up this visual line.
  6156. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6157. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6158. builder.pos = 0;
  6159. builder.addToken = buildToken;
  6160. // Optionally wire in some hacks into the token-rendering
  6161. // algorithm, to deal with browser quirks.
  6162. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6163. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6164. builder.map = [];
  6165. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6166. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6167. if (line.styleClasses) {
  6168. if (line.styleClasses.bgClass)
  6169. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6170. if (line.styleClasses.textClass)
  6171. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6172. }
  6173. // Ensure at least a single node is present, for measuring.
  6174. if (builder.map.length == 0)
  6175. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6176. // Store the map and a cache object for the current logical line
  6177. if (i == 0) {
  6178. lineView.measure.map = builder.map;
  6179. lineView.measure.cache = {};
  6180. } else {
  6181. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6182. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6183. }
  6184. }
  6185. // See issue #2901
  6186. if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
  6187. builder.content.className = "cm-tab-wrap-hack";
  6188. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6189. if (builder.pre.className)
  6190. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6191. return builder;
  6192. }
  6193. function defaultSpecialCharPlaceholder(ch) {
  6194. var token = elt("span", "\u2022", "cm-invalidchar");
  6195. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6196. token.setAttribute("aria-label", token.title);
  6197. return token;
  6198. }
  6199. // Build up the DOM representation for a single token, and add it to
  6200. // the line map. Takes care to render special characters separately.
  6201. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6202. if (!text) return;
  6203. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  6204. var special = builder.cm.state.specialChars, mustWrap = false;
  6205. if (!special.test(text)) {
  6206. builder.col += text.length;
  6207. var content = document.createTextNode(displayText);
  6208. builder.map.push(builder.pos, builder.pos + text.length, content);
  6209. if (ie && ie_version < 9) mustWrap = true;
  6210. builder.pos += text.length;
  6211. } else {
  6212. var content = document.createDocumentFragment(), pos = 0;
  6213. while (true) {
  6214. special.lastIndex = pos;
  6215. var m = special.exec(text);
  6216. var skipped = m ? m.index - pos : text.length - pos;
  6217. if (skipped) {
  6218. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  6219. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6220. else content.appendChild(txt);
  6221. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6222. builder.col += skipped;
  6223. builder.pos += skipped;
  6224. }
  6225. if (!m) break;
  6226. pos += skipped + 1;
  6227. if (m[0] == "\t") {
  6228. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6229. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6230. txt.setAttribute("role", "presentation");
  6231. txt.setAttribute("cm-text", "\t");
  6232. builder.col += tabWidth;
  6233. } else {
  6234. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6235. txt.setAttribute("cm-text", m[0]);
  6236. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6237. else content.appendChild(txt);
  6238. builder.col += 1;
  6239. }
  6240. builder.map.push(builder.pos, builder.pos + 1, txt);
  6241. builder.pos++;
  6242. }
  6243. }
  6244. if (style || startStyle || endStyle || mustWrap || css) {
  6245. var fullStyle = style || "";
  6246. if (startStyle) fullStyle += startStyle;
  6247. if (endStyle) fullStyle += endStyle;
  6248. var token = elt("span", [content], fullStyle, css);
  6249. if (title) token.title = title;
  6250. return builder.content.appendChild(token);
  6251. }
  6252. builder.content.appendChild(content);
  6253. }
  6254. function splitSpaces(old) {
  6255. var out = " ";
  6256. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  6257. out += " ";
  6258. return out;
  6259. }
  6260. // Work around nonsense dimensions being reported for stretches of
  6261. // right-to-left text.
  6262. function buildTokenBadBidi(inner, order) {
  6263. return function(builder, text, style, startStyle, endStyle, title, css) {
  6264. style = style ? style + " cm-force-border" : "cm-force-border";
  6265. var start = builder.pos, end = start + text.length;
  6266. for (;;) {
  6267. // Find the part that overlaps with the start of this text
  6268. for (var i = 0; i < order.length; i++) {
  6269. var part = order[i];
  6270. if (part.to > start && part.from <= start) break;
  6271. }
  6272. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  6273. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  6274. startStyle = null;
  6275. text = text.slice(part.to - start);
  6276. start = part.to;
  6277. }
  6278. };
  6279. }
  6280. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6281. var widget = !ignoreWidget && marker.widgetNode;
  6282. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6283. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6284. if (!widget)
  6285. widget = builder.content.appendChild(document.createElement("span"));
  6286. widget.setAttribute("cm-marker", marker.id);
  6287. }
  6288. if (widget) {
  6289. builder.cm.display.input.setUneditable(widget);
  6290. builder.content.appendChild(widget);
  6291. }
  6292. builder.pos += size;
  6293. }
  6294. // Outputs a number of spans to make up a line, taking highlighting
  6295. // and marked text into account.
  6296. function insertLineContent(line, builder, styles) {
  6297. var spans = line.markedSpans, allText = line.text, at = 0;
  6298. if (!spans) {
  6299. for (var i = 1; i < styles.length; i+=2)
  6300. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  6301. return;
  6302. }
  6303. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6304. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6305. for (;;) {
  6306. if (nextChange == pos) { // Update current marker set
  6307. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6308. collapsed = null; nextChange = Infinity;
  6309. var foundBookmarks = [];
  6310. for (var j = 0; j < spans.length; ++j) {
  6311. var sp = spans[j], m = sp.marker;
  6312. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  6313. foundBookmarks.push(m);
  6314. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  6315. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  6316. nextChange = sp.to;
  6317. spanEndStyle = "";
  6318. }
  6319. if (m.className) spanStyle += " " + m.className;
  6320. if (m.css) css = m.css;
  6321. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6322. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  6323. if (m.title && !title) title = m.title;
  6324. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6325. collapsed = sp;
  6326. } else if (sp.from > pos && nextChange > sp.from) {
  6327. nextChange = sp.from;
  6328. }
  6329. }
  6330. if (collapsed && (collapsed.from || 0) == pos) {
  6331. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6332. collapsed.marker, collapsed.from == null);
  6333. if (collapsed.to == null) return;
  6334. if (collapsed.to == pos) collapsed = false;
  6335. }
  6336. if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
  6337. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6338. }
  6339. if (pos >= len) break;
  6340. var upto = Math.min(len, nextChange);
  6341. while (true) {
  6342. if (text) {
  6343. var end = pos + text.length;
  6344. if (!collapsed) {
  6345. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6346. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6347. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6348. }
  6349. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  6350. pos = end;
  6351. spanStartStyle = "";
  6352. }
  6353. text = allText.slice(at, at = styles[i++]);
  6354. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6355. }
  6356. }
  6357. }
  6358. // DOCUMENT DATA STRUCTURE
  6359. // By default, updates that start and end at the beginning of a line
  6360. // are treated specially, in order to make the association of line
  6361. // widgets and marker elements with the text behave more intuitive.
  6362. function isWholeLineUpdate(doc, change) {
  6363. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6364. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6365. }
  6366. // Perform a change on the document data structure.
  6367. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6368. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  6369. function update(line, text, spans) {
  6370. updateLine(line, text, spans, estimateHeight);
  6371. signalLater(line, "change", line, change);
  6372. }
  6373. function linesFor(start, end) {
  6374. for (var i = start, result = []; i < end; ++i)
  6375. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6376. return result;
  6377. }
  6378. var from = change.from, to = change.to, text = change.text;
  6379. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6380. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6381. // Adjust the line structure
  6382. if (change.full) {
  6383. doc.insert(0, linesFor(0, text.length));
  6384. doc.remove(text.length, doc.size - text.length);
  6385. } else if (isWholeLineUpdate(doc, change)) {
  6386. // This is a whole-line replace. Treated specially to make
  6387. // sure line objects move the way they are supposed to.
  6388. var added = linesFor(0, text.length - 1);
  6389. update(lastLine, lastLine.text, lastSpans);
  6390. if (nlines) doc.remove(from.line, nlines);
  6391. if (added.length) doc.insert(from.line, added);
  6392. } else if (firstLine == lastLine) {
  6393. if (text.length == 1) {
  6394. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6395. } else {
  6396. var added = linesFor(1, text.length - 1);
  6397. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6398. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6399. doc.insert(from.line + 1, added);
  6400. }
  6401. } else if (text.length == 1) {
  6402. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6403. doc.remove(from.line + 1, nlines);
  6404. } else {
  6405. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6406. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6407. var added = linesFor(1, text.length - 1);
  6408. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6409. doc.insert(from.line + 1, added);
  6410. }
  6411. signalLater(doc, "change", doc, change);
  6412. }
  6413. // The document is represented as a BTree consisting of leaves, with
  6414. // chunk of lines in them, and branches, with up to ten leaves or
  6415. // other branch nodes below them. The top node is always a branch
  6416. // node, and is the document object itself (meaning it has
  6417. // additional methods and properties).
  6418. //
  6419. // All nodes have parent links. The tree is used both to go from
  6420. // line numbers to line objects, and to go from objects to numbers.
  6421. // It also indexes by height, and is used to convert between height
  6422. // and line object, and to find the total height of the document.
  6423. //
  6424. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6425. function LeafChunk(lines) {
  6426. this.lines = lines;
  6427. this.parent = null;
  6428. for (var i = 0, height = 0; i < lines.length; ++i) {
  6429. lines[i].parent = this;
  6430. height += lines[i].height;
  6431. }
  6432. this.height = height;
  6433. }
  6434. LeafChunk.prototype = {
  6435. chunkSize: function() { return this.lines.length; },
  6436. // Remove the n lines at offset 'at'.
  6437. removeInner: function(at, n) {
  6438. for (var i = at, e = at + n; i < e; ++i) {
  6439. var line = this.lines[i];
  6440. this.height -= line.height;
  6441. cleanUpLine(line);
  6442. signalLater(line, "delete");
  6443. }
  6444. this.lines.splice(at, n);
  6445. },
  6446. // Helper used to collapse a small branch into a single leaf.
  6447. collapse: function(lines) {
  6448. lines.push.apply(lines, this.lines);
  6449. },
  6450. // Insert the given array of lines at offset 'at', count them as
  6451. // having the given height.
  6452. insertInner: function(at, lines, height) {
  6453. this.height += height;
  6454. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6455. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6456. },
  6457. // Used to iterate over a part of the tree.
  6458. iterN: function(at, n, op) {
  6459. for (var e = at + n; at < e; ++at)
  6460. if (op(this.lines[at])) return true;
  6461. }
  6462. };
  6463. function BranchChunk(children) {
  6464. this.children = children;
  6465. var size = 0, height = 0;
  6466. for (var i = 0; i < children.length; ++i) {
  6467. var ch = children[i];
  6468. size += ch.chunkSize(); height += ch.height;
  6469. ch.parent = this;
  6470. }
  6471. this.size = size;
  6472. this.height = height;
  6473. this.parent = null;
  6474. }
  6475. BranchChunk.prototype = {
  6476. chunkSize: function() { return this.size; },
  6477. removeInner: function(at, n) {
  6478. this.size -= n;
  6479. for (var i = 0; i < this.children.length; ++i) {
  6480. var child = this.children[i], sz = child.chunkSize();
  6481. if (at < sz) {
  6482. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6483. child.removeInner(at, rm);
  6484. this.height -= oldHeight - child.height;
  6485. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6486. if ((n -= rm) == 0) break;
  6487. at = 0;
  6488. } else at -= sz;
  6489. }
  6490. // If the result is smaller than 25 lines, ensure that it is a
  6491. // single leaf node.
  6492. if (this.size - n < 25 &&
  6493. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6494. var lines = [];
  6495. this.collapse(lines);
  6496. this.children = [new LeafChunk(lines)];
  6497. this.children[0].parent = this;
  6498. }
  6499. },
  6500. collapse: function(lines) {
  6501. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6502. },
  6503. insertInner: function(at, lines, height) {
  6504. this.size += lines.length;
  6505. this.height += height;
  6506. for (var i = 0; i < this.children.length; ++i) {
  6507. var child = this.children[i], sz = child.chunkSize();
  6508. if (at <= sz) {
  6509. child.insertInner(at, lines, height);
  6510. if (child.lines && child.lines.length > 50) {
  6511. while (child.lines.length > 50) {
  6512. var spilled = child.lines.splice(child.lines.length - 25, 25);
  6513. var newleaf = new LeafChunk(spilled);
  6514. child.height -= newleaf.height;
  6515. this.children.splice(i + 1, 0, newleaf);
  6516. newleaf.parent = this;
  6517. }
  6518. this.maybeSpill();
  6519. }
  6520. break;
  6521. }
  6522. at -= sz;
  6523. }
  6524. },
  6525. // When a node has grown, check whether it should be split.
  6526. maybeSpill: function() {
  6527. if (this.children.length <= 10) return;
  6528. var me = this;
  6529. do {
  6530. var spilled = me.children.splice(me.children.length - 5, 5);
  6531. var sibling = new BranchChunk(spilled);
  6532. if (!me.parent) { // Become the parent node
  6533. var copy = new BranchChunk(me.children);
  6534. copy.parent = me;
  6535. me.children = [copy, sibling];
  6536. me = copy;
  6537. } else {
  6538. me.size -= sibling.size;
  6539. me.height -= sibling.height;
  6540. var myIndex = indexOf(me.parent.children, me);
  6541. me.parent.children.splice(myIndex + 1, 0, sibling);
  6542. }
  6543. sibling.parent = me.parent;
  6544. } while (me.children.length > 10);
  6545. me.parent.maybeSpill();
  6546. },
  6547. iterN: function(at, n, op) {
  6548. for (var i = 0; i < this.children.length; ++i) {
  6549. var child = this.children[i], sz = child.chunkSize();
  6550. if (at < sz) {
  6551. var used = Math.min(n, sz - at);
  6552. if (child.iterN(at, used, op)) return true;
  6553. if ((n -= used) == 0) break;
  6554. at = 0;
  6555. } else at -= sz;
  6556. }
  6557. }
  6558. };
  6559. var nextDocId = 0;
  6560. var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
  6561. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  6562. if (firstLine == null) firstLine = 0;
  6563. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6564. this.first = firstLine;
  6565. this.scrollTop = this.scrollLeft = 0;
  6566. this.cantEdit = false;
  6567. this.cleanGeneration = 1;
  6568. this.frontier = firstLine;
  6569. var start = Pos(firstLine, 0);
  6570. this.sel = simpleSelection(start);
  6571. this.history = new History(null);
  6572. this.id = ++nextDocId;
  6573. this.modeOption = mode;
  6574. if (typeof text == "string") text = splitLines(text);
  6575. updateDoc(this, {from: start, to: start, text: text});
  6576. setSelection(this, simpleSelection(start), sel_dontScroll);
  6577. };
  6578. Doc.prototype = createObj(BranchChunk.prototype, {
  6579. constructor: Doc,
  6580. // Iterate over the document. Supports two forms -- with only one
  6581. // argument, it calls that for each line in the document. With
  6582. // three, it iterates over the range given by the first two (with
  6583. // the second being non-inclusive).
  6584. iter: function(from, to, op) {
  6585. if (op) this.iterN(from - this.first, to - from, op);
  6586. else this.iterN(this.first, this.first + this.size, from);
  6587. },
  6588. // Non-public interface for adding and removing lines.
  6589. insert: function(at, lines) {
  6590. var height = 0;
  6591. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6592. this.insertInner(at - this.first, lines, height);
  6593. },
  6594. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6595. // From here, the methods are part of the public interface. Most
  6596. // are also available from CodeMirror (editor) instances.
  6597. getValue: function(lineSep) {
  6598. var lines = getLines(this, this.first, this.first + this.size);
  6599. if (lineSep === false) return lines;
  6600. return lines.join(lineSep || "\n");
  6601. },
  6602. setValue: docMethodOp(function(code) {
  6603. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6604. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6605. text: splitLines(code), origin: "setValue", full: true}, true);
  6606. setSelection(this, simpleSelection(top));
  6607. }),
  6608. replaceRange: function(code, from, to, origin) {
  6609. from = clipPos(this, from);
  6610. to = to ? clipPos(this, to) : from;
  6611. replaceRange(this, code, from, to, origin);
  6612. },
  6613. getRange: function(from, to, lineSep) {
  6614. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6615. if (lineSep === false) return lines;
  6616. return lines.join(lineSep || "\n");
  6617. },
  6618. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6619. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6620. getLineNumber: function(line) {return lineNo(line);},
  6621. getLineHandleVisualStart: function(line) {
  6622. if (typeof line == "number") line = getLine(this, line);
  6623. return visualLine(line);
  6624. },
  6625. lineCount: function() {return this.size;},
  6626. firstLine: function() {return this.first;},
  6627. lastLine: function() {return this.first + this.size - 1;},
  6628. clipPos: function(pos) {return clipPos(this, pos);},
  6629. getCursor: function(start) {
  6630. var range = this.sel.primary(), pos;
  6631. if (start == null || start == "head") pos = range.head;
  6632. else if (start == "anchor") pos = range.anchor;
  6633. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6634. else pos = range.from();
  6635. return pos;
  6636. },
  6637. listSelections: function() { return this.sel.ranges; },
  6638. somethingSelected: function() {return this.sel.somethingSelected();},
  6639. setCursor: docMethodOp(function(line, ch, options) {
  6640. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6641. }),
  6642. setSelection: docMethodOp(function(anchor, head, options) {
  6643. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6644. }),
  6645. extendSelection: docMethodOp(function(head, other, options) {
  6646. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6647. }),
  6648. extendSelections: docMethodOp(function(heads, options) {
  6649. extendSelections(this, clipPosArray(this, heads, options));
  6650. }),
  6651. extendSelectionsBy: docMethodOp(function(f, options) {
  6652. extendSelections(this, map(this.sel.ranges, f), options);
  6653. }),
  6654. setSelections: docMethodOp(function(ranges, primary, options) {
  6655. if (!ranges.length) return;
  6656. for (var i = 0, out = []; i < ranges.length; i++)
  6657. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6658. clipPos(this, ranges[i].head));
  6659. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6660. setSelection(this, normalizeSelection(out, primary), options);
  6661. }),
  6662. addSelection: docMethodOp(function(anchor, head, options) {
  6663. var ranges = this.sel.ranges.slice(0);
  6664. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6665. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6666. }),
  6667. getSelection: function(lineSep) {
  6668. var ranges = this.sel.ranges, lines;
  6669. for (var i = 0; i < ranges.length; i++) {
  6670. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6671. lines = lines ? lines.concat(sel) : sel;
  6672. }
  6673. if (lineSep === false) return lines;
  6674. else return lines.join(lineSep || "\n");
  6675. },
  6676. getSelections: function(lineSep) {
  6677. var parts = [], ranges = this.sel.ranges;
  6678. for (var i = 0; i < ranges.length; i++) {
  6679. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6680. if (lineSep !== false) sel = sel.join(lineSep || "\n");
  6681. parts[i] = sel;
  6682. }
  6683. return parts;
  6684. },
  6685. replaceSelection: function(code, collapse, origin) {
  6686. var dup = [];
  6687. for (var i = 0; i < this.sel.ranges.length; i++)
  6688. dup[i] = code;
  6689. this.replaceSelections(dup, collapse, origin || "+input");
  6690. },
  6691. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6692. var changes = [], sel = this.sel;
  6693. for (var i = 0; i < sel.ranges.length; i++) {
  6694. var range = sel.ranges[i];
  6695. changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
  6696. }
  6697. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6698. for (var i = changes.length - 1; i >= 0; i--)
  6699. makeChange(this, changes[i]);
  6700. if (newSel) setSelectionReplaceHistory(this, newSel);
  6701. else if (this.cm) ensureCursorVisible(this.cm);
  6702. }),
  6703. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6704. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6705. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6706. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6707. setExtending: function(val) {this.extend = val;},
  6708. getExtending: function() {return this.extend;},
  6709. historySize: function() {
  6710. var hist = this.history, done = 0, undone = 0;
  6711. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6712. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6713. return {undo: done, redo: undone};
  6714. },
  6715. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6716. markClean: function() {
  6717. this.cleanGeneration = this.changeGeneration(true);
  6718. },
  6719. changeGeneration: function(forceSplit) {
  6720. if (forceSplit)
  6721. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6722. return this.history.generation;
  6723. },
  6724. isClean: function (gen) {
  6725. return this.history.generation == (gen || this.cleanGeneration);
  6726. },
  6727. getHistory: function() {
  6728. return {done: copyHistoryArray(this.history.done),
  6729. undone: copyHistoryArray(this.history.undone)};
  6730. },
  6731. setHistory: function(histData) {
  6732. var hist = this.history = new History(this.history.maxGeneration);
  6733. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6734. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6735. },
  6736. addLineClass: docMethodOp(function(handle, where, cls) {
  6737. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6738. var prop = where == "text" ? "textClass"
  6739. : where == "background" ? "bgClass"
  6740. : where == "gutter" ? "gutterClass" : "wrapClass";
  6741. if (!line[prop]) line[prop] = cls;
  6742. else if (classTest(cls).test(line[prop])) return false;
  6743. else line[prop] += " " + cls;
  6744. return true;
  6745. });
  6746. }),
  6747. removeLineClass: docMethodOp(function(handle, where, cls) {
  6748. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6749. var prop = where == "text" ? "textClass"
  6750. : where == "background" ? "bgClass"
  6751. : where == "gutter" ? "gutterClass" : "wrapClass";
  6752. var cur = line[prop];
  6753. if (!cur) return false;
  6754. else if (cls == null) line[prop] = null;
  6755. else {
  6756. var found = cur.match(classTest(cls));
  6757. if (!found) return false;
  6758. var end = found.index + found[0].length;
  6759. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6760. }
  6761. return true;
  6762. });
  6763. }),
  6764. addLineWidget: docMethodOp(function(handle, node, options) {
  6765. return addLineWidget(this, handle, node, options);
  6766. }),
  6767. removeLineWidget: function(widget) { widget.clear(); },
  6768. markText: function(from, to, options) {
  6769. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  6770. },
  6771. setBookmark: function(pos, options) {
  6772. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6773. insertLeft: options && options.insertLeft,
  6774. clearWhenEmpty: false, shared: options && options.shared,
  6775. handleMouseEvents: options && options.handleMouseEvents};
  6776. pos = clipPos(this, pos);
  6777. return markText(this, pos, pos, realOpts, "bookmark");
  6778. },
  6779. findMarksAt: function(pos) {
  6780. pos = clipPos(this, pos);
  6781. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6782. if (spans) for (var i = 0; i < spans.length; ++i) {
  6783. var span = spans[i];
  6784. if ((span.from == null || span.from <= pos.ch) &&
  6785. (span.to == null || span.to >= pos.ch))
  6786. markers.push(span.marker.parent || span.marker);
  6787. }
  6788. return markers;
  6789. },
  6790. findMarks: function(from, to, filter) {
  6791. from = clipPos(this, from); to = clipPos(this, to);
  6792. var found = [], lineNo = from.line;
  6793. this.iter(from.line, to.line + 1, function(line) {
  6794. var spans = line.markedSpans;
  6795. if (spans) for (var i = 0; i < spans.length; i++) {
  6796. var span = spans[i];
  6797. if (!(lineNo == from.line && from.ch > span.to ||
  6798. span.from == null && lineNo != from.line||
  6799. lineNo == to.line && span.from > to.ch) &&
  6800. (!filter || filter(span.marker)))
  6801. found.push(span.marker.parent || span.marker);
  6802. }
  6803. ++lineNo;
  6804. });
  6805. return found;
  6806. },
  6807. getAllMarks: function() {
  6808. var markers = [];
  6809. this.iter(function(line) {
  6810. var sps = line.markedSpans;
  6811. if (sps) for (var i = 0; i < sps.length; ++i)
  6812. if (sps[i].from != null) markers.push(sps[i].marker);
  6813. });
  6814. return markers;
  6815. },
  6816. posFromIndex: function(off) {
  6817. var ch, lineNo = this.first;
  6818. this.iter(function(line) {
  6819. var sz = line.text.length + 1;
  6820. if (sz > off) { ch = off; return true; }
  6821. off -= sz;
  6822. ++lineNo;
  6823. });
  6824. return clipPos(this, Pos(lineNo, ch));
  6825. },
  6826. indexFromPos: function (coords) {
  6827. coords = clipPos(this, coords);
  6828. var index = coords.ch;
  6829. if (coords.line < this.first || coords.ch < 0) return 0;
  6830. this.iter(this.first, coords.line, function (line) {
  6831. index += line.text.length + 1;
  6832. });
  6833. return index;
  6834. },
  6835. copy: function(copyHistory) {
  6836. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  6837. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6838. doc.sel = this.sel;
  6839. doc.extend = false;
  6840. if (copyHistory) {
  6841. doc.history.undoDepth = this.history.undoDepth;
  6842. doc.setHistory(this.getHistory());
  6843. }
  6844. return doc;
  6845. },
  6846. linkedDoc: function(options) {
  6847. if (!options) options = {};
  6848. var from = this.first, to = this.first + this.size;
  6849. if (options.from != null && options.from > from) from = options.from;
  6850. if (options.to != null && options.to < to) to = options.to;
  6851. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  6852. if (options.sharedHist) copy.history = this.history;
  6853. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6854. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6855. copySharedMarkers(copy, findSharedMarkers(this));
  6856. return copy;
  6857. },
  6858. unlinkDoc: function(other) {
  6859. if (other instanceof CodeMirror) other = other.doc;
  6860. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6861. var link = this.linked[i];
  6862. if (link.doc != other) continue;
  6863. this.linked.splice(i, 1);
  6864. other.unlinkDoc(this);
  6865. detachSharedMarkers(findSharedMarkers(this));
  6866. break;
  6867. }
  6868. // If the histories were shared, split them again
  6869. if (other.history == this.history) {
  6870. var splitIds = [other.id];
  6871. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  6872. other.history = new History(null);
  6873. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6874. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6875. }
  6876. },
  6877. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  6878. getMode: function() {return this.mode;},
  6879. getEditor: function() {return this.cm;}
  6880. });
  6881. // Public alias.
  6882. Doc.prototype.eachLine = Doc.prototype.iter;
  6883. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  6884. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  6885. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  6886. CodeMirror.prototype[prop] = (function(method) {
  6887. return function() {return method.apply(this.doc, arguments);};
  6888. })(Doc.prototype[prop]);
  6889. eventMixin(Doc);
  6890. // Call f for all linked documents.
  6891. function linkedDocs(doc, f, sharedHistOnly) {
  6892. function propagate(doc, skip, sharedHist) {
  6893. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  6894. var rel = doc.linked[i];
  6895. if (rel.doc == skip) continue;
  6896. var shared = sharedHist && rel.sharedHist;
  6897. if (sharedHistOnly && !shared) continue;
  6898. f(rel.doc, shared);
  6899. propagate(rel.doc, doc, shared);
  6900. }
  6901. }
  6902. propagate(doc, null, true);
  6903. }
  6904. // Attach a document to an editor.
  6905. function attachDoc(cm, doc) {
  6906. if (doc.cm) throw new Error("This document is already in use.");
  6907. cm.doc = doc;
  6908. doc.cm = cm;
  6909. estimateLineHeights(cm);
  6910. loadMode(cm);
  6911. if (!cm.options.lineWrapping) findMaxLine(cm);
  6912. cm.options.mode = doc.modeOption;
  6913. regChange(cm);
  6914. }
  6915. // LINE UTILITIES
  6916. // Find the line object corresponding to the given line number.
  6917. function getLine(doc, n) {
  6918. n -= doc.first;
  6919. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  6920. for (var chunk = doc; !chunk.lines;) {
  6921. for (var i = 0;; ++i) {
  6922. var child = chunk.children[i], sz = child.chunkSize();
  6923. if (n < sz) { chunk = child; break; }
  6924. n -= sz;
  6925. }
  6926. }
  6927. return chunk.lines[n];
  6928. }
  6929. // Get the part of a document between two positions, as an array of
  6930. // strings.
  6931. function getBetween(doc, start, end) {
  6932. var out = [], n = start.line;
  6933. doc.iter(start.line, end.line + 1, function(line) {
  6934. var text = line.text;
  6935. if (n == end.line) text = text.slice(0, end.ch);
  6936. if (n == start.line) text = text.slice(start.ch);
  6937. out.push(text);
  6938. ++n;
  6939. });
  6940. return out;
  6941. }
  6942. // Get the lines between from and to, as array of strings.
  6943. function getLines(doc, from, to) {
  6944. var out = [];
  6945. doc.iter(from, to, function(line) { out.push(line.text); });
  6946. return out;
  6947. }
  6948. // Update the height of a line, propagating the height change
  6949. // upwards to parent nodes.
  6950. function updateLineHeight(line, height) {
  6951. var diff = height - line.height;
  6952. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  6953. }
  6954. // Given a line object, find its line number by walking up through
  6955. // its parent links.
  6956. function lineNo(line) {
  6957. if (line.parent == null) return null;
  6958. var cur = line.parent, no = indexOf(cur.lines, line);
  6959. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  6960. for (var i = 0;; ++i) {
  6961. if (chunk.children[i] == cur) break;
  6962. no += chunk.children[i].chunkSize();
  6963. }
  6964. }
  6965. return no + cur.first;
  6966. }
  6967. // Find the line at the given vertical position, using the height
  6968. // information in the document tree.
  6969. function lineAtHeight(chunk, h) {
  6970. var n = chunk.first;
  6971. outer: do {
  6972. for (var i = 0; i < chunk.children.length; ++i) {
  6973. var child = chunk.children[i], ch = child.height;
  6974. if (h < ch) { chunk = child; continue outer; }
  6975. h -= ch;
  6976. n += child.chunkSize();
  6977. }
  6978. return n;
  6979. } while (!chunk.lines);
  6980. for (var i = 0; i < chunk.lines.length; ++i) {
  6981. var line = chunk.lines[i], lh = line.height;
  6982. if (h < lh) break;
  6983. h -= lh;
  6984. }
  6985. return n + i;
  6986. }
  6987. // Find the height above the given line.
  6988. function heightAtLine(lineObj) {
  6989. lineObj = visualLine(lineObj);
  6990. var h = 0, chunk = lineObj.parent;
  6991. for (var i = 0; i < chunk.lines.length; ++i) {
  6992. var line = chunk.lines[i];
  6993. if (line == lineObj) break;
  6994. else h += line.height;
  6995. }
  6996. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  6997. for (var i = 0; i < p.children.length; ++i) {
  6998. var cur = p.children[i];
  6999. if (cur == chunk) break;
  7000. else h += cur.height;
  7001. }
  7002. }
  7003. return h;
  7004. }
  7005. // Get the bidi ordering for the given line (and cache it). Returns
  7006. // false for lines that are fully left-to-right, and an array of
  7007. // BidiSpan objects otherwise.
  7008. function getOrder(line) {
  7009. var order = line.order;
  7010. if (order == null) order = line.order = bidiOrdering(line.text);
  7011. return order;
  7012. }
  7013. // HISTORY
  7014. function History(startGen) {
  7015. // Arrays of change events and selections. Doing something adds an
  7016. // event to done and clears undo. Undoing moves events from done
  7017. // to undone, redoing moves them in the other direction.
  7018. this.done = []; this.undone = [];
  7019. this.undoDepth = Infinity;
  7020. // Used to track when changes can be merged into a single undo
  7021. // event
  7022. this.lastModTime = this.lastSelTime = 0;
  7023. this.lastOp = this.lastSelOp = null;
  7024. this.lastOrigin = this.lastSelOrigin = null;
  7025. // Used by the isClean() method
  7026. this.generation = this.maxGeneration = startGen || 1;
  7027. }
  7028. // Create a history change event from an updateDoc-style change
  7029. // object.
  7030. function historyChangeFromChange(doc, change) {
  7031. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  7032. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  7033. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  7034. return histChange;
  7035. }
  7036. // Pop all selection events off the end of a history array. Stop at
  7037. // a change event.
  7038. function clearSelectionEvents(array) {
  7039. while (array.length) {
  7040. var last = lst(array);
  7041. if (last.ranges) array.pop();
  7042. else break;
  7043. }
  7044. }
  7045. // Find the top change event in the history. Pop off selection
  7046. // events that are in the way.
  7047. function lastChangeEvent(hist, force) {
  7048. if (force) {
  7049. clearSelectionEvents(hist.done);
  7050. return lst(hist.done);
  7051. } else if (hist.done.length && !lst(hist.done).ranges) {
  7052. return lst(hist.done);
  7053. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  7054. hist.done.pop();
  7055. return lst(hist.done);
  7056. }
  7057. }
  7058. // Register a change in the history. Merges changes that are within
  7059. // a single operation, ore are close together with an origin that
  7060. // allows merging (starting with "+") into a single event.
  7061. function addChangeToHistory(doc, change, selAfter, opId) {
  7062. var hist = doc.history;
  7063. hist.undone.length = 0;
  7064. var time = +new Date, cur;
  7065. if ((hist.lastOp == opId ||
  7066. hist.lastOrigin == change.origin && change.origin &&
  7067. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  7068. change.origin.charAt(0) == "*")) &&
  7069. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  7070. // Merge this change into the last event
  7071. var last = lst(cur.changes);
  7072. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  7073. // Optimized case for simple insertion -- don't want to add
  7074. // new changesets for every character typed
  7075. last.to = changeEnd(change);
  7076. } else {
  7077. // Add new sub-event
  7078. cur.changes.push(historyChangeFromChange(doc, change));
  7079. }
  7080. } else {
  7081. // Can not be merged, start a new event.
  7082. var before = lst(hist.done);
  7083. if (!before || !before.ranges)
  7084. pushSelectionToHistory(doc.sel, hist.done);
  7085. cur = {changes: [historyChangeFromChange(doc, change)],
  7086. generation: hist.generation};
  7087. hist.done.push(cur);
  7088. while (hist.done.length > hist.undoDepth) {
  7089. hist.done.shift();
  7090. if (!hist.done[0].ranges) hist.done.shift();
  7091. }
  7092. }
  7093. hist.done.push(selAfter);
  7094. hist.generation = ++hist.maxGeneration;
  7095. hist.lastModTime = hist.lastSelTime = time;
  7096. hist.lastOp = hist.lastSelOp = opId;
  7097. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7098. if (!last) signal(doc, "historyAdded");
  7099. }
  7100. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7101. var ch = origin.charAt(0);
  7102. return ch == "*" ||
  7103. ch == "+" &&
  7104. prev.ranges.length == sel.ranges.length &&
  7105. prev.somethingSelected() == sel.somethingSelected() &&
  7106. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7107. }
  7108. // Called whenever the selection changes, sets the new selection as
  7109. // the pending selection in the history, and pushes the old pending
  7110. // selection into the 'done' array when it was significantly
  7111. // different (in number of selected ranges, emptiness, or time).
  7112. function addSelectionToHistory(doc, sel, opId, options) {
  7113. var hist = doc.history, origin = options && options.origin;
  7114. // A new event is started when the previous origin does not match
  7115. // the current, or the origins don't allow matching. Origins
  7116. // starting with * are always merged, those starting with + are
  7117. // merged when similar and close together in time.
  7118. if (opId == hist.lastSelOp ||
  7119. (origin && hist.lastSelOrigin == origin &&
  7120. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7121. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7122. hist.done[hist.done.length - 1] = sel;
  7123. else
  7124. pushSelectionToHistory(sel, hist.done);
  7125. hist.lastSelTime = +new Date;
  7126. hist.lastSelOrigin = origin;
  7127. hist.lastSelOp = opId;
  7128. if (options && options.clearRedo !== false)
  7129. clearSelectionEvents(hist.undone);
  7130. }
  7131. function pushSelectionToHistory(sel, dest) {
  7132. var top = lst(dest);
  7133. if (!(top && top.ranges && top.equals(sel)))
  7134. dest.push(sel);
  7135. }
  7136. // Used to store marked span information in the history.
  7137. function attachLocalSpans(doc, change, from, to) {
  7138. var existing = change["spans_" + doc.id], n = 0;
  7139. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  7140. if (line.markedSpans)
  7141. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7142. ++n;
  7143. });
  7144. }
  7145. // When un/re-doing restores text containing marked spans, those
  7146. // that have been explicitly cleared should not be restored.
  7147. function removeClearedSpans(spans) {
  7148. if (!spans) return null;
  7149. for (var i = 0, out; i < spans.length; ++i) {
  7150. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7151. else if (out) out.push(spans[i]);
  7152. }
  7153. return !out ? spans : out.length ? out : null;
  7154. }
  7155. // Retrieve and filter the old marked spans stored in a change event.
  7156. function getOldSpans(doc, change) {
  7157. var found = change["spans_" + doc.id];
  7158. if (!found) return null;
  7159. for (var i = 0, nw = []; i < change.text.length; ++i)
  7160. nw.push(removeClearedSpans(found[i]));
  7161. return nw;
  7162. }
  7163. // Used both to provide a JSON-safe object in .getHistory, and, when
  7164. // detaching a document, to split the history in two
  7165. function copyHistoryArray(events, newGroup, instantiateSel) {
  7166. for (var i = 0, copy = []; i < events.length; ++i) {
  7167. var event = events[i];
  7168. if (event.ranges) {
  7169. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7170. continue;
  7171. }
  7172. var changes = event.changes, newChanges = [];
  7173. copy.push({changes: newChanges});
  7174. for (var j = 0; j < changes.length; ++j) {
  7175. var change = changes[j], m;
  7176. newChanges.push({from: change.from, to: change.to, text: change.text});
  7177. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7178. if (indexOf(newGroup, Number(m[1])) > -1) {
  7179. lst(newChanges)[prop] = change[prop];
  7180. delete change[prop];
  7181. }
  7182. }
  7183. }
  7184. }
  7185. return copy;
  7186. }
  7187. // Rebasing/resetting history to deal with externally-sourced changes
  7188. function rebaseHistSelSingle(pos, from, to, diff) {
  7189. if (to < pos.line) {
  7190. pos.line += diff;
  7191. } else if (from < pos.line) {
  7192. pos.line = from;
  7193. pos.ch = 0;
  7194. }
  7195. }
  7196. // Tries to rebase an array of history events given a change in the
  7197. // document. If the change touches the same lines as the event, the
  7198. // event, and everything 'behind' it, is discarded. If the change is
  7199. // before the event, the event's positions are updated. Uses a
  7200. // copy-on-write scheme for the positions, to avoid having to
  7201. // reallocate them all on every rebase, but also avoid problems with
  7202. // shared position objects being unsafely updated.
  7203. function rebaseHistArray(array, from, to, diff) {
  7204. for (var i = 0; i < array.length; ++i) {
  7205. var sub = array[i], ok = true;
  7206. if (sub.ranges) {
  7207. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7208. for (var j = 0; j < sub.ranges.length; j++) {
  7209. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7210. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7211. }
  7212. continue;
  7213. }
  7214. for (var j = 0; j < sub.changes.length; ++j) {
  7215. var cur = sub.changes[j];
  7216. if (to < cur.from.line) {
  7217. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7218. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7219. } else if (from <= cur.to.line) {
  7220. ok = false;
  7221. break;
  7222. }
  7223. }
  7224. if (!ok) {
  7225. array.splice(0, i + 1);
  7226. i = 0;
  7227. }
  7228. }
  7229. }
  7230. function rebaseHist(hist, change) {
  7231. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7232. rebaseHistArray(hist.done, from, to, diff);
  7233. rebaseHistArray(hist.undone, from, to, diff);
  7234. }
  7235. // EVENT UTILITIES
  7236. // Due to the fact that we still support jurassic IE versions, some
  7237. // compatibility wrappers are needed.
  7238. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  7239. if (e.preventDefault) e.preventDefault();
  7240. else e.returnValue = false;
  7241. };
  7242. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  7243. if (e.stopPropagation) e.stopPropagation();
  7244. else e.cancelBubble = true;
  7245. };
  7246. function e_defaultPrevented(e) {
  7247. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7248. }
  7249. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  7250. function e_target(e) {return e.target || e.srcElement;}
  7251. function e_button(e) {
  7252. var b = e.which;
  7253. if (b == null) {
  7254. if (e.button & 1) b = 1;
  7255. else if (e.button & 2) b = 3;
  7256. else if (e.button & 4) b = 2;
  7257. }
  7258. if (mac && e.ctrlKey && b == 1) b = 3;
  7259. return b;
  7260. }
  7261. // EVENT HANDLING
  7262. // Lightweight event framework. on/off also work on DOM nodes,
  7263. // registering native DOM handlers.
  7264. var on = CodeMirror.on = function(emitter, type, f) {
  7265. if (emitter.addEventListener)
  7266. emitter.addEventListener(type, f, false);
  7267. else if (emitter.attachEvent)
  7268. emitter.attachEvent("on" + type, f);
  7269. else {
  7270. var map = emitter._handlers || (emitter._handlers = {});
  7271. var arr = map[type] || (map[type] = []);
  7272. arr.push(f);
  7273. }
  7274. };
  7275. var off = CodeMirror.off = function(emitter, type, f) {
  7276. if (emitter.removeEventListener)
  7277. emitter.removeEventListener(type, f, false);
  7278. else if (emitter.detachEvent)
  7279. emitter.detachEvent("on" + type, f);
  7280. else {
  7281. var arr = emitter._handlers && emitter._handlers[type];
  7282. if (!arr) return;
  7283. for (var i = 0; i < arr.length; ++i)
  7284. if (arr[i] == f) { arr.splice(i, 1); break; }
  7285. }
  7286. };
  7287. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  7288. var arr = emitter._handlers && emitter._handlers[type];
  7289. if (!arr) return;
  7290. var args = Array.prototype.slice.call(arguments, 2);
  7291. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  7292. };
  7293. var orphanDelayedCallbacks = null;
  7294. // Often, we want to signal events at a point where we are in the
  7295. // middle of some work, but don't want the handler to start calling
  7296. // other methods on the editor, which might be in an inconsistent
  7297. // state or simply not expect any other events to happen.
  7298. // signalLater looks whether there are any handlers, and schedules
  7299. // them to be executed when the last operation ends, or, if no
  7300. // operation is active, when a timeout fires.
  7301. function signalLater(emitter, type /*, values...*/) {
  7302. var arr = emitter._handlers && emitter._handlers[type];
  7303. if (!arr) return;
  7304. var args = Array.prototype.slice.call(arguments, 2), list;
  7305. if (operationGroup) {
  7306. list = operationGroup.delayedCallbacks;
  7307. } else if (orphanDelayedCallbacks) {
  7308. list = orphanDelayedCallbacks;
  7309. } else {
  7310. list = orphanDelayedCallbacks = [];
  7311. setTimeout(fireOrphanDelayed, 0);
  7312. }
  7313. function bnd(f) {return function(){f.apply(null, args);};};
  7314. for (var i = 0; i < arr.length; ++i)
  7315. list.push(bnd(arr[i]));
  7316. }
  7317. function fireOrphanDelayed() {
  7318. var delayed = orphanDelayedCallbacks;
  7319. orphanDelayedCallbacks = null;
  7320. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7321. }
  7322. // The DOM events that CodeMirror handles can be overridden by
  7323. // registering a (non-DOM) handler on the editor for the event name,
  7324. // and preventDefault-ing the event in that handler.
  7325. function signalDOMEvent(cm, e, override) {
  7326. if (typeof e == "string")
  7327. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  7328. signal(cm, override || e.type, cm, e);
  7329. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7330. }
  7331. function signalCursorActivity(cm) {
  7332. var arr = cm._handlers && cm._handlers.cursorActivity;
  7333. if (!arr) return;
  7334. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7335. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7336. set.push(arr[i]);
  7337. }
  7338. function hasHandler(emitter, type) {
  7339. var arr = emitter._handlers && emitter._handlers[type];
  7340. return arr && arr.length > 0;
  7341. }
  7342. // Add on and off methods to a constructor's prototype, to make
  7343. // registering events on such objects more convenient.
  7344. function eventMixin(ctor) {
  7345. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7346. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7347. }
  7348. // MISC UTILITIES
  7349. // Number of pixels added to scroller and sizer to hide scrollbar
  7350. var scrollerGap = 30;
  7351. // Returned or thrown by various protocols to signal 'I'm not
  7352. // handling this'.
  7353. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  7354. // Reused option objects for setSelection & friends
  7355. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  7356. function Delayed() {this.id = null;}
  7357. Delayed.prototype.set = function(ms, f) {
  7358. clearTimeout(this.id);
  7359. this.id = setTimeout(f, ms);
  7360. };
  7361. // Counts the column offset in a string, taking tabs into account.
  7362. // Used mostly to find indentation.
  7363. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  7364. if (end == null) {
  7365. end = string.search(/[^\s\u00a0]/);
  7366. if (end == -1) end = string.length;
  7367. }
  7368. for (var i = startIndex || 0, n = startValue || 0;;) {
  7369. var nextTab = string.indexOf("\t", i);
  7370. if (nextTab < 0 || nextTab >= end)
  7371. return n + (end - i);
  7372. n += nextTab - i;
  7373. n += tabSize - (n % tabSize);
  7374. i = nextTab + 1;
  7375. }
  7376. };
  7377. // The inverse of countColumn -- find the offset that corresponds to
  7378. // a particular column.
  7379. function findColumn(string, goal, tabSize) {
  7380. for (var pos = 0, col = 0;;) {
  7381. var nextTab = string.indexOf("\t", pos);
  7382. if (nextTab == -1) nextTab = string.length;
  7383. var skipped = nextTab - pos;
  7384. if (nextTab == string.length || col + skipped >= goal)
  7385. return pos + Math.min(skipped, goal - col);
  7386. col += nextTab - pos;
  7387. col += tabSize - (col % tabSize);
  7388. pos = nextTab + 1;
  7389. if (col >= goal) return pos;
  7390. }
  7391. }
  7392. var spaceStrs = [""];
  7393. function spaceStr(n) {
  7394. while (spaceStrs.length <= n)
  7395. spaceStrs.push(lst(spaceStrs) + " ");
  7396. return spaceStrs[n];
  7397. }
  7398. function lst(arr) { return arr[arr.length-1]; }
  7399. var selectInput = function(node) { node.select(); };
  7400. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7401. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7402. else if (ie) // Suppress mysterious IE10 errors
  7403. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  7404. function indexOf(array, elt) {
  7405. for (var i = 0; i < array.length; ++i)
  7406. if (array[i] == elt) return i;
  7407. return -1;
  7408. }
  7409. function map(array, f) {
  7410. var out = [];
  7411. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7412. return out;
  7413. }
  7414. function nothing() {}
  7415. function createObj(base, props) {
  7416. var inst;
  7417. if (Object.create) {
  7418. inst = Object.create(base);
  7419. } else {
  7420. nothing.prototype = base;
  7421. inst = new nothing();
  7422. }
  7423. if (props) copyObj(props, inst);
  7424. return inst;
  7425. };
  7426. function copyObj(obj, target, overwrite) {
  7427. if (!target) target = {};
  7428. for (var prop in obj)
  7429. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7430. target[prop] = obj[prop];
  7431. return target;
  7432. }
  7433. function bind(f) {
  7434. var args = Array.prototype.slice.call(arguments, 1);
  7435. return function(){return f.apply(null, args);};
  7436. }
  7437. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7438. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  7439. return /\w/.test(ch) || ch > "\x80" &&
  7440. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7441. };
  7442. function isWordChar(ch, helper) {
  7443. if (!helper) return isWordCharBasic(ch);
  7444. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7445. return helper.test(ch);
  7446. }
  7447. function isEmpty(obj) {
  7448. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7449. return true;
  7450. }
  7451. // Extending unicode characters. A series of a non-extending char +
  7452. // any number of extending chars is treated as a single unit as far
  7453. // as editing and measuring is concerned. This is not fully correct,
  7454. // since some scripts/fonts/browsers also treat other configurations
  7455. // of code points as a group.
  7456. 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]/;
  7457. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7458. // DOM UTILITIES
  7459. function elt(tag, content, className, style) {
  7460. var e = document.createElement(tag);
  7461. if (className) e.className = className;
  7462. if (style) e.style.cssText = style;
  7463. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7464. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7465. return e;
  7466. }
  7467. var range;
  7468. if (document.createRange) range = function(node, start, end, endNode) {
  7469. var r = document.createRange();
  7470. r.setEnd(endNode || node, end);
  7471. r.setStart(node, start);
  7472. return r;
  7473. };
  7474. else range = function(node, start, end) {
  7475. var r = document.body.createTextRange();
  7476. try { r.moveToElementText(node.parentNode); }
  7477. catch(e) { return r; }
  7478. r.collapse(true);
  7479. r.moveEnd("character", end);
  7480. r.moveStart("character", start);
  7481. return r;
  7482. };
  7483. function removeChildren(e) {
  7484. for (var count = e.childNodes.length; count > 0; --count)
  7485. e.removeChild(e.firstChild);
  7486. return e;
  7487. }
  7488. function removeChildrenAndAdd(parent, e) {
  7489. return removeChildren(parent).appendChild(e);
  7490. }
  7491. var contains = CodeMirror.contains = function(parent, child) {
  7492. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7493. child = child.parentNode;
  7494. if (parent.contains)
  7495. return parent.contains(child);
  7496. do {
  7497. if (child.nodeType == 11) child = child.host;
  7498. if (child == parent) return true;
  7499. } while (child = child.parentNode);
  7500. };
  7501. function activeElt() { return document.activeElement; }
  7502. // Older versions of IE throws unspecified error when touching
  7503. // document.activeElement in some cases (during loading, in iframe)
  7504. if (ie && ie_version < 11) activeElt = function() {
  7505. try { return document.activeElement; }
  7506. catch(e) { return document.body; }
  7507. };
  7508. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7509. var rmClass = CodeMirror.rmClass = function(node, cls) {
  7510. var current = node.className;
  7511. var match = classTest(cls).exec(current);
  7512. if (match) {
  7513. var after = current.slice(match.index + match[0].length);
  7514. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7515. }
  7516. };
  7517. var addClass = CodeMirror.addClass = function(node, cls) {
  7518. var current = node.className;
  7519. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7520. };
  7521. function joinClasses(a, b) {
  7522. var as = a.split(" ");
  7523. for (var i = 0; i < as.length; i++)
  7524. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7525. return b;
  7526. }
  7527. // WINDOW-WIDE EVENTS
  7528. // These must be handled carefully, because naively registering a
  7529. // handler for each editor will cause the editors to never be
  7530. // garbage collected.
  7531. function forEachCodeMirror(f) {
  7532. if (!document.body.getElementsByClassName) return;
  7533. var byClass = document.body.getElementsByClassName("CodeMirror");
  7534. for (var i = 0; i < byClass.length; i++) {
  7535. var cm = byClass[i].CodeMirror;
  7536. if (cm) f(cm);
  7537. }
  7538. }
  7539. var globalsRegistered = false;
  7540. function ensureGlobalHandlers() {
  7541. if (globalsRegistered) return;
  7542. registerGlobalHandlers();
  7543. globalsRegistered = true;
  7544. }
  7545. function registerGlobalHandlers() {
  7546. // When the window resizes, we need to refresh active editors.
  7547. var resizeTimer;
  7548. on(window, "resize", function() {
  7549. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  7550. resizeTimer = null;
  7551. forEachCodeMirror(onResize);
  7552. }, 100);
  7553. });
  7554. // When the window loses focus, we want to show the editor as blurred
  7555. on(window, "blur", function() {
  7556. forEachCodeMirror(onBlur);
  7557. });
  7558. }
  7559. // FEATURE DETECTION
  7560. // Detect drag-and-drop
  7561. var dragAndDrop = function() {
  7562. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7563. // couldn't get it to work yet.
  7564. if (ie && ie_version < 9) return false;
  7565. var div = elt('div');
  7566. return "draggable" in div || "dragDrop" in div;
  7567. }();
  7568. var zwspSupported;
  7569. function zeroWidthElement(measure) {
  7570. if (zwspSupported == null) {
  7571. var test = elt("span", "\u200b");
  7572. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7573. if (measure.firstChild.offsetHeight != 0)
  7574. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7575. }
  7576. var node = zwspSupported ? elt("span", "\u200b") :
  7577. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7578. node.setAttribute("cm-text", "");
  7579. return node;
  7580. }
  7581. // Feature-detect IE's crummy client rect reporting for bidi text
  7582. var badBidiRects;
  7583. function hasBadBidiRects(measure) {
  7584. if (badBidiRects != null) return badBidiRects;
  7585. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7586. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7587. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7588. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7589. return badBidiRects = (r1.right - r0.right < 3);
  7590. }
  7591. // See if "".split is the broken IE version, if so, provide an
  7592. // alternative way to split lines.
  7593. var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7594. var pos = 0, result = [], l = string.length;
  7595. while (pos <= l) {
  7596. var nl = string.indexOf("\n", pos);
  7597. if (nl == -1) nl = string.length;
  7598. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7599. var rt = line.indexOf("\r");
  7600. if (rt != -1) {
  7601. result.push(line.slice(0, rt));
  7602. pos += rt + 1;
  7603. } else {
  7604. result.push(line);
  7605. pos = nl + 1;
  7606. }
  7607. }
  7608. return result;
  7609. } : function(string){return string.split(/\r\n?|\n/);};
  7610. var hasSelection = window.getSelection ? function(te) {
  7611. try { return te.selectionStart != te.selectionEnd; }
  7612. catch(e) { return false; }
  7613. } : function(te) {
  7614. try {var range = te.ownerDocument.selection.createRange();}
  7615. catch(e) {}
  7616. if (!range || range.parentElement() != te) return false;
  7617. return range.compareEndPoints("StartToEnd", range) != 0;
  7618. };
  7619. var hasCopyEvent = (function() {
  7620. var e = elt("div");
  7621. if ("oncopy" in e) return true;
  7622. e.setAttribute("oncopy", "return;");
  7623. return typeof e.oncopy == "function";
  7624. })();
  7625. var badZoomedRects = null;
  7626. function hasBadZoomedRects(measure) {
  7627. if (badZoomedRects != null) return badZoomedRects;
  7628. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7629. var normal = node.getBoundingClientRect();
  7630. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7631. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7632. }
  7633. // KEY NAMES
  7634. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7635. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7636. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7637. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
  7638. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7639. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7640. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
  7641. CodeMirror.keyNames = keyNames;
  7642. (function() {
  7643. // Number keys
  7644. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7645. // Alphabetic keys
  7646. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7647. // Function keys
  7648. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7649. })();
  7650. // BIDI HELPERS
  7651. function iterateBidiSections(order, from, to, f) {
  7652. if (!order) return f(from, to, "ltr");
  7653. var found = false;
  7654. for (var i = 0; i < order.length; ++i) {
  7655. var part = order[i];
  7656. if (part.from < to && part.to > from || from == to && part.to == from) {
  7657. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7658. found = true;
  7659. }
  7660. }
  7661. if (!found) f(from, to, "ltr");
  7662. }
  7663. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7664. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7665. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7666. function lineRight(line) {
  7667. var order = getOrder(line);
  7668. if (!order) return line.text.length;
  7669. return bidiRight(lst(order));
  7670. }
  7671. function lineStart(cm, lineN) {
  7672. var line = getLine(cm.doc, lineN);
  7673. var visual = visualLine(line);
  7674. if (visual != line) lineN = lineNo(visual);
  7675. var order = getOrder(visual);
  7676. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7677. return Pos(lineN, ch);
  7678. }
  7679. function lineEnd(cm, lineN) {
  7680. var merged, line = getLine(cm.doc, lineN);
  7681. while (merged = collapsedSpanAtEnd(line)) {
  7682. line = merged.find(1, true).line;
  7683. lineN = null;
  7684. }
  7685. var order = getOrder(line);
  7686. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7687. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7688. }
  7689. function lineStartSmart(cm, pos) {
  7690. var start = lineStart(cm, pos.line);
  7691. var line = getLine(cm.doc, start.line);
  7692. var order = getOrder(line);
  7693. if (!order || order[0].level == 0) {
  7694. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7695. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7696. return Pos(start.line, inWS ? 0 : firstNonWS);
  7697. }
  7698. return start;
  7699. }
  7700. function compareBidiLevel(order, a, b) {
  7701. var linedir = order[0].level;
  7702. if (a == linedir) return true;
  7703. if (b == linedir) return false;
  7704. return a < b;
  7705. }
  7706. var bidiOther;
  7707. function getBidiPartAt(order, pos) {
  7708. bidiOther = null;
  7709. for (var i = 0, found; i < order.length; ++i) {
  7710. var cur = order[i];
  7711. if (cur.from < pos && cur.to > pos) return i;
  7712. if ((cur.from == pos || cur.to == pos)) {
  7713. if (found == null) {
  7714. found = i;
  7715. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7716. if (cur.from != cur.to) bidiOther = found;
  7717. return i;
  7718. } else {
  7719. if (cur.from != cur.to) bidiOther = i;
  7720. return found;
  7721. }
  7722. }
  7723. }
  7724. return found;
  7725. }
  7726. function moveInLine(line, pos, dir, byUnit) {
  7727. if (!byUnit) return pos + dir;
  7728. do pos += dir;
  7729. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7730. return pos;
  7731. }
  7732. // This is needed in order to move 'visually' through bi-directional
  7733. // text -- i.e., pressing left should make the cursor go left, even
  7734. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7735. // LTR text touch each other. This often requires the cursor offset
  7736. // to move more than one unit, in order to visually move one unit.
  7737. function moveVisually(line, start, dir, byUnit) {
  7738. var bidi = getOrder(line);
  7739. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7740. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7741. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7742. for (;;) {
  7743. if (target > part.from && target < part.to) return target;
  7744. if (target == part.from || target == part.to) {
  7745. if (getBidiPartAt(bidi, target) == pos) return target;
  7746. part = bidi[pos += dir];
  7747. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7748. } else {
  7749. part = bidi[pos += dir];
  7750. if (!part) return null;
  7751. if ((dir > 0) == part.level % 2)
  7752. target = moveInLine(line, part.to, -1, byUnit);
  7753. else
  7754. target = moveInLine(line, part.from, 1, byUnit);
  7755. }
  7756. }
  7757. }
  7758. function moveLogically(line, start, dir, byUnit) {
  7759. var target = start + dir;
  7760. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7761. return target < 0 || target > line.text.length ? null : target;
  7762. }
  7763. // Bidirectional ordering algorithm
  7764. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7765. // that this (partially) implements.
  7766. // One-char codes used for character types:
  7767. // L (L): Left-to-Right
  7768. // R (R): Right-to-Left
  7769. // r (AL): Right-to-Left Arabic
  7770. // 1 (EN): European Number
  7771. // + (ES): European Number Separator
  7772. // % (ET): European Number Terminator
  7773. // n (AN): Arabic Number
  7774. // , (CS): Common Number Separator
  7775. // m (NSM): Non-Spacing Mark
  7776. // b (BN): Boundary Neutral
  7777. // s (B): Paragraph Separator
  7778. // t (S): Segment Separator
  7779. // w (WS): Whitespace
  7780. // N (ON): Other Neutrals
  7781. // Returns null if characters are ordered as they appear
  7782. // (left-to-right), or an array of sections ({from, to, level}
  7783. // objects) in the order in which they occur visually.
  7784. var bidiOrdering = (function() {
  7785. // Character types for codepoints 0 to 0xff
  7786. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7787. // Character types for codepoints 0x600 to 0x6ff
  7788. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7789. function charType(code) {
  7790. if (code <= 0xf7) return lowTypes.charAt(code);
  7791. else if (0x590 <= code && code <= 0x5f4) return "R";
  7792. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7793. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7794. else if (0x2000 <= code && code <= 0x200b) return "w";
  7795. else if (code == 0x200c) return "b";
  7796. else return "L";
  7797. }
  7798. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7799. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7800. // Browsers seem to always treat the boundaries of block elements as being L.
  7801. var outerType = "L";
  7802. function BidiSpan(level, from, to) {
  7803. this.level = level;
  7804. this.from = from; this.to = to;
  7805. }
  7806. return function(str) {
  7807. if (!bidiRE.test(str)) return false;
  7808. var len = str.length, types = [];
  7809. for (var i = 0, type; i < len; ++i)
  7810. types.push(type = charType(str.charCodeAt(i)));
  7811. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7812. // change the type of the NSM to the type of the previous
  7813. // character. If the NSM is at the start of the level run, it will
  7814. // get the type of sor.
  7815. for (var i = 0, prev = outerType; i < len; ++i) {
  7816. var type = types[i];
  7817. if (type == "m") types[i] = prev;
  7818. else prev = type;
  7819. }
  7820. // W2. Search backwards from each instance of a European number
  7821. // until the first strong type (R, L, AL, or sor) is found. If an
  7822. // AL is found, change the type of the European number to Arabic
  7823. // number.
  7824. // W3. Change all ALs to R.
  7825. for (var i = 0, cur = outerType; i < len; ++i) {
  7826. var type = types[i];
  7827. if (type == "1" && cur == "r") types[i] = "n";
  7828. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7829. }
  7830. // W4. A single European separator between two European numbers
  7831. // changes to a European number. A single common separator between
  7832. // two numbers of the same type changes to that type.
  7833. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7834. var type = types[i];
  7835. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  7836. else if (type == "," && prev == types[i+1] &&
  7837. (prev == "1" || prev == "n")) types[i] = prev;
  7838. prev = type;
  7839. }
  7840. // W5. A sequence of European terminators adjacent to European
  7841. // numbers changes to all European numbers.
  7842. // W6. Otherwise, separators and terminators change to Other
  7843. // Neutral.
  7844. for (var i = 0; i < len; ++i) {
  7845. var type = types[i];
  7846. if (type == ",") types[i] = "N";
  7847. else if (type == "%") {
  7848. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  7849. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7850. for (var j = i; j < end; ++j) types[j] = replace;
  7851. i = end - 1;
  7852. }
  7853. }
  7854. // W7. Search backwards from each instance of a European number
  7855. // until the first strong type (R, L, or sor) is found. If an L is
  7856. // found, then change the type of the European number to L.
  7857. for (var i = 0, cur = outerType; i < len; ++i) {
  7858. var type = types[i];
  7859. if (cur == "L" && type == "1") types[i] = "L";
  7860. else if (isStrong.test(type)) cur = type;
  7861. }
  7862. // N1. A sequence of neutrals takes the direction of the
  7863. // surrounding strong text if the text on both sides has the same
  7864. // direction. European and Arabic numbers act as if they were R in
  7865. // terms of their influence on neutrals. Start-of-level-run (sor)
  7866. // and end-of-level-run (eor) are used at level run boundaries.
  7867. // N2. Any remaining neutrals take the embedding direction.
  7868. for (var i = 0; i < len; ++i) {
  7869. if (isNeutral.test(types[i])) {
  7870. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  7871. var before = (i ? types[i-1] : outerType) == "L";
  7872. var after = (end < len ? types[end] : outerType) == "L";
  7873. var replace = before || after ? "L" : "R";
  7874. for (var j = i; j < end; ++j) types[j] = replace;
  7875. i = end - 1;
  7876. }
  7877. }
  7878. // Here we depart from the documented algorithm, in order to avoid
  7879. // building up an actual levels array. Since there are only three
  7880. // levels (0, 1, 2) in an implementation that doesn't take
  7881. // explicit embedding into account, we can build up the order on
  7882. // the fly, without following the level-based algorithm.
  7883. var order = [], m;
  7884. for (var i = 0; i < len;) {
  7885. if (countsAsLeft.test(types[i])) {
  7886. var start = i;
  7887. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  7888. order.push(new BidiSpan(0, start, i));
  7889. } else {
  7890. var pos = i, at = order.length;
  7891. for (++i; i < len && types[i] != "L"; ++i) {}
  7892. for (var j = pos; j < i;) {
  7893. if (countsAsNum.test(types[j])) {
  7894. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  7895. var nstart = j;
  7896. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  7897. order.splice(at, 0, new BidiSpan(2, nstart, j));
  7898. pos = j;
  7899. } else ++j;
  7900. }
  7901. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  7902. }
  7903. }
  7904. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  7905. order[0].from = m[0].length;
  7906. order.unshift(new BidiSpan(0, 0, m[0].length));
  7907. }
  7908. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  7909. lst(order).to -= m[0].length;
  7910. order.push(new BidiSpan(0, len - m[0].length, len));
  7911. }
  7912. if (order[0].level == 2)
  7913. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  7914. if (order[0].level != lst(order).level)
  7915. order.push(new BidiSpan(order[0].level, len, len));
  7916. return order;
  7917. };
  7918. })();
  7919. // THE END
  7920. CodeMirror.version = "5.3.0";
  7921. return CodeMirror;
  7922. });