codemirror.js 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799
  1. // CodeMirror version 3.15
  2. //
  3. // CodeMirror is the only global var we claim
  4. window.CodeMirror = (function() {
  5. "use strict";
  6. // BROWSER SNIFFING
  7. // Crude, but necessary to handle a number of hard-to-feature-detect
  8. // bugs and behavior differences.
  9. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  10. var ie = /MSIE \d/.test(navigator.userAgent);
  11. var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
  12. var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
  13. var webkit = /WebKit\//.test(navigator.userAgent);
  14. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  15. var chrome = /Chrome\//.test(navigator.userAgent);
  16. var opera = /Opera\//.test(navigator.userAgent);
  17. var safari = /Apple Computer/.test(navigator.vendor);
  18. var khtml = /KHTML\//.test(navigator.userAgent);
  19. var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
  20. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  21. var phantom = /PhantomJS/.test(navigator.userAgent);
  22. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  23. // This is woefully incomplete. Suggestions for alternative methods welcome.
  24. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
  25. var mac = ios || /Mac/.test(navigator.platform);
  26. var windows = /windows/i.test(navigator.platform);
  27. var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
  28. if (opera_version) opera_version = Number(opera_version[1]);
  29. if (opera_version && opera_version >= 15) { opera = false; webkit = true; }
  30. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  31. var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
  32. var captureMiddleClick = gecko || (ie && !ie_lt9);
  33. // Optimize some code when these features are not used
  34. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  35. // CONSTRUCTOR
  36. function CodeMirror(place, options) {
  37. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  38. this.options = options = options || {};
  39. // Determine effective options based on given values and defaults.
  40. for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
  41. options[opt] = defaults[opt];
  42. setGuttersForLineNumbers(options);
  43. var docStart = typeof options.value == "string" ? 0 : options.value.first;
  44. var display = this.display = makeDisplay(place, docStart);
  45. display.wrapper.CodeMirror = this;
  46. updateGutters(this);
  47. if (options.autofocus && !mobile) focusInput(this);
  48. this.state = {keyMaps: [],
  49. overlays: [],
  50. modeGen: 0,
  51. overwrite: false, focused: false,
  52. suppressEdits: false, pasteIncoming: false,
  53. draggingText: false,
  54. highlight: new Delayed()};
  55. themeChanged(this);
  56. if (options.lineWrapping)
  57. this.display.wrapper.className += " CodeMirror-wrap";
  58. var doc = options.value;
  59. if (typeof doc == "string") doc = new Doc(options.value, options.mode);
  60. operation(this, attachDoc)(this, doc);
  61. // Override magic textarea content restore that IE sometimes does
  62. // on our hidden textarea on reload
  63. if (ie) setTimeout(bind(resetInput, this, true), 20);
  64. registerEventHandlers(this);
  65. // IE throws unspecified error in certain cases, when
  66. // trying to access activeElement before onload
  67. var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
  68. if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
  69. else onBlur(this);
  70. operation(this, function() {
  71. for (var opt in optionHandlers)
  72. if (optionHandlers.propertyIsEnumerable(opt))
  73. optionHandlers[opt](this, options[opt], Init);
  74. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  75. })();
  76. }
  77. // DISPLAY CONSTRUCTOR
  78. function makeDisplay(place, docStart) {
  79. var d = {};
  80. var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");
  81. if (webkit) input.style.width = "1000px";
  82. else input.setAttribute("wrap", "off");
  83. // if border: 0; -- iOS fails to open keyboard (issue #1287)
  84. if (ios) input.style.border = "1px solid black";
  85. input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
  86. // Wraps and hides input textarea
  87. d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  88. // The actual fake scrollbars.
  89. d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
  90. d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
  91. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  92. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  93. // DIVs containing the selection and the actual code
  94. d.lineDiv = elt("div", null, "CodeMirror-code");
  95. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  96. // Blinky cursor, and element used to ensure cursor fits at the end of a line
  97. d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
  98. // Secondary cursor, shown when on a 'jump' in bi-directional text
  99. d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
  100. // Used to measure text size
  101. d.measure = elt("div", null, "CodeMirror-measure");
  102. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  103. d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
  104. null, "position: relative; outline: none");
  105. // Moved around its parent to cover visible view
  106. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  107. // Set to the height of the text, causes scrolling
  108. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  109. // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
  110. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
  111. // Will contain the gutters, if any
  112. d.gutters = elt("div", null, "CodeMirror-gutters");
  113. d.lineGutter = null;
  114. // Provides scrolling
  115. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  116. d.scroller.setAttribute("tabIndex", "-1");
  117. // The element in which the editor lives.
  118. d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
  119. d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  120. // Work around IE7 z-index bug
  121. if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  122. if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
  123. // Needed to hide big blue blinking cursor on Mobile Safari
  124. if (ios) input.style.width = "0px";
  125. if (!webkit) d.scroller.draggable = true;
  126. // Needed to handle Tab key in KHTML
  127. if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
  128. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  129. else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
  130. // Current visible range (may be bigger than the view window).
  131. d.viewOffset = d.lastSizeC = 0;
  132. d.showingFrom = d.showingTo = docStart;
  133. // Used to only resize the line number gutter when necessary (when
  134. // the amount of lines crosses a boundary that makes its width change)
  135. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  136. // See readInput and resetInput
  137. d.prevInput = "";
  138. // Set to true when a non-horizontal-scrolling widget is added. As
  139. // an optimization, widget aligning is skipped when d is false.
  140. d.alignWidgets = false;
  141. // Flag that indicates whether we currently expect input to appear
  142. // (after some event like 'keypress' or 'input') and are polling
  143. // intensively.
  144. d.pollingFast = false;
  145. // Self-resetting timeout for the poller
  146. d.poll = new Delayed();
  147. d.cachedCharWidth = d.cachedTextHeight = null;
  148. d.measureLineCache = [];
  149. d.measureLineCachePos = 0;
  150. // Tracks when resetInput has punted to just putting a short
  151. // string instead of the (large) selection.
  152. d.inaccurateSelection = false;
  153. // Tracks the maximum line length so that the horizontal scrollbar
  154. // can be kept static when scrolling.
  155. d.maxLine = null;
  156. d.maxLineLength = 0;
  157. d.maxLineChanged = false;
  158. // Used for measuring wheel scrolling granularity
  159. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  160. return d;
  161. }
  162. // STATE UPDATES
  163. // Used to get the editor into a consistent state again when options change.
  164. function loadMode(cm) {
  165. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  166. cm.doc.iter(function(line) {
  167. if (line.stateAfter) line.stateAfter = null;
  168. if (line.styles) line.styles = null;
  169. });
  170. cm.doc.frontier = cm.doc.first;
  171. startWorker(cm, 100);
  172. cm.state.modeGen++;
  173. if (cm.curOp) regChange(cm);
  174. }
  175. function wrappingChanged(cm) {
  176. if (cm.options.lineWrapping) {
  177. cm.display.wrapper.className += " CodeMirror-wrap";
  178. cm.display.sizer.style.minWidth = "";
  179. } else {
  180. cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
  181. computeMaxLength(cm);
  182. }
  183. estimateLineHeights(cm);
  184. regChange(cm);
  185. clearCaches(cm);
  186. setTimeout(function(){updateScrollbars(cm);}, 100);
  187. }
  188. function estimateHeight(cm) {
  189. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  190. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  191. return function(line) {
  192. if (lineIsHidden(cm.doc, line))
  193. return 0;
  194. else if (wrapping)
  195. return (Math.ceil(line.text.length / perLine) || 1) * th;
  196. else
  197. return th;
  198. };
  199. }
  200. function estimateLineHeights(cm) {
  201. var doc = cm.doc, est = estimateHeight(cm);
  202. doc.iter(function(line) {
  203. var estHeight = est(line);
  204. if (estHeight != line.height) updateLineHeight(line, estHeight);
  205. });
  206. }
  207. function keyMapChanged(cm) {
  208. var map = keyMap[cm.options.keyMap], style = map.style;
  209. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
  210. (style ? " cm-keymap-" + style : "");
  211. cm.state.disableInput = map.disableInput;
  212. }
  213. function themeChanged(cm) {
  214. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  215. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  216. clearCaches(cm);
  217. }
  218. function guttersChanged(cm) {
  219. updateGutters(cm);
  220. regChange(cm);
  221. setTimeout(function(){alignHorizontally(cm);}, 20);
  222. }
  223. function updateGutters(cm) {
  224. var gutters = cm.display.gutters, specs = cm.options.gutters;
  225. removeChildren(gutters);
  226. for (var i = 0; i < specs.length; ++i) {
  227. var gutterClass = specs[i];
  228. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  229. if (gutterClass == "CodeMirror-linenumbers") {
  230. cm.display.lineGutter = gElt;
  231. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  232. }
  233. }
  234. gutters.style.display = i ? "" : "none";
  235. }
  236. function lineLength(doc, line) {
  237. if (line.height == 0) return 0;
  238. var len = line.text.length, merged, cur = line;
  239. while (merged = collapsedSpanAtStart(cur)) {
  240. var found = merged.find();
  241. cur = getLine(doc, found.from.line);
  242. len += found.from.ch - found.to.ch;
  243. }
  244. cur = line;
  245. while (merged = collapsedSpanAtEnd(cur)) {
  246. var found = merged.find();
  247. len -= cur.text.length - found.from.ch;
  248. cur = getLine(doc, found.to.line);
  249. len += cur.text.length - found.to.ch;
  250. }
  251. return len;
  252. }
  253. function computeMaxLength(cm) {
  254. var d = cm.display, doc = cm.doc;
  255. d.maxLine = getLine(doc, doc.first);
  256. d.maxLineLength = lineLength(doc, d.maxLine);
  257. d.maxLineChanged = true;
  258. doc.iter(function(line) {
  259. var len = lineLength(doc, line);
  260. if (len > d.maxLineLength) {
  261. d.maxLineLength = len;
  262. d.maxLine = line;
  263. }
  264. });
  265. }
  266. // Make sure the gutters options contains the element
  267. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  268. function setGuttersForLineNumbers(options) {
  269. var found = false;
  270. for (var i = 0; i < options.gutters.length; ++i) {
  271. if (options.gutters[i] == "CodeMirror-linenumbers") {
  272. if (options.lineNumbers) found = true;
  273. else options.gutters.splice(i--, 1);
  274. }
  275. }
  276. if (!found && options.lineNumbers)
  277. options.gutters.push("CodeMirror-linenumbers");
  278. }
  279. // SCROLLBARS
  280. // Re-synchronize the fake scrollbars with the actual size of the
  281. // content. Optionally force a scrollTop.
  282. function updateScrollbars(cm) {
  283. var d = cm.display, docHeight = cm.doc.height;
  284. var totalHeight = docHeight + paddingVert(d);
  285. d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
  286. d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px";
  287. var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
  288. var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1);
  289. var needsV = scrollHeight > (d.scroller.clientHeight + 1);
  290. if (needsV) {
  291. d.scrollbarV.style.display = "block";
  292. d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
  293. d.scrollbarV.firstChild.style.height =
  294. (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
  295. } else d.scrollbarV.style.display = "";
  296. if (needsH) {
  297. d.scrollbarH.style.display = "block";
  298. d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
  299. d.scrollbarH.firstChild.style.width =
  300. (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
  301. } else d.scrollbarH.style.display = "";
  302. if (needsH && needsV) {
  303. d.scrollbarFiller.style.display = "block";
  304. d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
  305. } else d.scrollbarFiller.style.display = "";
  306. if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  307. d.gutterFiller.style.display = "block";
  308. d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
  309. d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
  310. } else d.gutterFiller.style.display = "";
  311. if (mac_geLion && scrollbarWidth(d.measure) === 0)
  312. d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
  313. }
  314. function visibleLines(display, doc, viewPort) {
  315. var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
  316. if (typeof viewPort == "number") top = viewPort;
  317. else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
  318. top = Math.floor(top - paddingTop(display));
  319. var bottom = Math.ceil(top + height);
  320. return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
  321. }
  322. // LINE NUMBERS
  323. function alignHorizontally(cm) {
  324. var display = cm.display;
  325. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  326. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  327. var gutterW = display.gutters.offsetWidth, l = comp + "px";
  328. for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
  329. for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
  330. }
  331. if (cm.options.fixedGutter)
  332. display.gutters.style.left = (comp + gutterW) + "px";
  333. }
  334. function maybeUpdateLineNumberWidth(cm) {
  335. if (!cm.options.lineNumbers) return false;
  336. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  337. if (last.length != display.lineNumChars) {
  338. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  339. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  340. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  341. display.lineGutter.style.width = "";
  342. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
  343. display.lineNumWidth = display.lineNumInnerWidth + padding;
  344. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  345. display.lineGutter.style.width = display.lineNumWidth + "px";
  346. return true;
  347. }
  348. return false;
  349. }
  350. function lineNumberFor(options, i) {
  351. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  352. }
  353. function compensateForHScroll(display) {
  354. return getRect(display.scroller).left - getRect(display.sizer).left;
  355. }
  356. // DISPLAY DRAWING
  357. function updateDisplay(cm, changes, viewPort, forced) {
  358. var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated;
  359. var visible = visibleLines(cm.display, cm.doc, viewPort);
  360. for (;;) {
  361. if (!updateDisplayInner(cm, changes, visible, forced)) break;
  362. forced = false;
  363. updated = true;
  364. updateSelection(cm);
  365. updateScrollbars(cm);
  366. // Clip forced viewport to actual scrollable area
  367. if (viewPort)
  368. viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight,
  369. typeof viewPort == "number" ? viewPort : viewPort.top);
  370. visible = visibleLines(cm.display, cm.doc, viewPort);
  371. if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo)
  372. break;
  373. changes = [];
  374. }
  375. if (updated) {
  376. signalLater(cm, "update", cm);
  377. if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
  378. signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
  379. }
  380. return updated;
  381. }
  382. // Uses a set of changes plus the current scroll position to
  383. // determine which DOM updates have to be made, and makes the
  384. // updates.
  385. function updateDisplayInner(cm, changes, visible, forced) {
  386. var display = cm.display, doc = cm.doc;
  387. if (!display.wrapper.clientWidth) {
  388. display.showingFrom = display.showingTo = doc.first;
  389. display.viewOffset = 0;
  390. return;
  391. }
  392. // Bail out if the visible area is already rendered and nothing changed.
  393. if (!forced && changes.length == 0 &&
  394. visible.from > display.showingFrom && visible.to < display.showingTo)
  395. return;
  396. if (maybeUpdateLineNumberWidth(cm))
  397. changes = [{from: doc.first, to: doc.first + doc.size}];
  398. var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
  399. display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
  400. // Used to determine which lines need their line numbers updated
  401. var positionsChangedFrom = Infinity;
  402. if (cm.options.lineNumbers)
  403. for (var i = 0; i < changes.length; ++i)
  404. if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
  405. var end = doc.first + doc.size;
  406. var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
  407. var to = Math.min(end, visible.to + cm.options.viewportMargin);
  408. if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
  409. if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
  410. if (sawCollapsedSpans) {
  411. from = lineNo(visualLine(doc, getLine(doc, from)));
  412. while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
  413. }
  414. // Create a range of theoretically intact lines, and punch holes
  415. // in that using the change info.
  416. var intact = [{from: Math.max(display.showingFrom, doc.first),
  417. to: Math.min(display.showingTo, end)}];
  418. if (intact[0].from >= intact[0].to) intact = [];
  419. else intact = computeIntact(intact, changes);
  420. // When merged lines are present, we might have to reduce the
  421. // intact ranges because changes in continued fragments of the
  422. // intact lines do require the lines to be redrawn.
  423. if (sawCollapsedSpans)
  424. for (var i = 0; i < intact.length; ++i) {
  425. var range = intact[i], merged;
  426. while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
  427. var newTo = merged.find().from.line;
  428. if (newTo > range.from) range.to = newTo;
  429. else { intact.splice(i--, 1); break; }
  430. }
  431. }
  432. // Clip off the parts that won't be visible
  433. var intactLines = 0;
  434. for (var i = 0; i < intact.length; ++i) {
  435. var range = intact[i];
  436. if (range.from < from) range.from = from;
  437. if (range.to > to) range.to = to;
  438. if (range.from >= range.to) intact.splice(i--, 1);
  439. else intactLines += range.to - range.from;
  440. }
  441. if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
  442. updateViewOffset(cm);
  443. return;
  444. }
  445. intact.sort(function(a, b) {return a.from - b.from;});
  446. // Avoid crashing on IE's "unspecified error" when in iframes
  447. try {
  448. var focused = document.activeElement;
  449. } catch(e) {}
  450. if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
  451. patchDisplay(cm, from, to, intact, positionsChangedFrom);
  452. display.lineDiv.style.display = "";
  453. if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus();
  454. var different = from != display.showingFrom || to != display.showingTo ||
  455. display.lastSizeC != display.wrapper.clientHeight;
  456. // This is just a bogus formula that detects when the editor is
  457. // resized or the font size changes.
  458. if (different) {
  459. display.lastSizeC = display.wrapper.clientHeight;
  460. startWorker(cm, 400);
  461. }
  462. display.showingFrom = from; display.showingTo = to;
  463. updateHeightsInViewport(cm);
  464. updateViewOffset(cm);
  465. return true;
  466. }
  467. function updateHeightsInViewport(cm) {
  468. var display = cm.display;
  469. var prevBottom = display.lineDiv.offsetTop;
  470. for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
  471. if (ie_lt8) {
  472. var bot = node.offsetTop + node.offsetHeight;
  473. height = bot - prevBottom;
  474. prevBottom = bot;
  475. } else {
  476. var box = getRect(node);
  477. height = box.bottom - box.top;
  478. }
  479. var diff = node.lineObj.height - height;
  480. if (height < 2) height = textHeight(display);
  481. if (diff > .001 || diff < -.001) {
  482. updateLineHeight(node.lineObj, height);
  483. var widgets = node.lineObj.widgets;
  484. if (widgets) for (var i = 0; i < widgets.length; ++i)
  485. widgets[i].height = widgets[i].node.offsetHeight;
  486. }
  487. }
  488. }
  489. function updateViewOffset(cm) {
  490. var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
  491. // Position the mover div to align with the current virtual scroll position
  492. cm.display.mover.style.top = off + "px";
  493. }
  494. function computeIntact(intact, changes) {
  495. for (var i = 0, l = changes.length || 0; i < l; ++i) {
  496. var change = changes[i], intact2 = [], diff = change.diff || 0;
  497. for (var j = 0, l2 = intact.length; j < l2; ++j) {
  498. var range = intact[j];
  499. if (change.to <= range.from && change.diff) {
  500. intact2.push({from: range.from + diff, to: range.to + diff});
  501. } else if (change.to <= range.from || change.from >= range.to) {
  502. intact2.push(range);
  503. } else {
  504. if (change.from > range.from)
  505. intact2.push({from: range.from, to: change.from});
  506. if (change.to < range.to)
  507. intact2.push({from: change.to + diff, to: range.to + diff});
  508. }
  509. }
  510. intact = intact2;
  511. }
  512. return intact;
  513. }
  514. function getDimensions(cm) {
  515. var d = cm.display, left = {}, width = {};
  516. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  517. left[cm.options.gutters[i]] = n.offsetLeft;
  518. width[cm.options.gutters[i]] = n.offsetWidth;
  519. }
  520. return {fixedPos: compensateForHScroll(d),
  521. gutterTotalWidth: d.gutters.offsetWidth,
  522. gutterLeft: left,
  523. gutterWidth: width,
  524. wrapperWidth: d.wrapper.clientWidth};
  525. }
  526. function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
  527. var dims = getDimensions(cm);
  528. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  529. if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
  530. removeChildren(display.lineDiv);
  531. var container = display.lineDiv, cur = container.firstChild;
  532. function rm(node) {
  533. var next = node.nextSibling;
  534. if (webkit && mac && cm.display.currentWheelTarget == node) {
  535. node.style.display = "none";
  536. node.lineObj = null;
  537. } else {
  538. node.parentNode.removeChild(node);
  539. }
  540. return next;
  541. }
  542. var nextIntact = intact.shift(), lineN = from;
  543. cm.doc.iter(from, to, function(line) {
  544. if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
  545. if (lineIsHidden(cm.doc, line)) {
  546. if (line.height != 0) updateLineHeight(line, 0);
  547. if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) {
  548. var w = line.widgets[i];
  549. if (w.showIfHidden) {
  550. var prev = cur.previousSibling;
  551. if (/pre/i.test(prev.nodeName)) {
  552. var wrap = elt("div", null, null, "position: relative");
  553. prev.parentNode.replaceChild(wrap, prev);
  554. wrap.appendChild(prev);
  555. prev = wrap;
  556. }
  557. var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget"));
  558. if (!w.handleMouseEvents) wnode.ignoreEvents = true;
  559. positionLineWidget(w, wnode, prev, dims);
  560. }
  561. }
  562. } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
  563. // This line is intact. Skip to the actual node. Update its
  564. // line number if needed.
  565. while (cur.lineObj != line) cur = rm(cur);
  566. if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
  567. setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
  568. cur = cur.nextSibling;
  569. } else {
  570. // For lines with widgets, make an attempt to find and reuse
  571. // the existing element, so that widgets aren't needlessly
  572. // removed and re-inserted into the dom
  573. if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
  574. if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
  575. // This line needs to be generated.
  576. var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
  577. if (lineNode != reuse) {
  578. container.insertBefore(lineNode, cur);
  579. } else {
  580. while (cur != reuse) cur = rm(cur);
  581. cur = cur.nextSibling;
  582. }
  583. lineNode.lineObj = line;
  584. }
  585. ++lineN;
  586. });
  587. while (cur) cur = rm(cur);
  588. }
  589. function buildLineElement(cm, line, lineNo, dims, reuse) {
  590. var lineElement = lineContent(cm, line);
  591. var markers = line.gutterMarkers, display = cm.display, wrap;
  592. if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets)
  593. return lineElement;
  594. // Lines with gutter elements, widgets or a background class need
  595. // to be wrapped again, and have the extra elements added to the
  596. // wrapper div
  597. if (reuse) {
  598. reuse.alignable = null;
  599. var isOk = true, widgetsSeen = 0, insertBefore = null;
  600. for (var n = reuse.firstChild, next; n; n = next) {
  601. next = n.nextSibling;
  602. if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
  603. reuse.removeChild(n);
  604. } else {
  605. for (var i = 0; i < line.widgets.length; ++i) {
  606. var widget = line.widgets[i];
  607. if (widget.node == n.firstChild) {
  608. if (!widget.above && !insertBefore) insertBefore = n;
  609. positionLineWidget(widget, n, reuse, dims);
  610. ++widgetsSeen;
  611. break;
  612. }
  613. }
  614. if (i == line.widgets.length) { isOk = false; break; }
  615. }
  616. }
  617. reuse.insertBefore(lineElement, insertBefore);
  618. if (isOk && widgetsSeen == line.widgets.length) {
  619. wrap = reuse;
  620. reuse.className = line.wrapClass || "";
  621. }
  622. }
  623. if (!wrap) {
  624. wrap = elt("div", null, line.wrapClass, "position: relative");
  625. wrap.appendChild(lineElement);
  626. }
  627. // Kludge to make sure the styled element lies behind the selection (by z-index)
  628. if (line.bgClass)
  629. wrap.insertBefore(elt("div", null, line.bgClass + " CodeMirror-linebackground"), wrap.firstChild);
  630. if (cm.options.lineNumbers || markers) {
  631. var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " +
  632. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
  633. wrap.firstChild);
  634. if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
  635. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  636. wrap.lineNumber = gutterWrap.appendChild(
  637. elt("div", lineNumberFor(cm.options, lineNo),
  638. "CodeMirror-linenumber CodeMirror-gutter-elt",
  639. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  640. + display.lineNumInnerWidth + "px"));
  641. if (markers)
  642. for (var k = 0; k < cm.options.gutters.length; ++k) {
  643. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  644. if (found)
  645. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  646. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  647. }
  648. }
  649. if (ie_lt8) wrap.style.zIndex = 2;
  650. if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  651. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  652. if (!widget.handleMouseEvents) node.ignoreEvents = true;
  653. positionLineWidget(widget, node, wrap, dims);
  654. if (widget.above)
  655. wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
  656. else
  657. wrap.appendChild(node);
  658. signalLater(widget, "redraw");
  659. }
  660. return wrap;
  661. }
  662. function positionLineWidget(widget, node, wrap, dims) {
  663. if (widget.noHScroll) {
  664. (wrap.alignable || (wrap.alignable = [])).push(node);
  665. var width = dims.wrapperWidth;
  666. node.style.left = dims.fixedPos + "px";
  667. if (!widget.coverGutter) {
  668. width -= dims.gutterTotalWidth;
  669. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  670. }
  671. node.style.width = width + "px";
  672. }
  673. if (widget.coverGutter) {
  674. node.style.zIndex = 5;
  675. node.style.position = "relative";
  676. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  677. }
  678. }
  679. // SELECTION / CURSOR
  680. function updateSelection(cm) {
  681. var display = cm.display;
  682. var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
  683. if (collapsed || cm.options.showCursorWhenSelecting)
  684. updateSelectionCursor(cm);
  685. else
  686. display.cursor.style.display = display.otherCursor.style.display = "none";
  687. if (!collapsed)
  688. updateSelectionRange(cm);
  689. else
  690. display.selectionDiv.style.display = "none";
  691. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  692. if (cm.options.moveInputWithCursor) {
  693. var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
  694. var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
  695. display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  696. headPos.top + lineOff.top - wrapOff.top)) + "px";
  697. display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  698. headPos.left + lineOff.left - wrapOff.left)) + "px";
  699. }
  700. }
  701. // No selection, plain cursor
  702. function updateSelectionCursor(cm) {
  703. var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
  704. display.cursor.style.left = pos.left + "px";
  705. display.cursor.style.top = pos.top + "px";
  706. display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  707. display.cursor.style.display = "";
  708. if (pos.other) {
  709. display.otherCursor.style.display = "";
  710. display.otherCursor.style.left = pos.other.left + "px";
  711. display.otherCursor.style.top = pos.other.top + "px";
  712. display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  713. } else { display.otherCursor.style.display = "none"; }
  714. }
  715. // Highlight selection
  716. function updateSelectionRange(cm) {
  717. var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
  718. var fragment = document.createDocumentFragment();
  719. var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
  720. function add(left, top, width, bottom) {
  721. if (top < 0) top = 0;
  722. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  723. "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
  724. "px; height: " + (bottom - top) + "px"));
  725. }
  726. function drawForLine(line, fromArg, toArg) {
  727. var lineObj = getLine(doc, line);
  728. var lineLen = lineObj.text.length;
  729. var start, end;
  730. function coords(ch, bias) {
  731. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  732. }
  733. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  734. var leftPos = coords(from, "left"), rightPos, left, right;
  735. if (from == to) {
  736. rightPos = leftPos;
  737. left = right = leftPos.left;
  738. } else {
  739. rightPos = coords(to - 1, "right");
  740. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  741. left = leftPos.left;
  742. right = rightPos.right;
  743. }
  744. if (fromArg == null && from == 0) left = pl;
  745. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  746. add(left, leftPos.top, null, leftPos.bottom);
  747. left = pl;
  748. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  749. }
  750. if (toArg == null && to == lineLen) right = clientWidth;
  751. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  752. start = leftPos;
  753. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  754. end = rightPos;
  755. if (left < pl + 1) left = pl;
  756. add(left, rightPos.top, right - left, rightPos.bottom);
  757. });
  758. return {start: start, end: end};
  759. }
  760. if (sel.from.line == sel.to.line) {
  761. drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
  762. } else {
  763. var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line);
  764. var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine);
  765. var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end;
  766. var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start;
  767. if (singleVLine) {
  768. if (leftEnd.top < rightStart.top - 2) {
  769. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  770. add(pl, rightStart.top, rightStart.left, rightStart.bottom);
  771. } else {
  772. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  773. }
  774. }
  775. if (leftEnd.bottom < rightStart.top)
  776. add(pl, leftEnd.bottom, null, rightStart.top);
  777. }
  778. removeChildrenAndAdd(display.selectionDiv, fragment);
  779. display.selectionDiv.style.display = "";
  780. }
  781. // Cursor-blinking
  782. function restartBlink(cm) {
  783. if (!cm.state.focused) return;
  784. var display = cm.display;
  785. clearInterval(display.blinker);
  786. var on = true;
  787. display.cursor.style.visibility = display.otherCursor.style.visibility = "";
  788. display.blinker = setInterval(function() {
  789. display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
  790. }, cm.options.cursorBlinkRate);
  791. }
  792. // HIGHLIGHT WORKER
  793. function startWorker(cm, time) {
  794. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
  795. cm.state.highlight.set(time, bind(highlightWorker, cm));
  796. }
  797. function highlightWorker(cm) {
  798. var doc = cm.doc;
  799. if (doc.frontier < doc.first) doc.frontier = doc.first;
  800. if (doc.frontier >= cm.display.showingTo) return;
  801. var end = +new Date + cm.options.workTime;
  802. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  803. var changed = [], prevChange;
  804. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
  805. if (doc.frontier >= cm.display.showingFrom) { // Visible
  806. var oldStyles = line.styles;
  807. line.styles = highlightLine(cm, line, state);
  808. var ischange = !oldStyles || oldStyles.length != line.styles.length;
  809. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  810. if (ischange) {
  811. if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
  812. else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
  813. }
  814. line.stateAfter = copyState(doc.mode, state);
  815. } else {
  816. processLine(cm, line, state);
  817. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  818. }
  819. ++doc.frontier;
  820. if (+new Date > end) {
  821. startWorker(cm, cm.options.workDelay);
  822. return true;
  823. }
  824. });
  825. if (changed.length)
  826. operation(cm, function() {
  827. for (var i = 0; i < changed.length; ++i)
  828. regChange(this, changed[i].start, changed[i].end);
  829. })();
  830. }
  831. // Finds the line to start with when starting a parse. Tries to
  832. // find a line with a stateAfter, so that it can start with a
  833. // valid state. If that fails, it returns the line with the
  834. // smallest indentation, which tends to need the least context to
  835. // parse correctly.
  836. function findStartLine(cm, n, precise) {
  837. var minindent, minline, doc = cm.doc;
  838. for (var search = n, lim = n - 100; search > lim; --search) {
  839. if (search <= doc.first) return doc.first;
  840. var line = getLine(doc, search - 1);
  841. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  842. var indented = countColumn(line.text, null, cm.options.tabSize);
  843. if (minline == null || minindent > indented) {
  844. minline = search - 1;
  845. minindent = indented;
  846. }
  847. }
  848. return minline;
  849. }
  850. function getStateBefore(cm, n, precise) {
  851. var doc = cm.doc, display = cm.display;
  852. if (!doc.mode.startState) return true;
  853. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  854. if (!state) state = startState(doc.mode);
  855. else state = copyState(doc.mode, state);
  856. doc.iter(pos, n, function(line) {
  857. processLine(cm, line, state);
  858. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
  859. line.stateAfter = save ? copyState(doc.mode, state) : null;
  860. ++pos;
  861. });
  862. return state;
  863. }
  864. // POSITION MEASUREMENT
  865. function paddingTop(display) {return display.lineSpace.offsetTop;}
  866. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  867. function paddingLeft(display) {
  868. var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
  869. return e.offsetLeft;
  870. }
  871. function measureChar(cm, line, ch, data, bias) {
  872. var dir = -1;
  873. data = data || measureLine(cm, line);
  874. for (var pos = ch;; pos += dir) {
  875. var r = data[pos];
  876. if (r) break;
  877. if (dir < 0 && pos == 0) dir = 1;
  878. }
  879. bias = pos > ch ? "left" : pos < ch ? "right" : bias;
  880. if (bias == "left" && r.leftSide) r = r.leftSide;
  881. else if (bias == "right" && r.rightSide) r = r.rightSide;
  882. return {left: pos < ch ? r.right : r.left,
  883. right: pos > ch ? r.left : r.right,
  884. top: r.top,
  885. bottom: r.bottom};
  886. }
  887. function findCachedMeasurement(cm, line) {
  888. var cache = cm.display.measureLineCache;
  889. for (var i = 0; i < cache.length; ++i) {
  890. var memo = cache[i];
  891. if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
  892. cm.display.scroller.clientWidth == memo.width &&
  893. memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass)
  894. return memo;
  895. }
  896. }
  897. function clearCachedMeasurement(cm, line) {
  898. var exists = findCachedMeasurement(cm, line);
  899. if (exists) exists.text = exists.measure = exists.markedSpans = null;
  900. }
  901. function measureLine(cm, line) {
  902. // First look in the cache
  903. var cached = findCachedMeasurement(cm, line);
  904. if (cached) return cached.measure;
  905. // Failing that, recompute and store result in cache
  906. var measure = measureLineInner(cm, line);
  907. var cache = cm.display.measureLineCache;
  908. var memo = {text: line.text, width: cm.display.scroller.clientWidth,
  909. markedSpans: line.markedSpans, measure: measure,
  910. classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass};
  911. if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
  912. else cache.push(memo);
  913. return measure;
  914. }
  915. function measureLineInner(cm, line) {
  916. var display = cm.display, measure = emptyArray(line.text.length);
  917. var pre = lineContent(cm, line, measure, true);
  918. // IE does not cache element positions of inline elements between
  919. // calls to getBoundingClientRect. This makes the loop below,
  920. // which gathers the positions of all the characters on the line,
  921. // do an amount of layout work quadratic to the number of
  922. // characters. When line wrapping is off, we try to improve things
  923. // by first subdividing the line into a bunch of inline blocks, so
  924. // that IE can reuse most of the layout information from caches
  925. // for those blocks. This does interfere with line wrapping, so it
  926. // doesn't work when wrapping is on, but in that case the
  927. // situation is slightly better, since IE does cache line-wrapping
  928. // information and only recomputes per-line.
  929. if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
  930. var fragment = document.createDocumentFragment();
  931. var chunk = 10, n = pre.childNodes.length;
  932. for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
  933. var wrap = elt("div", null, null, "display: inline-block");
  934. for (var j = 0; j < chunk && n; ++j) {
  935. wrap.appendChild(pre.firstChild);
  936. --n;
  937. }
  938. fragment.appendChild(wrap);
  939. }
  940. pre.appendChild(fragment);
  941. }
  942. removeChildrenAndAdd(display.measure, pre);
  943. var outer = getRect(display.lineDiv);
  944. var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
  945. // Work around an IE7/8 bug where it will sometimes have randomly
  946. // replaced our pre with a clone at this point.
  947. if (ie_lt9 && display.measure.first != pre)
  948. removeChildrenAndAdd(display.measure, pre);
  949. function measureRect(rect) {
  950. var top = rect.top - outer.top, bot = rect.bottom - outer.top;
  951. if (bot > maxBot) bot = maxBot;
  952. if (top < 0) top = 0;
  953. for (var i = vranges.length - 2; i >= 0; i -= 2) {
  954. var rtop = vranges[i], rbot = vranges[i+1];
  955. if (rtop > bot || rbot < top) continue;
  956. if (rtop <= top && rbot >= bot ||
  957. top <= rtop && bot >= rbot ||
  958. Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
  959. vranges[i] = Math.min(top, rtop);
  960. vranges[i+1] = Math.max(bot, rbot);
  961. break;
  962. }
  963. }
  964. if (i < 0) { i = vranges.length; vranges.push(top, bot); }
  965. return {left: rect.left - outer.left,
  966. right: rect.right - outer.left,
  967. top: i, bottom: null};
  968. }
  969. function finishRect(rect) {
  970. rect.bottom = vranges[rect.top+1];
  971. rect.top = vranges[rect.top];
  972. }
  973. for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
  974. var node = cur, rect = null;
  975. // A widget might wrap, needs special care
  976. if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) {
  977. if (cur.firstChild.nodeType == 1) node = cur.firstChild;
  978. var rects = node.getClientRects();
  979. if (rects.length > 1) {
  980. rect = data[i] = measureRect(rects[0]);
  981. rect.rightSide = measureRect(rects[rects.length - 1]);
  982. }
  983. }
  984. if (!rect) rect = data[i] = measureRect(getRect(node));
  985. if (cur.measureRight) rect.right = getRect(cur.measureRight).left;
  986. if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide));
  987. }
  988. for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
  989. finishRect(cur);
  990. if (cur.leftSide) finishRect(cur.leftSide);
  991. if (cur.rightSide) finishRect(cur.rightSide);
  992. }
  993. return data;
  994. }
  995. function measureLineWidth(cm, line) {
  996. var hasBadSpan = false;
  997. if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
  998. var sp = line.markedSpans[i];
  999. if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
  1000. }
  1001. var cached = !hasBadSpan && findCachedMeasurement(cm, line);
  1002. if (cached) return measureChar(cm, line, line.text.length, cached.measure, "right").right;
  1003. var pre = lineContent(cm, line, null, true);
  1004. var end = pre.appendChild(zeroWidthElement(cm.display.measure));
  1005. removeChildrenAndAdd(cm.display.measure, pre);
  1006. return getRect(end).right - getRect(cm.display.lineDiv).left;
  1007. }
  1008. function clearCaches(cm) {
  1009. cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
  1010. cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
  1011. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  1012. cm.display.lineNumChars = null;
  1013. }
  1014. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  1015. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  1016. // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
  1017. function intoCoordSystem(cm, lineObj, rect, context) {
  1018. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  1019. var size = widgetHeight(lineObj.widgets[i]);
  1020. rect.top += size; rect.bottom += size;
  1021. }
  1022. if (context == "line") return rect;
  1023. if (!context) context = "local";
  1024. var yOff = heightAtLine(cm, lineObj);
  1025. if (context == "local") yOff += paddingTop(cm.display);
  1026. else yOff -= cm.display.viewOffset;
  1027. if (context == "page" || context == "window") {
  1028. var lOff = getRect(cm.display.lineSpace);
  1029. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  1030. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  1031. rect.left += xOff; rect.right += xOff;
  1032. }
  1033. rect.top += yOff; rect.bottom += yOff;
  1034. return rect;
  1035. }
  1036. // Context may be "window", "page", "div", or "local"/null
  1037. // Result is in "div" coords
  1038. function fromCoordSystem(cm, coords, context) {
  1039. if (context == "div") return coords;
  1040. var left = coords.left, top = coords.top;
  1041. // First move into "page" coordinate system
  1042. if (context == "page") {
  1043. left -= pageScrollX();
  1044. top -= pageScrollY();
  1045. } else if (context == "local" || !context) {
  1046. var localBox = getRect(cm.display.sizer);
  1047. left += localBox.left;
  1048. top += localBox.top;
  1049. }
  1050. var lineSpaceBox = getRect(cm.display.lineSpace);
  1051. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  1052. }
  1053. function charCoords(cm, pos, context, lineObj, bias) {
  1054. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  1055. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context);
  1056. }
  1057. function cursorCoords(cm, pos, context, lineObj, measurement) {
  1058. lineObj = lineObj || getLine(cm.doc, pos.line);
  1059. if (!measurement) measurement = measureLine(cm, lineObj);
  1060. function get(ch, right) {
  1061. var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left");
  1062. if (right) m.left = m.right; else m.right = m.left;
  1063. return intoCoordSystem(cm, lineObj, m, context);
  1064. }
  1065. function getBidi(ch, partPos) {
  1066. var part = order[partPos], right = part.level % 2;
  1067. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  1068. part = order[--partPos];
  1069. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  1070. right = true;
  1071. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  1072. part = order[++partPos];
  1073. ch = bidiLeft(part) - part.level % 2;
  1074. right = false;
  1075. }
  1076. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  1077. return get(ch, right);
  1078. }
  1079. var order = getOrder(lineObj), ch = pos.ch;
  1080. if (!order) return get(ch);
  1081. var partPos = getBidiPartAt(order, ch);
  1082. var val = getBidi(ch, partPos);
  1083. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  1084. return val;
  1085. }
  1086. function PosWithInfo(line, ch, outside, xRel) {
  1087. var pos = new Pos(line, ch);
  1088. pos.xRel = xRel;
  1089. if (outside) pos.outside = true;
  1090. return pos;
  1091. }
  1092. // Coords must be lineSpace-local
  1093. function coordsChar(cm, x, y) {
  1094. var doc = cm.doc;
  1095. y += cm.display.viewOffset;
  1096. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  1097. var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  1098. if (lineNo > last)
  1099. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  1100. if (x < 0) x = 0;
  1101. for (;;) {
  1102. var lineObj = getLine(doc, lineNo);
  1103. var found = coordsCharInner(cm, lineObj, lineNo, x, y);
  1104. var merged = collapsedSpanAtEnd(lineObj);
  1105. var mergedPos = merged && merged.find();
  1106. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  1107. lineNo = mergedPos.to.line;
  1108. else
  1109. return found;
  1110. }
  1111. }
  1112. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  1113. var innerOff = y - heightAtLine(cm, lineObj);
  1114. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  1115. var measurement = measureLine(cm, lineObj);
  1116. function getX(ch) {
  1117. var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
  1118. lineObj, measurement);
  1119. wrongLine = true;
  1120. if (innerOff > sp.bottom) return sp.left - adjust;
  1121. else if (innerOff < sp.top) return sp.left + adjust;
  1122. else wrongLine = false;
  1123. return sp.left;
  1124. }
  1125. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  1126. var from = lineLeft(lineObj), to = lineRight(lineObj);
  1127. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  1128. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  1129. // Do a binary search between these bounds.
  1130. for (;;) {
  1131. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  1132. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  1133. var xDiff = x - (ch == from ? fromX : toX);
  1134. while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
  1135. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  1136. xDiff < 0 ? -1 : xDiff ? 1 : 0);
  1137. return pos;
  1138. }
  1139. var step = Math.ceil(dist / 2), middle = from + step;
  1140. if (bidi) {
  1141. middle = from;
  1142. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  1143. }
  1144. var middleX = getX(middle);
  1145. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  1146. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  1147. }
  1148. }
  1149. var measureText;
  1150. function textHeight(display) {
  1151. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  1152. if (measureText == null) {
  1153. measureText = elt("pre");
  1154. // Measure a bunch of lines, for browsers that compute
  1155. // fractional heights.
  1156. for (var i = 0; i < 49; ++i) {
  1157. measureText.appendChild(document.createTextNode("x"));
  1158. measureText.appendChild(elt("br"));
  1159. }
  1160. measureText.appendChild(document.createTextNode("x"));
  1161. }
  1162. removeChildrenAndAdd(display.measure, measureText);
  1163. var height = measureText.offsetHeight / 50;
  1164. if (height > 3) display.cachedTextHeight = height;
  1165. removeChildren(display.measure);
  1166. return height || 1;
  1167. }
  1168. function charWidth(display) {
  1169. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  1170. var anchor = elt("span", "x");
  1171. var pre = elt("pre", [anchor]);
  1172. removeChildrenAndAdd(display.measure, pre);
  1173. var width = anchor.offsetWidth;
  1174. if (width > 2) display.cachedCharWidth = width;
  1175. return width || 10;
  1176. }
  1177. // OPERATIONS
  1178. // Operations are used to wrap changes in such a way that each
  1179. // change won't have to update the cursor and display (which would
  1180. // be awkward, slow, and error-prone), but instead updates are
  1181. // batched and then all combined and executed at once.
  1182. var nextOpId = 0;
  1183. function startOperation(cm) {
  1184. cm.curOp = {
  1185. // An array of ranges of lines that have to be updated. See
  1186. // updateDisplay.
  1187. changes: [],
  1188. forceUpdate: false,
  1189. updateInput: null,
  1190. userSelChange: null,
  1191. textChanged: null,
  1192. selectionChanged: false,
  1193. cursorActivity: false,
  1194. updateMaxLine: false,
  1195. updateScrollPos: false,
  1196. id: ++nextOpId
  1197. };
  1198. if (!delayedCallbackDepth++) delayedCallbacks = [];
  1199. }
  1200. function endOperation(cm) {
  1201. var op = cm.curOp, doc = cm.doc, display = cm.display;
  1202. cm.curOp = null;
  1203. if (op.updateMaxLine) computeMaxLength(cm);
  1204. if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) {
  1205. var width = measureLineWidth(cm, display.maxLine);
  1206. display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
  1207. display.maxLineChanged = false;
  1208. var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
  1209. if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
  1210. setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
  1211. }
  1212. var newScrollPos, updated;
  1213. if (op.updateScrollPos) {
  1214. newScrollPos = op.updateScrollPos;
  1215. } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
  1216. var coords = cursorCoords(cm, doc.sel.head);
  1217. newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
  1218. }
  1219. if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) {
  1220. updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate);
  1221. if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
  1222. }
  1223. if (!updated && op.selectionChanged) updateSelection(cm);
  1224. if (op.updateScrollPos) {
  1225. display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop;
  1226. display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft;
  1227. alignHorizontally(cm);
  1228. if (op.scrollToPos)
  1229. scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin);
  1230. } else if (newScrollPos) {
  1231. scrollCursorIntoView(cm);
  1232. }
  1233. if (op.selectionChanged) restartBlink(cm);
  1234. if (cm.state.focused && op.updateInput)
  1235. resetInput(cm, op.userSelChange);
  1236. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  1237. if (hidden) for (var i = 0; i < hidden.length; ++i)
  1238. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  1239. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  1240. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  1241. var delayed;
  1242. if (!--delayedCallbackDepth) {
  1243. delayed = delayedCallbacks;
  1244. delayedCallbacks = null;
  1245. }
  1246. if (op.textChanged)
  1247. signal(cm, "change", cm, op.textChanged);
  1248. if (op.cursorActivity) signal(cm, "cursorActivity", cm);
  1249. if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
  1250. }
  1251. // Wraps a function in an operation. Returns the wrapped function.
  1252. function operation(cm1, f) {
  1253. return function() {
  1254. var cm = cm1 || this, withOp = !cm.curOp;
  1255. if (withOp) startOperation(cm);
  1256. try { var result = f.apply(cm, arguments); }
  1257. finally { if (withOp) endOperation(cm); }
  1258. return result;
  1259. };
  1260. }
  1261. function docOperation(f) {
  1262. return function() {
  1263. var withOp = this.cm && !this.cm.curOp, result;
  1264. if (withOp) startOperation(this.cm);
  1265. try { result = f.apply(this, arguments); }
  1266. finally { if (withOp) endOperation(this.cm); }
  1267. return result;
  1268. };
  1269. }
  1270. function runInOp(cm, f) {
  1271. var withOp = !cm.curOp, result;
  1272. if (withOp) startOperation(cm);
  1273. try { result = f(); }
  1274. finally { if (withOp) endOperation(cm); }
  1275. return result;
  1276. }
  1277. function regChange(cm, from, to, lendiff) {
  1278. if (from == null) from = cm.doc.first;
  1279. if (to == null) to = cm.doc.first + cm.doc.size;
  1280. cm.curOp.changes.push({from: from, to: to, diff: lendiff});
  1281. }
  1282. // INPUT HANDLING
  1283. function slowPoll(cm) {
  1284. if (cm.display.pollingFast) return;
  1285. cm.display.poll.set(cm.options.pollInterval, function() {
  1286. readInput(cm);
  1287. if (cm.state.focused) slowPoll(cm);
  1288. });
  1289. }
  1290. function fastPoll(cm) {
  1291. var missed = false;
  1292. cm.display.pollingFast = true;
  1293. function p() {
  1294. var changed = readInput(cm);
  1295. if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
  1296. else {cm.display.pollingFast = false; slowPoll(cm);}
  1297. }
  1298. cm.display.poll.set(20, p);
  1299. }
  1300. // prevInput is a hack to work with IME. If we reset the textarea
  1301. // on every change, that breaks IME. So we look for changes
  1302. // compared to the previous content instead. (Modern browsers have
  1303. // events that indicate IME taking place, but these are not widely
  1304. // supported or compatible enough yet to rely on.)
  1305. function readInput(cm) {
  1306. var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
  1307. if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false;
  1308. var text = input.value;
  1309. if (text == prevInput && posEq(sel.from, sel.to)) return false;
  1310. if (ie && !ie_lt9 && cm.display.inputHasSelection === text) {
  1311. resetInput(cm, true);
  1312. return false;
  1313. }
  1314. var withOp = !cm.curOp;
  1315. if (withOp) startOperation(cm);
  1316. sel.shift = false;
  1317. var same = 0, l = Math.min(prevInput.length, text.length);
  1318. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1319. var from = sel.from, to = sel.to;
  1320. if (same < prevInput.length)
  1321. from = Pos(from.line, from.ch - (prevInput.length - same));
  1322. else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
  1323. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same)));
  1324. var updateInput = cm.curOp.updateInput;
  1325. var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)),
  1326. origin: cm.state.pasteIncoming ? "paste" : "+input"};
  1327. makeChange(cm.doc, changeEvent, "end");
  1328. cm.curOp.updateInput = updateInput;
  1329. signalLater(cm, "inputRead", cm, changeEvent);
  1330. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
  1331. else cm.display.prevInput = text;
  1332. if (withOp) endOperation(cm);
  1333. cm.state.pasteIncoming = false;
  1334. return true;
  1335. }
  1336. function resetInput(cm, user) {
  1337. var minimal, selected, doc = cm.doc;
  1338. if (!posEq(doc.sel.from, doc.sel.to)) {
  1339. cm.display.prevInput = "";
  1340. minimal = hasCopyEvent &&
  1341. (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
  1342. var content = minimal ? "-" : selected || cm.getSelection();
  1343. cm.display.input.value = content;
  1344. if (cm.state.focused) selectInput(cm.display.input);
  1345. if (ie && !ie_lt9) cm.display.inputHasSelection = content;
  1346. } else if (user) {
  1347. cm.display.prevInput = cm.display.input.value = "";
  1348. if (ie && !ie_lt9) cm.display.inputHasSelection = null;
  1349. }
  1350. cm.display.inaccurateSelection = minimal;
  1351. }
  1352. function focusInput(cm) {
  1353. if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
  1354. cm.display.input.focus();
  1355. }
  1356. function isReadOnly(cm) {
  1357. return cm.options.readOnly || cm.doc.cantEdit;
  1358. }
  1359. // EVENT HANDLERS
  1360. function registerEventHandlers(cm) {
  1361. var d = cm.display;
  1362. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  1363. if (ie)
  1364. on(d.scroller, "dblclick", operation(cm, function(e) {
  1365. if (signalDOMEvent(cm, e)) return;
  1366. var pos = posFromMouse(cm, e);
  1367. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  1368. e_preventDefault(e);
  1369. var word = findWordAt(getLine(cm.doc, pos.line).text, pos);
  1370. extendSelection(cm.doc, word.from, word.to);
  1371. }));
  1372. else
  1373. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  1374. on(d.lineSpace, "selectstart", function(e) {
  1375. if (!eventInWidget(d, e)) e_preventDefault(e);
  1376. });
  1377. // Gecko browsers fire contextmenu *after* opening the menu, at
  1378. // which point we can't mess with it anymore. Context menu is
  1379. // handled in onMouseDown for Gecko.
  1380. if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  1381. on(d.scroller, "scroll", function() {
  1382. if (d.scroller.clientHeight) {
  1383. setScrollTop(cm, d.scroller.scrollTop);
  1384. setScrollLeft(cm, d.scroller.scrollLeft, true);
  1385. signal(cm, "scroll", cm);
  1386. }
  1387. });
  1388. on(d.scrollbarV, "scroll", function() {
  1389. if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
  1390. });
  1391. on(d.scrollbarH, "scroll", function() {
  1392. if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
  1393. });
  1394. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  1395. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  1396. function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
  1397. on(d.scrollbarH, "mousedown", reFocus);
  1398. on(d.scrollbarV, "mousedown", reFocus);
  1399. // Prevent wrapper from ever scrolling
  1400. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  1401. var resizeTimer;
  1402. function onResize() {
  1403. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  1404. resizeTimer = null;
  1405. // Might be a text scaling operation, clear size caches.
  1406. d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null;
  1407. clearCaches(cm);
  1408. runInOp(cm, bind(regChange, cm));
  1409. }, 100);
  1410. }
  1411. on(window, "resize", onResize);
  1412. // Above handler holds on to the editor and its data structures.
  1413. // Here we poll to unregister it when the editor is no longer in
  1414. // the document, so that it can be garbage-collected.
  1415. function unregister() {
  1416. for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
  1417. if (p) setTimeout(unregister, 5000);
  1418. else off(window, "resize", onResize);
  1419. }
  1420. setTimeout(unregister, 5000);
  1421. on(d.input, "keyup", operation(cm, function(e) {
  1422. if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1423. if (e.keyCode == 16) cm.doc.sel.shift = false;
  1424. }));
  1425. on(d.input, "input", bind(fastPoll, cm));
  1426. on(d.input, "keydown", operation(cm, onKeyDown));
  1427. on(d.input, "keypress", operation(cm, onKeyPress));
  1428. on(d.input, "focus", bind(onFocus, cm));
  1429. on(d.input, "blur", bind(onBlur, cm));
  1430. function drag_(e) {
  1431. if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
  1432. e_stop(e);
  1433. }
  1434. if (cm.options.dragDrop) {
  1435. on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
  1436. on(d.scroller, "dragenter", drag_);
  1437. on(d.scroller, "dragover", drag_);
  1438. on(d.scroller, "drop", operation(cm, onDrop));
  1439. }
  1440. on(d.scroller, "paste", function(e){
  1441. if (eventInWidget(d, e)) return;
  1442. focusInput(cm);
  1443. fastPoll(cm);
  1444. });
  1445. on(d.input, "paste", function() {
  1446. cm.state.pasteIncoming = true;
  1447. fastPoll(cm);
  1448. });
  1449. function prepareCopy() {
  1450. if (d.inaccurateSelection) {
  1451. d.prevInput = "";
  1452. d.inaccurateSelection = false;
  1453. d.input.value = cm.getSelection();
  1454. selectInput(d.input);
  1455. }
  1456. }
  1457. on(d.input, "cut", prepareCopy);
  1458. on(d.input, "copy", prepareCopy);
  1459. // Needed to handle Tab key in KHTML
  1460. if (khtml) on(d.sizer, "mouseup", function() {
  1461. if (document.activeElement == d.input) d.input.blur();
  1462. focusInput(cm);
  1463. });
  1464. }
  1465. function eventInWidget(display, e) {
  1466. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  1467. if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
  1468. }
  1469. }
  1470. function posFromMouse(cm, e, liberal) {
  1471. var display = cm.display;
  1472. if (!liberal) {
  1473. var target = e_target(e);
  1474. if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
  1475. target == display.scrollbarV || target == display.scrollbarV.firstChild ||
  1476. target == display.scrollbarFiller || target == display.gutterFiller) return null;
  1477. }
  1478. var x, y, space = getRect(display.lineSpace);
  1479. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  1480. try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
  1481. return coordsChar(cm, x - space.left, y - space.top);
  1482. }
  1483. var lastClick, lastDoubleClick;
  1484. function onMouseDown(e) {
  1485. if (signalDOMEvent(this, e)) return;
  1486. var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
  1487. sel.shift = e.shiftKey;
  1488. if (eventInWidget(display, e)) {
  1489. if (!webkit) {
  1490. display.scroller.draggable = false;
  1491. setTimeout(function(){display.scroller.draggable = true;}, 100);
  1492. }
  1493. return;
  1494. }
  1495. if (clickInGutter(cm, e)) return;
  1496. var start = posFromMouse(cm, e);
  1497. switch (e_button(e)) {
  1498. case 3:
  1499. if (captureMiddleClick) onContextMenu.call(cm, cm, e);
  1500. return;
  1501. case 2:
  1502. if (start) extendSelection(cm.doc, start);
  1503. setTimeout(bind(focusInput, cm), 20);
  1504. e_preventDefault(e);
  1505. return;
  1506. }
  1507. // For button 1, if it was clicked inside the editor
  1508. // (posFromMouse returning non-null), we have to adjust the
  1509. // selection.
  1510. if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
  1511. if (!cm.state.focused) onFocus(cm);
  1512. var now = +new Date, type = "single";
  1513. if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
  1514. type = "triple";
  1515. e_preventDefault(e);
  1516. setTimeout(bind(focusInput, cm), 20);
  1517. selectLine(cm, start.line);
  1518. } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
  1519. type = "double";
  1520. lastDoubleClick = {time: now, pos: start};
  1521. e_preventDefault(e);
  1522. var word = findWordAt(getLine(doc, start.line).text, start);
  1523. extendSelection(cm.doc, word.from, word.to);
  1524. } else { lastClick = {time: now, pos: start}; }
  1525. var last = start;
  1526. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
  1527. !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
  1528. var dragEnd = operation(cm, function(e2) {
  1529. if (webkit) display.scroller.draggable = false;
  1530. cm.state.draggingText = false;
  1531. off(document, "mouseup", dragEnd);
  1532. off(display.scroller, "drop", dragEnd);
  1533. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  1534. e_preventDefault(e2);
  1535. extendSelection(cm.doc, start);
  1536. focusInput(cm);
  1537. }
  1538. });
  1539. // Let the drag handler handle this.
  1540. if (webkit) display.scroller.draggable = true;
  1541. cm.state.draggingText = dragEnd;
  1542. // IE's approach to draggable
  1543. if (display.scroller.dragDrop) display.scroller.dragDrop();
  1544. on(document, "mouseup", dragEnd);
  1545. on(display.scroller, "drop", dragEnd);
  1546. return;
  1547. }
  1548. e_preventDefault(e);
  1549. if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
  1550. var startstart = sel.from, startend = sel.to, lastPos = start;
  1551. function doSelect(cur) {
  1552. if (posEq(lastPos, cur)) return;
  1553. lastPos = cur;
  1554. if (type == "single") {
  1555. extendSelection(cm.doc, clipPos(doc, start), cur);
  1556. return;
  1557. }
  1558. startstart = clipPos(doc, startstart);
  1559. startend = clipPos(doc, startend);
  1560. if (type == "double") {
  1561. var word = findWordAt(getLine(doc, cur.line).text, cur);
  1562. if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
  1563. else extendSelection(cm.doc, startstart, word.to);
  1564. } else if (type == "triple") {
  1565. if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
  1566. else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
  1567. }
  1568. }
  1569. var editorSize = getRect(display.wrapper);
  1570. // Used to ensure timeout re-tries don't fire when another extend
  1571. // happened in the meantime (clearTimeout isn't reliable -- at
  1572. // least on Chrome, the timeouts still happen even when cleared,
  1573. // if the clear happens after their scheduled firing time).
  1574. var counter = 0;
  1575. function extend(e) {
  1576. var curCount = ++counter;
  1577. var cur = posFromMouse(cm, e, true);
  1578. if (!cur) return;
  1579. if (!posEq(cur, last)) {
  1580. if (!cm.state.focused) onFocus(cm);
  1581. last = cur;
  1582. doSelect(cur);
  1583. var visible = visibleLines(display, doc);
  1584. if (cur.line >= visible.to || cur.line < visible.from)
  1585. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  1586. } else {
  1587. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  1588. if (outside) setTimeout(operation(cm, function() {
  1589. if (counter != curCount) return;
  1590. display.scroller.scrollTop += outside;
  1591. extend(e);
  1592. }), 50);
  1593. }
  1594. }
  1595. function done(e) {
  1596. counter = Infinity;
  1597. e_preventDefault(e);
  1598. focusInput(cm);
  1599. off(document, "mousemove", move);
  1600. off(document, "mouseup", up);
  1601. }
  1602. var move = operation(cm, function(e) {
  1603. if (!ie && !e_button(e)) done(e);
  1604. else extend(e);
  1605. });
  1606. var up = operation(cm, done);
  1607. on(document, "mousemove", move);
  1608. on(document, "mouseup", up);
  1609. }
  1610. function clickInGutter(cm, e) {
  1611. var display = cm.display;
  1612. try { var mX = e.clientX, mY = e.clientY; }
  1613. catch(e) { return false; }
  1614. if (mX >= Math.floor(getRect(display.gutters).right)) return false;
  1615. e_preventDefault(e);
  1616. if (!hasHandler(cm, "gutterClick")) return true;
  1617. var lineBox = getRect(display.lineDiv);
  1618. if (mY > lineBox.bottom) return true;
  1619. mY -= lineBox.top - display.viewOffset;
  1620. for (var i = 0; i < cm.options.gutters.length; ++i) {
  1621. var g = display.gutters.childNodes[i];
  1622. if (g && getRect(g).right >= mX) {
  1623. var line = lineAtHeight(cm.doc, mY);
  1624. var gutter = cm.options.gutters[i];
  1625. signalLater(cm, "gutterClick", cm, line, gutter, e);
  1626. break;
  1627. }
  1628. }
  1629. return true;
  1630. }
  1631. // Kludge to work around strange IE behavior where it'll sometimes
  1632. // re-fire a series of drag-related events right after the drop (#1551)
  1633. var lastDrop = 0;
  1634. function onDrop(e) {
  1635. var cm = this;
  1636. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
  1637. return;
  1638. e_preventDefault(e);
  1639. if (ie) lastDrop = +new Date;
  1640. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  1641. if (!pos || isReadOnly(cm)) return;
  1642. if (files && files.length && window.FileReader && window.File) {
  1643. var n = files.length, text = Array(n), read = 0;
  1644. var loadFile = function(file, i) {
  1645. var reader = new FileReader;
  1646. reader.onload = function() {
  1647. text[i] = reader.result;
  1648. if (++read == n) {
  1649. pos = clipPos(cm.doc, pos);
  1650. makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
  1651. }
  1652. };
  1653. reader.readAsText(file);
  1654. };
  1655. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  1656. } else {
  1657. // Don't do a replace if the drop happened inside of the selected text.
  1658. if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
  1659. cm.state.draggingText(e);
  1660. // Ensure the editor is re-focused
  1661. setTimeout(bind(focusInput, cm), 20);
  1662. return;
  1663. }
  1664. try {
  1665. var text = e.dataTransfer.getData("Text");
  1666. if (text) {
  1667. var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
  1668. setSelection(cm.doc, pos, pos);
  1669. if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
  1670. cm.replaceSelection(text, null, "paste");
  1671. focusInput(cm);
  1672. onFocus(cm);
  1673. }
  1674. }
  1675. catch(e){}
  1676. }
  1677. }
  1678. function onDragStart(cm, e) {
  1679. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  1680. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  1681. var txt = cm.getSelection();
  1682. e.dataTransfer.setData("Text", txt);
  1683. // Use dummy image instead of default browsers image.
  1684. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  1685. if (e.dataTransfer.setDragImage && !safari) {
  1686. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  1687. if (opera) {
  1688. img.width = img.height = 1;
  1689. cm.display.wrapper.appendChild(img);
  1690. // Force a relayout, or Opera won't use our image for some obscure reason
  1691. img._top = img.offsetTop;
  1692. }
  1693. e.dataTransfer.setDragImage(img, 0, 0);
  1694. if (opera) img.parentNode.removeChild(img);
  1695. }
  1696. }
  1697. function setScrollTop(cm, val) {
  1698. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  1699. cm.doc.scrollTop = val;
  1700. if (!gecko) updateDisplay(cm, [], val);
  1701. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  1702. if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
  1703. if (gecko) updateDisplay(cm, []);
  1704. startWorker(cm, 100);
  1705. }
  1706. function setScrollLeft(cm, val, isScroller) {
  1707. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  1708. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  1709. cm.doc.scrollLeft = val;
  1710. alignHorizontally(cm);
  1711. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  1712. if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
  1713. }
  1714. // Since the delta values reported on mouse wheel events are
  1715. // unstandardized between browsers and even browser versions, and
  1716. // generally horribly unpredictable, this code starts by measuring
  1717. // the scroll effect that the first few mouse wheel events have,
  1718. // and, from that, detects the way it can convert deltas to pixel
  1719. // offsets afterwards.
  1720. //
  1721. // The reason we want to know the amount a wheel event will scroll
  1722. // is that it gives us a chance to update the display before the
  1723. // actual scrolling happens, reducing flickering.
  1724. var wheelSamples = 0, wheelPixelsPerUnit = null;
  1725. // Fill in a browser-detected starting value on browsers where we
  1726. // know one. These don't have to be accurate -- the result of them
  1727. // being wrong would just be a slight flicker on the first wheel
  1728. // scroll (if it is large enough).
  1729. if (ie) wheelPixelsPerUnit = -.53;
  1730. else if (gecko) wheelPixelsPerUnit = 15;
  1731. else if (chrome) wheelPixelsPerUnit = -.7;
  1732. else if (safari) wheelPixelsPerUnit = -1/3;
  1733. function onScrollWheel(cm, e) {
  1734. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  1735. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  1736. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  1737. else if (dy == null) dy = e.wheelDelta;
  1738. var display = cm.display, scroll = display.scroller;
  1739. // Quit if there's nothing to scroll here
  1740. if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
  1741. dy && scroll.scrollHeight > scroll.clientHeight)) return;
  1742. // Webkit browsers on OS X abort momentum scrolls when the target
  1743. // of the scroll event is removed from the scrollable element.
  1744. // This hack (see related code in patchDisplay) makes sure the
  1745. // element is kept around.
  1746. if (dy && mac && webkit) {
  1747. for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
  1748. if (cur.lineObj) {
  1749. cm.display.currentWheelTarget = cur;
  1750. break;
  1751. }
  1752. }
  1753. }
  1754. // On some browsers, horizontal scrolling will cause redraws to
  1755. // happen before the gutter has been realigned, causing it to
  1756. // wriggle around in a most unseemly way. When we have an
  1757. // estimated pixels/delta value, we just handle horizontal
  1758. // scrolling entirely here. It'll be slightly off from native, but
  1759. // better than glitching out.
  1760. if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
  1761. if (dy)
  1762. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  1763. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  1764. e_preventDefault(e);
  1765. display.wheelStartX = null; // Abort measurement, if in progress
  1766. return;
  1767. }
  1768. if (dy && wheelPixelsPerUnit != null) {
  1769. var pixels = dy * wheelPixelsPerUnit;
  1770. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  1771. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  1772. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  1773. updateDisplay(cm, [], {top: top, bottom: bot});
  1774. }
  1775. if (wheelSamples < 20) {
  1776. if (display.wheelStartX == null) {
  1777. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  1778. display.wheelDX = dx; display.wheelDY = dy;
  1779. setTimeout(function() {
  1780. if (display.wheelStartX == null) return;
  1781. var movedX = scroll.scrollLeft - display.wheelStartX;
  1782. var movedY = scroll.scrollTop - display.wheelStartY;
  1783. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  1784. (movedX && display.wheelDX && movedX / display.wheelDX);
  1785. display.wheelStartX = display.wheelStartY = null;
  1786. if (!sample) return;
  1787. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  1788. ++wheelSamples;
  1789. }, 200);
  1790. } else {
  1791. display.wheelDX += dx; display.wheelDY += dy;
  1792. }
  1793. }
  1794. }
  1795. function doHandleBinding(cm, bound, dropShift) {
  1796. if (typeof bound == "string") {
  1797. bound = commands[bound];
  1798. if (!bound) return false;
  1799. }
  1800. // Ensure previous input has been read, so that the handler sees a
  1801. // consistent view of the document
  1802. if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
  1803. var doc = cm.doc, prevShift = doc.sel.shift, done = false;
  1804. try {
  1805. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  1806. if (dropShift) doc.sel.shift = false;
  1807. done = bound(cm) != Pass;
  1808. } finally {
  1809. doc.sel.shift = prevShift;
  1810. cm.state.suppressEdits = false;
  1811. }
  1812. return done;
  1813. }
  1814. function allKeyMaps(cm) {
  1815. var maps = cm.state.keyMaps.slice(0);
  1816. if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
  1817. maps.push(cm.options.keyMap);
  1818. return maps;
  1819. }
  1820. var maybeTransition;
  1821. function handleKeyBinding(cm, e) {
  1822. // Handle auto keymap transitions
  1823. var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
  1824. clearTimeout(maybeTransition);
  1825. if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
  1826. if (getKeyMap(cm.options.keyMap) == startMap) {
  1827. cm.options.keyMap = (next.call ? next.call(null, cm) : next);
  1828. keyMapChanged(cm);
  1829. }
  1830. }, 50);
  1831. var name = keyName(e, true), handled = false;
  1832. if (!name) return false;
  1833. var keymaps = allKeyMaps(cm);
  1834. if (e.shiftKey) {
  1835. // First try to resolve full name (including 'Shift-'). Failing
  1836. // that, see if there is a cursor-motion command (starting with
  1837. // 'go') bound to the keyname without 'Shift-'.
  1838. handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
  1839. || lookupKey(name, keymaps, function(b) {
  1840. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  1841. return doHandleBinding(cm, b);
  1842. });
  1843. } else {
  1844. handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
  1845. }
  1846. if (handled) {
  1847. e_preventDefault(e);
  1848. restartBlink(cm);
  1849. if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
  1850. signalLater(cm, "keyHandled", cm, name, e);
  1851. }
  1852. return handled;
  1853. }
  1854. function handleCharBinding(cm, e, ch) {
  1855. var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
  1856. function(b) { return doHandleBinding(cm, b, true); });
  1857. if (handled) {
  1858. e_preventDefault(e);
  1859. restartBlink(cm);
  1860. signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
  1861. }
  1862. return handled;
  1863. }
  1864. var lastStoppedKey = null;
  1865. function onKeyDown(e) {
  1866. var cm = this;
  1867. if (!cm.state.focused) onFocus(cm);
  1868. if (ie && e.keyCode == 27) { e.returnValue = false; }
  1869. if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1870. var code = e.keyCode;
  1871. // IE does strange things with escape.
  1872. cm.doc.sel.shift = code == 16 || e.shiftKey;
  1873. // First give onKeyEvent option a chance to handle this.
  1874. var handled = handleKeyBinding(cm, e);
  1875. if (opera) {
  1876. lastStoppedKey = handled ? code : null;
  1877. // Opera has no cut event... we try to at least catch the key combo
  1878. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  1879. cm.replaceSelection("");
  1880. }
  1881. }
  1882. function onKeyPress(e) {
  1883. var cm = this;
  1884. if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1885. var keyCode = e.keyCode, charCode = e.charCode;
  1886. if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  1887. if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
  1888. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  1889. if (this.options.electricChars && this.doc.mode.electricChars &&
  1890. this.options.smartIndent && !isReadOnly(this) &&
  1891. this.doc.mode.electricChars.indexOf(ch) > -1)
  1892. setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75);
  1893. if (handleCharBinding(cm, e, ch)) return;
  1894. if (ie && !ie_lt9) cm.display.inputHasSelection = null;
  1895. fastPoll(cm);
  1896. }
  1897. function onFocus(cm) {
  1898. if (cm.options.readOnly == "nocursor") return;
  1899. if (!cm.state.focused) {
  1900. signal(cm, "focus", cm);
  1901. cm.state.focused = true;
  1902. if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
  1903. cm.display.wrapper.className += " CodeMirror-focused";
  1904. resetInput(cm, true);
  1905. }
  1906. slowPoll(cm);
  1907. restartBlink(cm);
  1908. }
  1909. function onBlur(cm) {
  1910. if (cm.state.focused) {
  1911. signal(cm, "blur", cm);
  1912. cm.state.focused = false;
  1913. cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
  1914. }
  1915. clearInterval(cm.display.blinker);
  1916. setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
  1917. }
  1918. var detectingSelectAll;
  1919. function onContextMenu(cm, e) {
  1920. if (signalDOMEvent(cm, e, "contextmenu")) return;
  1921. var display = cm.display, sel = cm.doc.sel;
  1922. if (eventInWidget(display, e)) return;
  1923. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1924. if (!pos || opera) return; // Opera is difficult.
  1925. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
  1926. operation(cm, setSelection)(cm.doc, pos, pos);
  1927. var oldCSS = display.input.style.cssText;
  1928. display.inputDiv.style.position = "absolute";
  1929. display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1930. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
  1931. "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
  1932. focusInput(cm);
  1933. resetInput(cm, true);
  1934. // Adds "Select all" to context menu in FF
  1935. if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
  1936. function prepareSelectAllHack() {
  1937. if (display.input.selectionStart != null) {
  1938. var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value);
  1939. display.prevInput = " ";
  1940. display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
  1941. }
  1942. }
  1943. function rehide() {
  1944. display.inputDiv.style.position = "relative";
  1945. display.input.style.cssText = oldCSS;
  1946. if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
  1947. slowPoll(cm);
  1948. // Try to detect the user choosing select-all
  1949. if (display.input.selectionStart != null) {
  1950. if (!ie || ie_lt9) prepareSelectAllHack();
  1951. clearTimeout(detectingSelectAll);
  1952. var i = 0, poll = function(){
  1953. if (display.prevInput == " " && display.input.selectionStart == 0)
  1954. operation(cm, commands.selectAll)(cm);
  1955. else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
  1956. else resetInput(cm);
  1957. };
  1958. detectingSelectAll = setTimeout(poll, 200);
  1959. }
  1960. }
  1961. if (ie && !ie_lt9) prepareSelectAllHack();
  1962. if (captureMiddleClick) {
  1963. e_stop(e);
  1964. var mouseup = function() {
  1965. off(window, "mouseup", mouseup);
  1966. setTimeout(rehide, 20);
  1967. };
  1968. on(window, "mouseup", mouseup);
  1969. } else {
  1970. setTimeout(rehide, 50);
  1971. }
  1972. }
  1973. // UPDATING
  1974. var changeEnd = CodeMirror.changeEnd = function(change) {
  1975. if (!change.text) return change.to;
  1976. return Pos(change.from.line + change.text.length - 1,
  1977. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  1978. };
  1979. // Make sure a position will be valid after the given change.
  1980. function clipPostChange(doc, change, pos) {
  1981. if (!posLess(change.from, pos)) return clipPos(doc, pos);
  1982. var diff = (change.text.length - 1) - (change.to.line - change.from.line);
  1983. if (pos.line > change.to.line + diff) {
  1984. var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
  1985. if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
  1986. return clipToLen(pos, getLine(doc, preLine).text.length);
  1987. }
  1988. if (pos.line == change.to.line + diff)
  1989. return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
  1990. getLine(doc, change.to.line).text.length - change.to.ch);
  1991. var inside = pos.line - change.from.line;
  1992. return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
  1993. }
  1994. // Hint can be null|"end"|"start"|"around"|{anchor,head}
  1995. function computeSelAfterChange(doc, change, hint) {
  1996. if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
  1997. return {anchor: clipPostChange(doc, change, hint.anchor),
  1998. head: clipPostChange(doc, change, hint.head)};
  1999. if (hint == "start") return {anchor: change.from, head: change.from};
  2000. var end = changeEnd(change);
  2001. if (hint == "around") return {anchor: change.from, head: end};
  2002. if (hint == "end") return {anchor: end, head: end};
  2003. // hint is null, leave the selection alone as much as possible
  2004. var adjustPos = function(pos) {
  2005. if (posLess(pos, change.from)) return pos;
  2006. if (!posLess(change.to, pos)) return end;
  2007. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  2008. if (pos.line == change.to.line) ch += end.ch - change.to.ch;
  2009. return Pos(line, ch);
  2010. };
  2011. return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
  2012. }
  2013. function filterChange(doc, change, update) {
  2014. var obj = {
  2015. canceled: false,
  2016. from: change.from,
  2017. to: change.to,
  2018. text: change.text,
  2019. origin: change.origin,
  2020. cancel: function() { this.canceled = true; }
  2021. };
  2022. if (update) obj.update = function(from, to, text, origin) {
  2023. if (from) this.from = clipPos(doc, from);
  2024. if (to) this.to = clipPos(doc, to);
  2025. if (text) this.text = text;
  2026. if (origin !== undefined) this.origin = origin;
  2027. };
  2028. signal(doc, "beforeChange", doc, obj);
  2029. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  2030. if (obj.canceled) return null;
  2031. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  2032. }
  2033. // Replace the range from from to to by the strings in replacement.
  2034. // change is a {from, to, text [, origin]} object
  2035. function makeChange(doc, change, selUpdate, ignoreReadOnly) {
  2036. if (doc.cm) {
  2037. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
  2038. if (doc.cm.state.suppressEdits) return;
  2039. }
  2040. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  2041. change = filterChange(doc, change, true);
  2042. if (!change) return;
  2043. }
  2044. // Possibly split or suppress the update based on the presence
  2045. // of read-only spans in its range.
  2046. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  2047. if (split) {
  2048. for (var i = split.length - 1; i >= 1; --i)
  2049. makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
  2050. if (split.length)
  2051. makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
  2052. } else {
  2053. makeChangeNoReadonly(doc, change, selUpdate);
  2054. }
  2055. }
  2056. function makeChangeNoReadonly(doc, change, selUpdate) {
  2057. var selAfter = computeSelAfterChange(doc, change, selUpdate);
  2058. addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  2059. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  2060. var rebased = [];
  2061. linkedDocs(doc, function(doc, sharedHist) {
  2062. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  2063. rebaseHist(doc.history, change);
  2064. rebased.push(doc.history);
  2065. }
  2066. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  2067. });
  2068. }
  2069. function makeChangeFromHistory(doc, type) {
  2070. if (doc.cm && doc.cm.state.suppressEdits) return;
  2071. var hist = doc.history;
  2072. var event = (type == "undo" ? hist.done : hist.undone).pop();
  2073. if (!event) return;
  2074. var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
  2075. anchorAfter: event.anchorBefore, headAfter: event.headBefore,
  2076. generation: hist.generation};
  2077. (type == "undo" ? hist.undone : hist.done).push(anti);
  2078. hist.generation = event.generation || ++hist.maxGeneration;
  2079. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  2080. for (var i = event.changes.length - 1; i >= 0; --i) {
  2081. var change = event.changes[i];
  2082. change.origin = type;
  2083. if (filter && !filterChange(doc, change, false)) {
  2084. (type == "undo" ? hist.done : hist.undone).length = 0;
  2085. return;
  2086. }
  2087. anti.changes.push(historyChangeFromChange(doc, change));
  2088. var after = i ? computeSelAfterChange(doc, change, null)
  2089. : {anchor: event.anchorBefore, head: event.headBefore};
  2090. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  2091. var rebased = [];
  2092. linkedDocs(doc, function(doc, sharedHist) {
  2093. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  2094. rebaseHist(doc.history, change);
  2095. rebased.push(doc.history);
  2096. }
  2097. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  2098. });
  2099. }
  2100. }
  2101. function shiftDoc(doc, distance) {
  2102. function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
  2103. doc.first += distance;
  2104. if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
  2105. doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
  2106. doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
  2107. }
  2108. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  2109. if (doc.cm && !doc.cm.curOp)
  2110. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  2111. if (change.to.line < doc.first) {
  2112. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  2113. return;
  2114. }
  2115. if (change.from.line > doc.lastLine()) return;
  2116. // Clip the change to the size of this doc
  2117. if (change.from.line < doc.first) {
  2118. var shift = change.text.length - 1 - (doc.first - change.from.line);
  2119. shiftDoc(doc, shift);
  2120. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  2121. text: [lst(change.text)], origin: change.origin};
  2122. }
  2123. var last = doc.lastLine();
  2124. if (change.to.line > last) {
  2125. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  2126. text: [change.text[0]], origin: change.origin};
  2127. }
  2128. change.removed = getBetween(doc, change.from, change.to);
  2129. if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
  2130. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
  2131. else updateDoc(doc, change, spans, selAfter);
  2132. }
  2133. function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
  2134. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  2135. var recomputeMaxLength = false, checkWidthStart = from.line;
  2136. if (!cm.options.lineWrapping) {
  2137. checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
  2138. doc.iter(checkWidthStart, to.line + 1, function(line) {
  2139. if (line == display.maxLine) {
  2140. recomputeMaxLength = true;
  2141. return true;
  2142. }
  2143. });
  2144. }
  2145. if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head))
  2146. cm.curOp.cursorActivity = true;
  2147. updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
  2148. if (!cm.options.lineWrapping) {
  2149. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  2150. var len = lineLength(doc, line);
  2151. if (len > display.maxLineLength) {
  2152. display.maxLine = line;
  2153. display.maxLineLength = len;
  2154. display.maxLineChanged = true;
  2155. recomputeMaxLength = false;
  2156. }
  2157. });
  2158. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  2159. }
  2160. // Adjust frontier, schedule worker
  2161. doc.frontier = Math.min(doc.frontier, from.line);
  2162. startWorker(cm, 400);
  2163. var lendiff = change.text.length - (to.line - from.line) - 1;
  2164. // Remember that these lines changed, for updating the display
  2165. regChange(cm, from.line, to.line + 1, lendiff);
  2166. if (hasHandler(cm, "change")) {
  2167. var changeObj = {from: from, to: to,
  2168. text: change.text,
  2169. removed: change.removed,
  2170. origin: change.origin};
  2171. if (cm.curOp.textChanged) {
  2172. for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
  2173. cur.next = changeObj;
  2174. } else cm.curOp.textChanged = changeObj;
  2175. }
  2176. }
  2177. function replaceRange(doc, code, from, to, origin) {
  2178. if (!to) to = from;
  2179. if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
  2180. if (typeof code == "string") code = splitLines(code);
  2181. makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
  2182. }
  2183. // POSITION OBJECT
  2184. function Pos(line, ch) {
  2185. if (!(this instanceof Pos)) return new Pos(line, ch);
  2186. this.line = line; this.ch = ch;
  2187. }
  2188. CodeMirror.Pos = Pos;
  2189. function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
  2190. function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
  2191. function copyPos(x) {return Pos(x.line, x.ch);}
  2192. // SELECTION
  2193. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  2194. function clipPos(doc, pos) {
  2195. if (pos.line < doc.first) return Pos(doc.first, 0);
  2196. var last = doc.first + doc.size - 1;
  2197. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  2198. return clipToLen(pos, getLine(doc, pos.line).text.length);
  2199. }
  2200. function clipToLen(pos, linelen) {
  2201. var ch = pos.ch;
  2202. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  2203. else if (ch < 0) return Pos(pos.line, 0);
  2204. else return pos;
  2205. }
  2206. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  2207. // If shift is held, this will move the selection anchor. Otherwise,
  2208. // it'll set the whole selection.
  2209. function extendSelection(doc, pos, other, bias) {
  2210. if (doc.sel.shift || doc.sel.extend) {
  2211. var anchor = doc.sel.anchor;
  2212. if (other) {
  2213. var posBefore = posLess(pos, anchor);
  2214. if (posBefore != posLess(other, anchor)) {
  2215. anchor = pos;
  2216. pos = other;
  2217. } else if (posBefore != posLess(pos, other)) {
  2218. pos = other;
  2219. }
  2220. }
  2221. setSelection(doc, anchor, pos, bias);
  2222. } else {
  2223. setSelection(doc, pos, other || pos, bias);
  2224. }
  2225. if (doc.cm) doc.cm.curOp.userSelChange = true;
  2226. }
  2227. function filterSelectionChange(doc, anchor, head) {
  2228. var obj = {anchor: anchor, head: head};
  2229. signal(doc, "beforeSelectionChange", doc, obj);
  2230. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  2231. obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
  2232. return obj;
  2233. }
  2234. // Update the selection. Last two args are only used by
  2235. // updateDoc, since they have to be expressed in the line
  2236. // numbers before the update.
  2237. function setSelection(doc, anchor, head, bias, checkAtomic) {
  2238. if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
  2239. var filtered = filterSelectionChange(doc, anchor, head);
  2240. head = filtered.head;
  2241. anchor = filtered.anchor;
  2242. }
  2243. var sel = doc.sel;
  2244. sel.goalColumn = null;
  2245. // Skip over atomic spans.
  2246. if (checkAtomic || !posEq(anchor, sel.anchor))
  2247. anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
  2248. if (checkAtomic || !posEq(head, sel.head))
  2249. head = skipAtomic(doc, head, bias, checkAtomic != "push");
  2250. if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
  2251. sel.anchor = anchor; sel.head = head;
  2252. var inv = posLess(head, anchor);
  2253. sel.from = inv ? head : anchor;
  2254. sel.to = inv ? anchor : head;
  2255. if (doc.cm)
  2256. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
  2257. doc.cm.curOp.cursorActivity = true;
  2258. signalLater(doc, "cursorActivity", doc);
  2259. }
  2260. function reCheckSelection(cm) {
  2261. setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
  2262. }
  2263. function skipAtomic(doc, pos, bias, mayClear) {
  2264. var flipped = false, curPos = pos;
  2265. var dir = bias || 1;
  2266. doc.cantEdit = false;
  2267. search: for (;;) {
  2268. var line = getLine(doc, curPos.line);
  2269. if (line.markedSpans) {
  2270. for (var i = 0; i < line.markedSpans.length; ++i) {
  2271. var sp = line.markedSpans[i], m = sp.marker;
  2272. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  2273. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  2274. if (mayClear) {
  2275. signal(m, "beforeCursorEnter");
  2276. if (m.explicitlyCleared) {
  2277. if (!line.markedSpans) break;
  2278. else {--i; continue;}
  2279. }
  2280. }
  2281. if (!m.atomic) continue;
  2282. var newPos = m.find()[dir < 0 ? "from" : "to"];
  2283. if (posEq(newPos, curPos)) {
  2284. newPos.ch += dir;
  2285. if (newPos.ch < 0) {
  2286. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  2287. else newPos = null;
  2288. } else if (newPos.ch > line.text.length) {
  2289. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  2290. else newPos = null;
  2291. }
  2292. if (!newPos) {
  2293. if (flipped) {
  2294. // Driven in a corner -- no valid cursor position found at all
  2295. // -- try again *with* clearing, if we didn't already
  2296. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  2297. // Otherwise, turn off editing until further notice, and return the start of the doc
  2298. doc.cantEdit = true;
  2299. return Pos(doc.first, 0);
  2300. }
  2301. flipped = true; newPos = pos; dir = -dir;
  2302. }
  2303. }
  2304. curPos = newPos;
  2305. continue search;
  2306. }
  2307. }
  2308. }
  2309. return curPos;
  2310. }
  2311. }
  2312. // SCROLLING
  2313. function scrollCursorIntoView(cm) {
  2314. var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin);
  2315. if (!cm.state.focused) return;
  2316. var display = cm.display, box = getRect(display.sizer), doScroll = null;
  2317. if (coords.top + box.top < 0) doScroll = true;
  2318. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  2319. if (doScroll != null && !phantom) {
  2320. var hidden = display.cursor.style.display == "none";
  2321. if (hidden) {
  2322. display.cursor.style.display = "";
  2323. display.cursor.style.left = coords.left + "px";
  2324. display.cursor.style.top = (coords.top - display.viewOffset) + "px";
  2325. }
  2326. display.cursor.scrollIntoView(doScroll);
  2327. if (hidden) display.cursor.style.display = "none";
  2328. }
  2329. }
  2330. function scrollPosIntoView(cm, pos, margin) {
  2331. if (margin == null) margin = 0;
  2332. for (;;) {
  2333. var changed = false, coords = cursorCoords(cm, pos);
  2334. var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin);
  2335. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  2336. if (scrollPos.scrollTop != null) {
  2337. setScrollTop(cm, scrollPos.scrollTop);
  2338. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  2339. }
  2340. if (scrollPos.scrollLeft != null) {
  2341. setScrollLeft(cm, scrollPos.scrollLeft);
  2342. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  2343. }
  2344. if (!changed) return coords;
  2345. }
  2346. }
  2347. function scrollIntoView(cm, x1, y1, x2, y2) {
  2348. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  2349. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  2350. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  2351. }
  2352. function calculateScrollPos(cm, x1, y1, x2, y2) {
  2353. var display = cm.display, snapMargin = textHeight(cm.display);
  2354. if (y1 < 0) y1 = 0;
  2355. var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
  2356. var docBottom = cm.doc.height + paddingVert(display);
  2357. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  2358. if (y1 < screentop) {
  2359. result.scrollTop = atTop ? 0 : y1;
  2360. } else if (y2 > screentop + screen) {
  2361. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  2362. if (newTop != screentop) result.scrollTop = newTop;
  2363. }
  2364. var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
  2365. x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
  2366. var gutterw = display.gutters.offsetWidth;
  2367. var atLeft = x1 < gutterw + 10;
  2368. if (x1 < screenleft + gutterw || atLeft) {
  2369. if (atLeft) x1 = 0;
  2370. result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
  2371. } else if (x2 > screenw + screenleft - 3) {
  2372. result.scrollLeft = x2 + 10 - screenw;
  2373. }
  2374. return result;
  2375. }
  2376. function updateScrollPos(cm, left, top) {
  2377. cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left,
  2378. scrollTop: top == null ? cm.doc.scrollTop : top};
  2379. }
  2380. function addToScrollPos(cm, left, top) {
  2381. var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
  2382. var scroll = cm.display.scroller;
  2383. pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
  2384. pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
  2385. }
  2386. // API UTILITIES
  2387. function indentLine(cm, n, how, aggressive) {
  2388. var doc = cm.doc;
  2389. if (how == null) how = "add";
  2390. if (how == "smart") {
  2391. if (!cm.doc.mode.indent) how = "prev";
  2392. else var state = getStateBefore(cm, n);
  2393. }
  2394. var tabSize = cm.options.tabSize;
  2395. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  2396. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  2397. if (how == "smart") {
  2398. indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  2399. if (indentation == Pass) {
  2400. if (!aggressive) return;
  2401. how = "prev";
  2402. }
  2403. }
  2404. if (how == "prev") {
  2405. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  2406. else indentation = 0;
  2407. } else if (how == "add") {
  2408. indentation = curSpace + cm.options.indentUnit;
  2409. } else if (how == "subtract") {
  2410. indentation = curSpace - cm.options.indentUnit;
  2411. } else if (typeof how == "number") {
  2412. indentation = curSpace + how;
  2413. }
  2414. indentation = Math.max(0, indentation);
  2415. var indentString = "", pos = 0;
  2416. if (cm.options.indentWithTabs)
  2417. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  2418. if (pos < indentation) indentString += spaceStr(indentation - pos);
  2419. if (indentString != curSpaceString)
  2420. replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  2421. line.stateAfter = null;
  2422. }
  2423. function changeLine(cm, handle, op) {
  2424. var no = handle, line = handle, doc = cm.doc;
  2425. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  2426. else no = lineNo(handle);
  2427. if (no == null) return null;
  2428. if (op(line, no)) regChange(cm, no, no + 1);
  2429. else return null;
  2430. return line;
  2431. }
  2432. function findPosH(doc, pos, dir, unit, visually) {
  2433. var line = pos.line, ch = pos.ch, origDir = dir;
  2434. var lineObj = getLine(doc, line);
  2435. var possible = true;
  2436. function findNextLine() {
  2437. var l = line + dir;
  2438. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  2439. line = l;
  2440. return lineObj = getLine(doc, l);
  2441. }
  2442. function moveOnce(boundToLine) {
  2443. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  2444. if (next == null) {
  2445. if (!boundToLine && findNextLine()) {
  2446. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  2447. else ch = dir < 0 ? lineObj.text.length : 0;
  2448. } else return (possible = false);
  2449. } else ch = next;
  2450. return true;
  2451. }
  2452. if (unit == "char") moveOnce();
  2453. else if (unit == "column") moveOnce(true);
  2454. else if (unit == "word" || unit == "group") {
  2455. var sawType = null, group = unit == "group";
  2456. for (var first = true;; first = false) {
  2457. if (dir < 0 && !moveOnce(!first)) break;
  2458. var cur = lineObj.text.charAt(ch) || "\n";
  2459. var type = isWordChar(cur) ? "w"
  2460. : !group ? null
  2461. : /\s/.test(cur) ? null
  2462. : "p";
  2463. if (sawType && sawType != type) {
  2464. if (dir < 0) {dir = 1; moveOnce();}
  2465. break;
  2466. }
  2467. if (type) sawType = type;
  2468. if (dir > 0 && !moveOnce(!first)) break;
  2469. }
  2470. }
  2471. var result = skipAtomic(doc, Pos(line, ch), origDir, true);
  2472. if (!possible) result.hitSide = true;
  2473. return result;
  2474. }
  2475. function findPosV(cm, pos, dir, unit) {
  2476. var doc = cm.doc, x = pos.left, y;
  2477. if (unit == "page") {
  2478. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  2479. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  2480. } else if (unit == "line") {
  2481. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  2482. }
  2483. for (;;) {
  2484. var target = coordsChar(cm, x, y);
  2485. if (!target.outside) break;
  2486. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  2487. y += dir * 5;
  2488. }
  2489. return target;
  2490. }
  2491. function findWordAt(line, pos) {
  2492. var start = pos.ch, end = pos.ch;
  2493. if (line) {
  2494. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  2495. var startChar = line.charAt(start);
  2496. var check = isWordChar(startChar) ? isWordChar
  2497. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  2498. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  2499. while (start > 0 && check(line.charAt(start - 1))) --start;
  2500. while (end < line.length && check(line.charAt(end))) ++end;
  2501. }
  2502. return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
  2503. }
  2504. function selectLine(cm, line) {
  2505. extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
  2506. }
  2507. // PROTOTYPE
  2508. // The publicly visible API. Note that operation(null, f) means
  2509. // 'wrap f in an operation, performed on its `this` parameter'
  2510. CodeMirror.prototype = {
  2511. constructor: CodeMirror,
  2512. focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
  2513. setOption: function(option, value) {
  2514. var options = this.options, old = options[option];
  2515. if (options[option] == value && option != "mode") return;
  2516. options[option] = value;
  2517. if (optionHandlers.hasOwnProperty(option))
  2518. operation(this, optionHandlers[option])(this, value, old);
  2519. },
  2520. getOption: function(option) {return this.options[option];},
  2521. getDoc: function() {return this.doc;},
  2522. addKeyMap: function(map, bottom) {
  2523. this.state.keyMaps[bottom ? "push" : "unshift"](map);
  2524. },
  2525. removeKeyMap: function(map) {
  2526. var maps = this.state.keyMaps;
  2527. for (var i = 0; i < maps.length; ++i)
  2528. if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
  2529. maps.splice(i, 1);
  2530. return true;
  2531. }
  2532. },
  2533. addOverlay: operation(null, function(spec, options) {
  2534. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  2535. if (mode.startState) throw new Error("Overlays may not be stateful.");
  2536. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  2537. this.state.modeGen++;
  2538. regChange(this);
  2539. }),
  2540. removeOverlay: operation(null, function(spec) {
  2541. var overlays = this.state.overlays;
  2542. for (var i = 0; i < overlays.length; ++i) {
  2543. var cur = overlays[i].modeSpec;
  2544. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  2545. overlays.splice(i, 1);
  2546. this.state.modeGen++;
  2547. regChange(this);
  2548. return;
  2549. }
  2550. }
  2551. }),
  2552. indentLine: operation(null, function(n, dir, aggressive) {
  2553. if (typeof dir != "string" && typeof dir != "number") {
  2554. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  2555. else dir = dir ? "add" : "subtract";
  2556. }
  2557. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  2558. }),
  2559. indentSelection: operation(null, function(how) {
  2560. var sel = this.doc.sel;
  2561. if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
  2562. var e = sel.to.line - (sel.to.ch ? 0 : 1);
  2563. for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
  2564. }),
  2565. // Fetch the parser token for a given character. Useful for hacks
  2566. // that want to inspect the mode state (say, for completion).
  2567. getTokenAt: function(pos, precise) {
  2568. var doc = this.doc;
  2569. pos = clipPos(doc, pos);
  2570. var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
  2571. var line = getLine(doc, pos.line);
  2572. var stream = new StringStream(line.text, this.options.tabSize);
  2573. while (stream.pos < pos.ch && !stream.eol()) {
  2574. stream.start = stream.pos;
  2575. var style = mode.token(stream, state);
  2576. }
  2577. return {start: stream.start,
  2578. end: stream.pos,
  2579. string: stream.current(),
  2580. className: style || null, // Deprecated, use 'type' instead
  2581. type: style || null,
  2582. state: state};
  2583. },
  2584. getTokenTypeAt: function(pos) {
  2585. pos = clipPos(this.doc, pos);
  2586. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  2587. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  2588. if (ch == 0) return styles[2];
  2589. for (;;) {
  2590. var mid = (before + after) >> 1;
  2591. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  2592. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  2593. else return styles[mid * 2 + 2];
  2594. }
  2595. },
  2596. getModeAt: function(pos) {
  2597. var mode = this.doc.mode;
  2598. if (!mode.innerMode) return mode;
  2599. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  2600. },
  2601. getHelper: function(pos, type) {
  2602. if (!helpers.hasOwnProperty(type)) return;
  2603. var help = helpers[type], mode = this.getModeAt(pos);
  2604. return mode[type] && help[mode[type]] ||
  2605. mode.helperType && help[mode.helperType] ||
  2606. help[mode.name];
  2607. },
  2608. getStateAfter: function(line, precise) {
  2609. var doc = this.doc;
  2610. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  2611. return getStateBefore(this, line + 1, precise);
  2612. },
  2613. cursorCoords: function(start, mode) {
  2614. var pos, sel = this.doc.sel;
  2615. if (start == null) pos = sel.head;
  2616. else if (typeof start == "object") pos = clipPos(this.doc, start);
  2617. else pos = start ? sel.from : sel.to;
  2618. return cursorCoords(this, pos, mode || "page");
  2619. },
  2620. charCoords: function(pos, mode) {
  2621. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  2622. },
  2623. coordsChar: function(coords, mode) {
  2624. coords = fromCoordSystem(this, coords, mode || "page");
  2625. return coordsChar(this, coords.left, coords.top);
  2626. },
  2627. lineAtHeight: function(height, mode) {
  2628. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  2629. return lineAtHeight(this.doc, height + this.display.viewOffset);
  2630. },
  2631. heightAtLine: function(line, mode) {
  2632. var end = false, last = this.doc.first + this.doc.size - 1;
  2633. if (line < this.doc.first) line = this.doc.first;
  2634. else if (line > last) { line = last; end = true; }
  2635. var lineObj = getLine(this.doc, line);
  2636. return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top +
  2637. (end ? lineObj.height : 0);
  2638. },
  2639. defaultTextHeight: function() { return textHeight(this.display); },
  2640. defaultCharWidth: function() { return charWidth(this.display); },
  2641. setGutterMarker: operation(null, function(line, gutterID, value) {
  2642. return changeLine(this, line, function(line) {
  2643. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  2644. markers[gutterID] = value;
  2645. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  2646. return true;
  2647. });
  2648. }),
  2649. clearGutter: operation(null, function(gutterID) {
  2650. var cm = this, doc = cm.doc, i = doc.first;
  2651. doc.iter(function(line) {
  2652. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  2653. line.gutterMarkers[gutterID] = null;
  2654. regChange(cm, i, i + 1);
  2655. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  2656. }
  2657. ++i;
  2658. });
  2659. }),
  2660. addLineClass: operation(null, function(handle, where, cls) {
  2661. return changeLine(this, handle, function(line) {
  2662. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  2663. if (!line[prop]) line[prop] = cls;
  2664. else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
  2665. else line[prop] += " " + cls;
  2666. return true;
  2667. });
  2668. }),
  2669. removeLineClass: operation(null, function(handle, where, cls) {
  2670. return changeLine(this, handle, function(line) {
  2671. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  2672. var cur = line[prop];
  2673. if (!cur) return false;
  2674. else if (cls == null) line[prop] = null;
  2675. else {
  2676. var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
  2677. if (!found) return false;
  2678. var end = found.index + found[0].length;
  2679. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  2680. }
  2681. return true;
  2682. });
  2683. }),
  2684. addLineWidget: operation(null, function(handle, node, options) {
  2685. return addLineWidget(this, handle, node, options);
  2686. }),
  2687. removeLineWidget: function(widget) { widget.clear(); },
  2688. lineInfo: function(line) {
  2689. if (typeof line == "number") {
  2690. if (!isLine(this.doc, line)) return null;
  2691. var n = line;
  2692. line = getLine(this.doc, line);
  2693. if (!line) return null;
  2694. } else {
  2695. var n = lineNo(line);
  2696. if (n == null) return null;
  2697. }
  2698. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  2699. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  2700. widgets: line.widgets};
  2701. },
  2702. getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
  2703. addWidget: function(pos, node, scroll, vert, horiz) {
  2704. var display = this.display;
  2705. pos = cursorCoords(this, clipPos(this.doc, pos));
  2706. var top = pos.bottom, left = pos.left;
  2707. node.style.position = "absolute";
  2708. display.sizer.appendChild(node);
  2709. if (vert == "over") {
  2710. top = pos.top;
  2711. } else if (vert == "above" || vert == "near") {
  2712. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  2713. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  2714. // Default to positioning above (if specified and possible); otherwise default to positioning below
  2715. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  2716. top = pos.top - node.offsetHeight;
  2717. else if (pos.bottom + node.offsetHeight <= vspace)
  2718. top = pos.bottom;
  2719. if (left + node.offsetWidth > hspace)
  2720. left = hspace - node.offsetWidth;
  2721. }
  2722. node.style.top = top + "px";
  2723. node.style.left = node.style.right = "";
  2724. if (horiz == "right") {
  2725. left = display.sizer.clientWidth - node.offsetWidth;
  2726. node.style.right = "0px";
  2727. } else {
  2728. if (horiz == "left") left = 0;
  2729. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  2730. node.style.left = left + "px";
  2731. }
  2732. if (scroll)
  2733. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  2734. },
  2735. triggerOnKeyDown: operation(null, onKeyDown),
  2736. execCommand: function(cmd) {return commands[cmd](this);},
  2737. findPosH: function(from, amount, unit, visually) {
  2738. var dir = 1;
  2739. if (amount < 0) { dir = -1; amount = -amount; }
  2740. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  2741. cur = findPosH(this.doc, cur, dir, unit, visually);
  2742. if (cur.hitSide) break;
  2743. }
  2744. return cur;
  2745. },
  2746. moveH: operation(null, function(dir, unit) {
  2747. var sel = this.doc.sel, pos;
  2748. if (sel.shift || sel.extend || posEq(sel.from, sel.to))
  2749. pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
  2750. else
  2751. pos = dir < 0 ? sel.from : sel.to;
  2752. extendSelection(this.doc, pos, pos, dir);
  2753. }),
  2754. deleteH: operation(null, function(dir, unit) {
  2755. var sel = this.doc.sel;
  2756. if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
  2757. else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
  2758. this.curOp.userSelChange = true;
  2759. }),
  2760. findPosV: function(from, amount, unit, goalColumn) {
  2761. var dir = 1, x = goalColumn;
  2762. if (amount < 0) { dir = -1; amount = -amount; }
  2763. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  2764. var coords = cursorCoords(this, cur, "div");
  2765. if (x == null) x = coords.left;
  2766. else coords.left = x;
  2767. cur = findPosV(this, coords, dir, unit);
  2768. if (cur.hitSide) break;
  2769. }
  2770. return cur;
  2771. },
  2772. moveV: operation(null, function(dir, unit) {
  2773. var sel = this.doc.sel;
  2774. var pos = cursorCoords(this, sel.head, "div");
  2775. if (sel.goalColumn != null) pos.left = sel.goalColumn;
  2776. var target = findPosV(this, pos, dir, unit);
  2777. if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
  2778. extendSelection(this.doc, target, target, dir);
  2779. sel.goalColumn = pos.left;
  2780. }),
  2781. toggleOverwrite: function(value) {
  2782. if (value != null && value == this.state.overwrite) return;
  2783. if (this.state.overwrite = !this.state.overwrite)
  2784. this.display.cursor.className += " CodeMirror-overwrite";
  2785. else
  2786. this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
  2787. },
  2788. hasFocus: function() { return this.state.focused; },
  2789. scrollTo: operation(null, function(x, y) {
  2790. updateScrollPos(this, x, y);
  2791. }),
  2792. getScrollInfo: function() {
  2793. var scroller = this.display.scroller, co = scrollerCutOff;
  2794. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  2795. height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
  2796. clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
  2797. },
  2798. scrollIntoView: operation(null, function(pos, margin) {
  2799. if (typeof pos == "number") pos = Pos(pos, 0);
  2800. if (!margin) margin = 0;
  2801. var coords = pos;
  2802. if (!pos || pos.line != null) {
  2803. this.curOp.scrollToPos = pos ? clipPos(this.doc, pos) : this.doc.sel.head;
  2804. this.curOp.scrollToPosMargin = margin;
  2805. coords = cursorCoords(this, this.curOp.scrollToPos);
  2806. }
  2807. var sPos = calculateScrollPos(this, coords.left, coords.top - margin, coords.right, coords.bottom + margin);
  2808. updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop);
  2809. }),
  2810. setSize: operation(null, function(width, height) {
  2811. function interpret(val) {
  2812. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  2813. }
  2814. if (width != null) this.display.wrapper.style.width = interpret(width);
  2815. if (height != null) this.display.wrapper.style.height = interpret(height);
  2816. if (this.options.lineWrapping)
  2817. this.display.measureLineCache.length = this.display.measureLineCachePos = 0;
  2818. this.curOp.forceUpdate = true;
  2819. }),
  2820. operation: function(f){return runInOp(this, f);},
  2821. refresh: operation(null, function() {
  2822. clearCaches(this);
  2823. updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop);
  2824. regChange(this);
  2825. }),
  2826. swapDoc: operation(null, function(doc) {
  2827. var old = this.doc;
  2828. old.cm = null;
  2829. attachDoc(this, doc);
  2830. clearCaches(this);
  2831. resetInput(this, true);
  2832. updateScrollPos(this, doc.scrollLeft, doc.scrollTop);
  2833. return old;
  2834. }),
  2835. getInputField: function(){return this.display.input;},
  2836. getWrapperElement: function(){return this.display.wrapper;},
  2837. getScrollerElement: function(){return this.display.scroller;},
  2838. getGutterElement: function(){return this.display.gutters;}
  2839. };
  2840. eventMixin(CodeMirror);
  2841. // OPTION DEFAULTS
  2842. var optionHandlers = CodeMirror.optionHandlers = {};
  2843. // The default configuration options.
  2844. var defaults = CodeMirror.defaults = {};
  2845. function option(name, deflt, handle, notOnInit) {
  2846. CodeMirror.defaults[name] = deflt;
  2847. if (handle) optionHandlers[name] =
  2848. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  2849. }
  2850. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  2851. // These two are, on init, called from the constructor because they
  2852. // have to be initialized before the editor can start at all.
  2853. option("value", "", function(cm, val) {
  2854. cm.setValue(val);
  2855. }, true);
  2856. option("mode", null, function(cm, val) {
  2857. cm.doc.modeOption = val;
  2858. loadMode(cm);
  2859. }, true);
  2860. option("indentUnit", 2, loadMode, true);
  2861. option("indentWithTabs", false);
  2862. option("smartIndent", true);
  2863. option("tabSize", 4, function(cm) {
  2864. loadMode(cm);
  2865. clearCaches(cm);
  2866. regChange(cm);
  2867. }, true);
  2868. option("electricChars", true);
  2869. option("rtlMoveVisually", !windows);
  2870. option("theme", "default", function(cm) {
  2871. themeChanged(cm);
  2872. guttersChanged(cm);
  2873. }, true);
  2874. option("keyMap", "default", keyMapChanged);
  2875. option("extraKeys", null);
  2876. option("onKeyEvent", null);
  2877. option("onDragEvent", null);
  2878. option("lineWrapping", false, wrappingChanged, true);
  2879. option("gutters", [], function(cm) {
  2880. setGuttersForLineNumbers(cm.options);
  2881. guttersChanged(cm);
  2882. }, true);
  2883. option("fixedGutter", true, function(cm, val) {
  2884. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  2885. cm.refresh();
  2886. }, true);
  2887. option("coverGutterNextToScrollbar", false, updateScrollbars, true);
  2888. option("lineNumbers", false, function(cm) {
  2889. setGuttersForLineNumbers(cm.options);
  2890. guttersChanged(cm);
  2891. }, true);
  2892. option("firstLineNumber", 1, guttersChanged, true);
  2893. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  2894. option("showCursorWhenSelecting", false, updateSelection, true);
  2895. option("readOnly", false, function(cm, val) {
  2896. if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
  2897. else if (!val) resetInput(cm, true);
  2898. });
  2899. option("dragDrop", true);
  2900. option("cursorBlinkRate", 530);
  2901. option("cursorScrollMargin", 0);
  2902. option("cursorHeight", 1);
  2903. option("workTime", 100);
  2904. option("workDelay", 100);
  2905. option("flattenSpans", true);
  2906. option("pollInterval", 100);
  2907. option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;});
  2908. option("historyEventDelay", 500);
  2909. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  2910. option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true);
  2911. option("moveInputWithCursor", true, function(cm, val) {
  2912. if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
  2913. });
  2914. option("tabindex", null, function(cm, val) {
  2915. cm.display.input.tabIndex = val || "";
  2916. });
  2917. option("autofocus", null);
  2918. // MODE DEFINITION AND QUERYING
  2919. // Known modes, by name and by MIME
  2920. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  2921. CodeMirror.defineMode = function(name, mode) {
  2922. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  2923. if (arguments.length > 2) {
  2924. mode.dependencies = [];
  2925. for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
  2926. }
  2927. modes[name] = mode;
  2928. };
  2929. CodeMirror.defineMIME = function(mime, spec) {
  2930. mimeModes[mime] = spec;
  2931. };
  2932. CodeMirror.resolveMode = function(spec) {
  2933. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  2934. spec = mimeModes[spec];
  2935. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  2936. var found = mimeModes[spec.name];
  2937. spec = createObj(found, spec);
  2938. spec.name = found.name;
  2939. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  2940. return CodeMirror.resolveMode("application/xml");
  2941. }
  2942. if (typeof spec == "string") return {name: spec};
  2943. else return spec || {name: "null"};
  2944. };
  2945. CodeMirror.getMode = function(options, spec) {
  2946. var spec = CodeMirror.resolveMode(spec);
  2947. var mfactory = modes[spec.name];
  2948. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  2949. var modeObj = mfactory(options, spec);
  2950. if (modeExtensions.hasOwnProperty(spec.name)) {
  2951. var exts = modeExtensions[spec.name];
  2952. for (var prop in exts) {
  2953. if (!exts.hasOwnProperty(prop)) continue;
  2954. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  2955. modeObj[prop] = exts[prop];
  2956. }
  2957. }
  2958. modeObj.name = spec.name;
  2959. return modeObj;
  2960. };
  2961. CodeMirror.defineMode("null", function() {
  2962. return {token: function(stream) {stream.skipToEnd();}};
  2963. });
  2964. CodeMirror.defineMIME("text/plain", "null");
  2965. var modeExtensions = CodeMirror.modeExtensions = {};
  2966. CodeMirror.extendMode = function(mode, properties) {
  2967. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  2968. copyObj(properties, exts);
  2969. };
  2970. // EXTENSIONS
  2971. CodeMirror.defineExtension = function(name, func) {
  2972. CodeMirror.prototype[name] = func;
  2973. };
  2974. CodeMirror.defineDocExtension = function(name, func) {
  2975. Doc.prototype[name] = func;
  2976. };
  2977. CodeMirror.defineOption = option;
  2978. var initHooks = [];
  2979. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  2980. var helpers = CodeMirror.helpers = {};
  2981. CodeMirror.registerHelper = function(type, name, value) {
  2982. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {};
  2983. helpers[type][name] = value;
  2984. };
  2985. // UTILITIES
  2986. CodeMirror.isWordChar = isWordChar;
  2987. // MODE STATE HANDLING
  2988. // Utility functions for working with state. Exported because modes
  2989. // sometimes need to do this.
  2990. function copyState(mode, state) {
  2991. if (state === true) return state;
  2992. if (mode.copyState) return mode.copyState(state);
  2993. var nstate = {};
  2994. for (var n in state) {
  2995. var val = state[n];
  2996. if (val instanceof Array) val = val.concat([]);
  2997. nstate[n] = val;
  2998. }
  2999. return nstate;
  3000. }
  3001. CodeMirror.copyState = copyState;
  3002. function startState(mode, a1, a2) {
  3003. return mode.startState ? mode.startState(a1, a2) : true;
  3004. }
  3005. CodeMirror.startState = startState;
  3006. CodeMirror.innerMode = function(mode, state) {
  3007. while (mode.innerMode) {
  3008. var info = mode.innerMode(state);
  3009. if (!info || info.mode == mode) break;
  3010. state = info.state;
  3011. mode = info.mode;
  3012. }
  3013. return info || {mode: mode, state: state};
  3014. };
  3015. // STANDARD COMMANDS
  3016. var commands = CodeMirror.commands = {
  3017. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));},
  3018. killLine: function(cm) {
  3019. var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
  3020. if (!sel && cm.getLine(from.line).length == from.ch)
  3021. cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete");
  3022. else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete");
  3023. },
  3024. deleteLine: function(cm) {
  3025. var l = cm.getCursor().line;
  3026. cm.replaceRange("", Pos(l, 0), Pos(l), "+delete");
  3027. },
  3028. delLineLeft: function(cm) {
  3029. var cur = cm.getCursor();
  3030. cm.replaceRange("", Pos(cur.line, 0), cur, "+delete");
  3031. },
  3032. undo: function(cm) {cm.undo();},
  3033. redo: function(cm) {cm.redo();},
  3034. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  3035. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  3036. goLineStart: function(cm) {
  3037. cm.extendSelection(lineStart(cm, cm.getCursor().line));
  3038. },
  3039. goLineStartSmart: function(cm) {
  3040. var cur = cm.getCursor(), start = lineStart(cm, cur.line);
  3041. var line = cm.getLineHandle(start.line);
  3042. var order = getOrder(line);
  3043. if (!order || order[0].level == 0) {
  3044. var firstNonWS = Math.max(0, line.text.search(/\S/));
  3045. var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
  3046. cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS));
  3047. } else cm.extendSelection(start);
  3048. },
  3049. goLineEnd: function(cm) {
  3050. cm.extendSelection(lineEnd(cm, cm.getCursor().line));
  3051. },
  3052. goLineRight: function(cm) {
  3053. var top = cm.charCoords(cm.getCursor(), "div").top + 5;
  3054. cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"));
  3055. },
  3056. goLineLeft: function(cm) {
  3057. var top = cm.charCoords(cm.getCursor(), "div").top + 5;
  3058. cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div"));
  3059. },
  3060. goLineUp: function(cm) {cm.moveV(-1, "line");},
  3061. goLineDown: function(cm) {cm.moveV(1, "line");},
  3062. goPageUp: function(cm) {cm.moveV(-1, "page");},
  3063. goPageDown: function(cm) {cm.moveV(1, "page");},
  3064. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  3065. goCharRight: function(cm) {cm.moveH(1, "char");},
  3066. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  3067. goColumnRight: function(cm) {cm.moveH(1, "column");},
  3068. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  3069. goGroupRight: function(cm) {cm.moveH(1, "group");},
  3070. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  3071. goWordRight: function(cm) {cm.moveH(1, "word");},
  3072. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  3073. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  3074. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  3075. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  3076. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  3077. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  3078. indentAuto: function(cm) {cm.indentSelection("smart");},
  3079. indentMore: function(cm) {cm.indentSelection("add");},
  3080. indentLess: function(cm) {cm.indentSelection("subtract");},
  3081. insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");},
  3082. defaultTab: function(cm) {
  3083. if (cm.somethingSelected()) cm.indentSelection("add");
  3084. else cm.replaceSelection("\t", "end", "+input");
  3085. },
  3086. transposeChars: function(cm) {
  3087. var cur = cm.getCursor(), line = cm.getLine(cur.line);
  3088. if (cur.ch > 0 && cur.ch < line.length - 1)
  3089. cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
  3090. Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
  3091. },
  3092. newlineAndIndent: function(cm) {
  3093. operation(cm, function() {
  3094. cm.replaceSelection("\n", "end", "+input");
  3095. cm.indentLine(cm.getCursor().line, null, true);
  3096. })();
  3097. },
  3098. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  3099. };
  3100. // STANDARD KEYMAPS
  3101. var keyMap = CodeMirror.keyMap = {};
  3102. keyMap.basic = {
  3103. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  3104. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  3105. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  3106. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
  3107. };
  3108. // Note that the save and find-related commands aren't defined by
  3109. // default. Unknown commands are simply ignored.
  3110. keyMap.pcDefault = {
  3111. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  3112. "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
  3113. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  3114. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  3115. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  3116. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  3117. fallthrough: "basic"
  3118. };
  3119. keyMap.macDefault = {
  3120. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  3121. "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  3122. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
  3123. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  3124. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  3125. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
  3126. fallthrough: ["basic", "emacsy"]
  3127. };
  3128. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  3129. keyMap.emacsy = {
  3130. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  3131. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  3132. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  3133. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  3134. };
  3135. // KEYMAP DISPATCH
  3136. function getKeyMap(val) {
  3137. if (typeof val == "string") return keyMap[val];
  3138. else return val;
  3139. }
  3140. function lookupKey(name, maps, handle) {
  3141. function lookup(map) {
  3142. map = getKeyMap(map);
  3143. var found = map[name];
  3144. if (found === false) return "stop";
  3145. if (found != null && handle(found)) return true;
  3146. if (map.nofallthrough) return "stop";
  3147. var fallthrough = map.fallthrough;
  3148. if (fallthrough == null) return false;
  3149. if (Object.prototype.toString.call(fallthrough) != "[object Array]")
  3150. return lookup(fallthrough);
  3151. for (var i = 0, e = fallthrough.length; i < e; ++i) {
  3152. var done = lookup(fallthrough[i]);
  3153. if (done) return done;
  3154. }
  3155. return false;
  3156. }
  3157. for (var i = 0; i < maps.length; ++i) {
  3158. var done = lookup(maps[i]);
  3159. if (done) return done != "stop";
  3160. }
  3161. }
  3162. function isModifierKey(event) {
  3163. var name = keyNames[event.keyCode];
  3164. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  3165. }
  3166. function keyName(event, noShift) {
  3167. if (opera && event.keyCode == 34 && event["char"]) return false;
  3168. var name = keyNames[event.keyCode];
  3169. if (name == null || event.altGraphKey) return false;
  3170. if (event.altKey) name = "Alt-" + name;
  3171. if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
  3172. if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
  3173. if (!noShift && event.shiftKey) name = "Shift-" + name;
  3174. return name;
  3175. }
  3176. CodeMirror.lookupKey = lookupKey;
  3177. CodeMirror.isModifierKey = isModifierKey;
  3178. CodeMirror.keyName = keyName;
  3179. // FROMTEXTAREA
  3180. CodeMirror.fromTextArea = function(textarea, options) {
  3181. if (!options) options = {};
  3182. options.value = textarea.value;
  3183. if (!options.tabindex && textarea.tabindex)
  3184. options.tabindex = textarea.tabindex;
  3185. if (!options.placeholder && textarea.placeholder)
  3186. options.placeholder = textarea.placeholder;
  3187. // Set autofocus to true if this textarea is focused, or if it has
  3188. // autofocus and no other element is focused.
  3189. if (options.autofocus == null) {
  3190. var hasFocus = document.body;
  3191. // doc.activeElement occasionally throws on IE
  3192. try { hasFocus = document.activeElement; } catch(e) {}
  3193. options.autofocus = hasFocus == textarea ||
  3194. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  3195. }
  3196. function save() {textarea.value = cm.getValue();}
  3197. if (textarea.form) {
  3198. on(textarea.form, "submit", save);
  3199. // Deplorable hack to make the submit method do the right thing.
  3200. if (!options.leaveSubmitMethodAlone) {
  3201. var form = textarea.form, realSubmit = form.submit;
  3202. try {
  3203. var wrappedSubmit = form.submit = function() {
  3204. save();
  3205. form.submit = realSubmit;
  3206. form.submit();
  3207. form.submit = wrappedSubmit;
  3208. };
  3209. } catch(e) {}
  3210. }
  3211. }
  3212. textarea.style.display = "none";
  3213. var cm = CodeMirror(function(node) {
  3214. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  3215. }, options);
  3216. cm.save = save;
  3217. cm.getTextArea = function() { return textarea; };
  3218. cm.toTextArea = function() {
  3219. save();
  3220. textarea.parentNode.removeChild(cm.getWrapperElement());
  3221. textarea.style.display = "";
  3222. if (textarea.form) {
  3223. off(textarea.form, "submit", save);
  3224. if (typeof textarea.form.submit == "function")
  3225. textarea.form.submit = realSubmit;
  3226. }
  3227. };
  3228. return cm;
  3229. };
  3230. // STRING STREAM
  3231. // Fed to the mode parsers, provides helper functions to make
  3232. // parsers more succinct.
  3233. // The character stream used by a mode's parser.
  3234. function StringStream(string, tabSize) {
  3235. this.pos = this.start = 0;
  3236. this.string = string;
  3237. this.tabSize = tabSize || 8;
  3238. this.lastColumnPos = this.lastColumnValue = 0;
  3239. }
  3240. StringStream.prototype = {
  3241. eol: function() {return this.pos >= this.string.length;},
  3242. sol: function() {return this.pos == 0;},
  3243. peek: function() {return this.string.charAt(this.pos) || undefined;},
  3244. next: function() {
  3245. if (this.pos < this.string.length)
  3246. return this.string.charAt(this.pos++);
  3247. },
  3248. eat: function(match) {
  3249. var ch = this.string.charAt(this.pos);
  3250. if (typeof match == "string") var ok = ch == match;
  3251. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  3252. if (ok) {++this.pos; return ch;}
  3253. },
  3254. eatWhile: function(match) {
  3255. var start = this.pos;
  3256. while (this.eat(match)){}
  3257. return this.pos > start;
  3258. },
  3259. eatSpace: function() {
  3260. var start = this.pos;
  3261. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  3262. return this.pos > start;
  3263. },
  3264. skipToEnd: function() {this.pos = this.string.length;},
  3265. skipTo: function(ch) {
  3266. var found = this.string.indexOf(ch, this.pos);
  3267. if (found > -1) {this.pos = found; return true;}
  3268. },
  3269. backUp: function(n) {this.pos -= n;},
  3270. column: function() {
  3271. if (this.lastColumnPos < this.start) {
  3272. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  3273. this.lastColumnPos = this.start;
  3274. }
  3275. return this.lastColumnValue;
  3276. },
  3277. indentation: function() {return countColumn(this.string, null, this.tabSize);},
  3278. match: function(pattern, consume, caseInsensitive) {
  3279. if (typeof pattern == "string") {
  3280. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  3281. var substr = this.string.substr(this.pos, pattern.length);
  3282. if (cased(substr) == cased(pattern)) {
  3283. if (consume !== false) this.pos += pattern.length;
  3284. return true;
  3285. }
  3286. } else {
  3287. var match = this.string.slice(this.pos).match(pattern);
  3288. if (match && match.index > 0) return null;
  3289. if (match && consume !== false) this.pos += match[0].length;
  3290. return match;
  3291. }
  3292. },
  3293. current: function(){return this.string.slice(this.start, this.pos);}
  3294. };
  3295. CodeMirror.StringStream = StringStream;
  3296. // TEXTMARKERS
  3297. function TextMarker(doc, type) {
  3298. this.lines = [];
  3299. this.type = type;
  3300. this.doc = doc;
  3301. }
  3302. CodeMirror.TextMarker = TextMarker;
  3303. eventMixin(TextMarker);
  3304. TextMarker.prototype.clear = function() {
  3305. if (this.explicitlyCleared) return;
  3306. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  3307. if (withOp) startOperation(cm);
  3308. if (hasHandler(this, "clear")) {
  3309. var found = this.find();
  3310. if (found) signalLater(this, "clear", found.from, found.to);
  3311. }
  3312. var min = null, max = null;
  3313. for (var i = 0; i < this.lines.length; ++i) {
  3314. var line = this.lines[i];
  3315. var span = getMarkedSpanFor(line.markedSpans, this);
  3316. if (span.to != null) max = lineNo(line);
  3317. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  3318. if (span.from != null)
  3319. min = lineNo(line);
  3320. else if (this.collapsed && !lineIsHidden(this.doc, line) && cm)
  3321. updateLineHeight(line, textHeight(cm.display));
  3322. }
  3323. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  3324. var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual);
  3325. if (len > cm.display.maxLineLength) {
  3326. cm.display.maxLine = visual;
  3327. cm.display.maxLineLength = len;
  3328. cm.display.maxLineChanged = true;
  3329. }
  3330. }
  3331. if (min != null && cm) regChange(cm, min, max + 1);
  3332. this.lines.length = 0;
  3333. this.explicitlyCleared = true;
  3334. if (this.atomic && this.doc.cantEdit) {
  3335. this.doc.cantEdit = false;
  3336. if (cm) reCheckSelection(cm);
  3337. }
  3338. if (withOp) endOperation(cm);
  3339. };
  3340. TextMarker.prototype.find = function() {
  3341. var from, to;
  3342. for (var i = 0; i < this.lines.length; ++i) {
  3343. var line = this.lines[i];
  3344. var span = getMarkedSpanFor(line.markedSpans, this);
  3345. if (span.from != null || span.to != null) {
  3346. var found = lineNo(line);
  3347. if (span.from != null) from = Pos(found, span.from);
  3348. if (span.to != null) to = Pos(found, span.to);
  3349. }
  3350. }
  3351. if (this.type == "bookmark") return from;
  3352. return from && {from: from, to: to};
  3353. };
  3354. TextMarker.prototype.changed = function() {
  3355. var pos = this.find(), cm = this.doc.cm;
  3356. if (!pos || !cm) return;
  3357. var line = getLine(this.doc, pos.from.line);
  3358. clearCachedMeasurement(cm, line);
  3359. if (pos.from.line >= cm.display.showingFrom && pos.from.line < cm.display.showingTo) {
  3360. for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) {
  3361. if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight);
  3362. break;
  3363. }
  3364. runInOp(cm, function() {
  3365. cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLine = true;
  3366. });
  3367. }
  3368. };
  3369. TextMarker.prototype.attachLine = function(line) {
  3370. if (!this.lines.length && this.doc.cm) {
  3371. var op = this.doc.cm.curOp;
  3372. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  3373. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  3374. }
  3375. this.lines.push(line);
  3376. };
  3377. TextMarker.prototype.detachLine = function(line) {
  3378. this.lines.splice(indexOf(this.lines, line), 1);
  3379. if (!this.lines.length && this.doc.cm) {
  3380. var op = this.doc.cm.curOp;
  3381. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  3382. }
  3383. };
  3384. function markText(doc, from, to, options, type) {
  3385. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  3386. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  3387. var marker = new TextMarker(doc, type);
  3388. if (type == "range" && !posLess(from, to)) return marker;
  3389. if (options) copyObj(options, marker);
  3390. if (marker.replacedWith) {
  3391. marker.collapsed = true;
  3392. marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
  3393. if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true;
  3394. }
  3395. if (marker.collapsed) sawCollapsedSpans = true;
  3396. if (marker.addToHistory)
  3397. addToHistory(doc, {from: from, to: to, origin: "markText"},
  3398. {head: doc.sel.head, anchor: doc.sel.anchor}, NaN);
  3399. var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine;
  3400. doc.iter(curLine, to.line + 1, function(line) {
  3401. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine)
  3402. updateMaxLine = true;
  3403. var span = {from: null, to: null, marker: marker};
  3404. size += line.text.length;
  3405. if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
  3406. if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
  3407. if (marker.collapsed) {
  3408. if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
  3409. if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
  3410. else updateLineHeight(line, 0);
  3411. }
  3412. addMarkedSpan(line, span);
  3413. ++curLine;
  3414. });
  3415. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  3416. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  3417. });
  3418. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  3419. if (marker.readOnly) {
  3420. sawReadOnlySpans = true;
  3421. if (doc.history.done.length || doc.history.undone.length)
  3422. doc.clearHistory();
  3423. }
  3424. if (marker.collapsed) {
  3425. if (collapsedAtStart != collapsedAtEnd)
  3426. throw new Error("Inserting collapsed marker overlapping an existing one");
  3427. marker.size = size;
  3428. marker.atomic = true;
  3429. }
  3430. if (cm) {
  3431. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  3432. if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.collapsed)
  3433. regChange(cm, from.line, to.line + 1);
  3434. if (marker.atomic) reCheckSelection(cm);
  3435. }
  3436. return marker;
  3437. }
  3438. // SHARED TEXTMARKERS
  3439. function SharedTextMarker(markers, primary) {
  3440. this.markers = markers;
  3441. this.primary = primary;
  3442. for (var i = 0, me = this; i < markers.length; ++i) {
  3443. markers[i].parent = this;
  3444. on(markers[i], "clear", function(){me.clear();});
  3445. }
  3446. }
  3447. CodeMirror.SharedTextMarker = SharedTextMarker;
  3448. eventMixin(SharedTextMarker);
  3449. SharedTextMarker.prototype.clear = function() {
  3450. if (this.explicitlyCleared) return;
  3451. this.explicitlyCleared = true;
  3452. for (var i = 0; i < this.markers.length; ++i)
  3453. this.markers[i].clear();
  3454. signalLater(this, "clear");
  3455. };
  3456. SharedTextMarker.prototype.find = function() {
  3457. return this.primary.find();
  3458. };
  3459. function markTextShared(doc, from, to, options, type) {
  3460. options = copyObj(options);
  3461. options.shared = false;
  3462. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  3463. var widget = options.replacedWith;
  3464. linkedDocs(doc, function(doc) {
  3465. if (widget) options.replacedWith = widget.cloneNode(true);
  3466. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  3467. for (var i = 0; i < doc.linked.length; ++i)
  3468. if (doc.linked[i].isParent) return;
  3469. primary = lst(markers);
  3470. });
  3471. return new SharedTextMarker(markers, primary);
  3472. }
  3473. // TEXTMARKER SPANS
  3474. function getMarkedSpanFor(spans, marker) {
  3475. if (spans) for (var i = 0; i < spans.length; ++i) {
  3476. var span = spans[i];
  3477. if (span.marker == marker) return span;
  3478. }
  3479. }
  3480. function removeMarkedSpan(spans, span) {
  3481. for (var r, i = 0; i < spans.length; ++i)
  3482. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  3483. return r;
  3484. }
  3485. function addMarkedSpan(line, span) {
  3486. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  3487. span.marker.attachLine(line);
  3488. }
  3489. function markedSpansBefore(old, startCh, isInsert) {
  3490. if (old) for (var i = 0, nw; i < old.length; ++i) {
  3491. var span = old[i], marker = span.marker;
  3492. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  3493. if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) {
  3494. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  3495. (nw || (nw = [])).push({from: span.from,
  3496. to: endsAfter ? null : span.to,
  3497. marker: marker});
  3498. }
  3499. }
  3500. return nw;
  3501. }
  3502. function markedSpansAfter(old, endCh, isInsert) {
  3503. if (old) for (var i = 0, nw; i < old.length; ++i) {
  3504. var span = old[i], marker = span.marker;
  3505. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  3506. if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) {
  3507. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  3508. (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
  3509. to: span.to == null ? null : span.to - endCh,
  3510. marker: marker});
  3511. }
  3512. }
  3513. return nw;
  3514. }
  3515. function stretchSpansOverChange(doc, change) {
  3516. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  3517. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  3518. if (!oldFirst && !oldLast) return null;
  3519. var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to);
  3520. // Get the spans that 'stick out' on both sides
  3521. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  3522. var last = markedSpansAfter(oldLast, endCh, isInsert);
  3523. // Next, merge those two ends
  3524. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  3525. if (first) {
  3526. // Fix up .to properties of first
  3527. for (var i = 0; i < first.length; ++i) {
  3528. var span = first[i];
  3529. if (span.to == null) {
  3530. var found = getMarkedSpanFor(last, span.marker);
  3531. if (!found) span.to = startCh;
  3532. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  3533. }
  3534. }
  3535. }
  3536. if (last) {
  3537. // Fix up .from in last (or move them into first in case of sameLine)
  3538. for (var i = 0; i < last.length; ++i) {
  3539. var span = last[i];
  3540. if (span.to != null) span.to += offset;
  3541. if (span.from == null) {
  3542. var found = getMarkedSpanFor(first, span.marker);
  3543. if (!found) {
  3544. span.from = offset;
  3545. if (sameLine) (first || (first = [])).push(span);
  3546. }
  3547. } else {
  3548. span.from += offset;
  3549. if (sameLine) (first || (first = [])).push(span);
  3550. }
  3551. }
  3552. }
  3553. if (sameLine && first) {
  3554. // Make sure we didn't create any zero-length spans
  3555. for (var i = 0; i < first.length; ++i)
  3556. if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark")
  3557. first.splice(i--, 1);
  3558. if (!first.length) first = null;
  3559. }
  3560. var newMarkers = [first];
  3561. if (!sameLine) {
  3562. // Fill gap with whole-line-spans
  3563. var gap = change.text.length - 2, gapMarkers;
  3564. if (gap > 0 && first)
  3565. for (var i = 0; i < first.length; ++i)
  3566. if (first[i].to == null)
  3567. (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
  3568. for (var i = 0; i < gap; ++i)
  3569. newMarkers.push(gapMarkers);
  3570. newMarkers.push(last);
  3571. }
  3572. return newMarkers;
  3573. }
  3574. function mergeOldSpans(doc, change) {
  3575. var old = getOldSpans(doc, change);
  3576. var stretched = stretchSpansOverChange(doc, change);
  3577. if (!old) return stretched;
  3578. if (!stretched) return old;
  3579. for (var i = 0; i < old.length; ++i) {
  3580. var oldCur = old[i], stretchCur = stretched[i];
  3581. if (oldCur && stretchCur) {
  3582. spans: for (var j = 0; j < stretchCur.length; ++j) {
  3583. var span = stretchCur[j];
  3584. for (var k = 0; k < oldCur.length; ++k)
  3585. if (oldCur[k].marker == span.marker) continue spans;
  3586. oldCur.push(span);
  3587. }
  3588. } else if (stretchCur) {
  3589. old[i] = stretchCur;
  3590. }
  3591. }
  3592. return old;
  3593. }
  3594. function removeReadOnlyRanges(doc, from, to) {
  3595. var markers = null;
  3596. doc.iter(from.line, to.line + 1, function(line) {
  3597. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  3598. var mark = line.markedSpans[i].marker;
  3599. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  3600. (markers || (markers = [])).push(mark);
  3601. }
  3602. });
  3603. if (!markers) return null;
  3604. var parts = [{from: from, to: to}];
  3605. for (var i = 0; i < markers.length; ++i) {
  3606. var mk = markers[i], m = mk.find();
  3607. for (var j = 0; j < parts.length; ++j) {
  3608. var p = parts[j];
  3609. if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue;
  3610. var newParts = [j, 1];
  3611. if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from))
  3612. newParts.push({from: p.from, to: m.from});
  3613. if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to))
  3614. newParts.push({from: m.to, to: p.to});
  3615. parts.splice.apply(parts, newParts);
  3616. j += newParts.length - 1;
  3617. }
  3618. }
  3619. return parts;
  3620. }
  3621. function collapsedSpanAt(line, ch) {
  3622. var sps = sawCollapsedSpans && line.markedSpans, found;
  3623. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  3624. sp = sps[i];
  3625. if (!sp.marker.collapsed) continue;
  3626. if ((sp.from == null || sp.from < ch) &&
  3627. (sp.to == null || sp.to > ch) &&
  3628. (!found || found.width < sp.marker.width))
  3629. found = sp.marker;
  3630. }
  3631. return found;
  3632. }
  3633. function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
  3634. function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
  3635. function visualLine(doc, line) {
  3636. var merged;
  3637. while (merged = collapsedSpanAtStart(line))
  3638. line = getLine(doc, merged.find().from.line);
  3639. return line;
  3640. }
  3641. function lineIsHidden(doc, line) {
  3642. var sps = sawCollapsedSpans && line.markedSpans;
  3643. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  3644. sp = sps[i];
  3645. if (!sp.marker.collapsed) continue;
  3646. if (sp.from == null) return true;
  3647. if (sp.marker.replacedWith) continue;
  3648. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  3649. return true;
  3650. }
  3651. }
  3652. function lineIsHiddenInner(doc, line, span) {
  3653. if (span.to == null) {
  3654. var end = span.marker.find().to, endLine = getLine(doc, end.line);
  3655. return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker));
  3656. }
  3657. if (span.marker.inclusiveRight && span.to == line.text.length)
  3658. return true;
  3659. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  3660. sp = line.markedSpans[i];
  3661. if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to &&
  3662. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  3663. lineIsHiddenInner(doc, line, sp)) return true;
  3664. }
  3665. }
  3666. function detachMarkedSpans(line) {
  3667. var spans = line.markedSpans;
  3668. if (!spans) return;
  3669. for (var i = 0; i < spans.length; ++i)
  3670. spans[i].marker.detachLine(line);
  3671. line.markedSpans = null;
  3672. }
  3673. function attachMarkedSpans(line, spans) {
  3674. if (!spans) return;
  3675. for (var i = 0; i < spans.length; ++i)
  3676. spans[i].marker.attachLine(line);
  3677. line.markedSpans = spans;
  3678. }
  3679. // LINE WIDGETS
  3680. var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
  3681. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  3682. this[opt] = options[opt];
  3683. this.cm = cm;
  3684. this.node = node;
  3685. };
  3686. eventMixin(LineWidget);
  3687. function widgetOperation(f) {
  3688. return function() {
  3689. var withOp = !this.cm.curOp;
  3690. if (withOp) startOperation(this.cm);
  3691. try {var result = f.apply(this, arguments);}
  3692. finally {if (withOp) endOperation(this.cm);}
  3693. return result;
  3694. };
  3695. }
  3696. LineWidget.prototype.clear = widgetOperation(function() {
  3697. var ws = this.line.widgets, no = lineNo(this.line);
  3698. if (no == null || !ws) return;
  3699. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  3700. if (!ws.length) this.line.widgets = null;
  3701. var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop;
  3702. updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this)));
  3703. if (aboveVisible) addToScrollPos(this.cm, 0, -this.height);
  3704. regChange(this.cm, no, no + 1);
  3705. });
  3706. LineWidget.prototype.changed = widgetOperation(function() {
  3707. var oldH = this.height;
  3708. this.height = null;
  3709. var diff = widgetHeight(this) - oldH;
  3710. if (!diff) return;
  3711. updateLineHeight(this.line, this.line.height + diff);
  3712. var no = lineNo(this.line);
  3713. regChange(this.cm, no, no + 1);
  3714. });
  3715. function widgetHeight(widget) {
  3716. if (widget.height != null) return widget.height;
  3717. if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1)
  3718. removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
  3719. return widget.height = widget.node.offsetHeight;
  3720. }
  3721. function addLineWidget(cm, handle, node, options) {
  3722. var widget = new LineWidget(cm, node, options);
  3723. if (widget.noHScroll) cm.display.alignWidgets = true;
  3724. changeLine(cm, handle, function(line) {
  3725. var widgets = line.widgets || (line.widgets = []);
  3726. if (widget.insertAt == null) widgets.push(widget);
  3727. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  3728. widget.line = line;
  3729. if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) {
  3730. var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop;
  3731. updateLineHeight(line, line.height + widgetHeight(widget));
  3732. if (aboveVisible) addToScrollPos(cm, 0, widget.height);
  3733. }
  3734. return true;
  3735. });
  3736. return widget;
  3737. }
  3738. // LINE DATA STRUCTURE
  3739. // Line objects. These hold state related to a line, including
  3740. // highlighting info (the styles array).
  3741. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  3742. this.text = text;
  3743. attachMarkedSpans(this, markedSpans);
  3744. this.height = estimateHeight ? estimateHeight(this) : 1;
  3745. };
  3746. eventMixin(Line);
  3747. function updateLine(line, text, markedSpans, estimateHeight) {
  3748. line.text = text;
  3749. if (line.stateAfter) line.stateAfter = null;
  3750. if (line.styles) line.styles = null;
  3751. if (line.order != null) line.order = null;
  3752. detachMarkedSpans(line);
  3753. attachMarkedSpans(line, markedSpans);
  3754. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  3755. if (estHeight != line.height) updateLineHeight(line, estHeight);
  3756. }
  3757. function cleanUpLine(line) {
  3758. line.parent = null;
  3759. detachMarkedSpans(line);
  3760. }
  3761. // Run the given mode's parser over a line, update the styles
  3762. // array, which contains alternating fragments of text and CSS
  3763. // classes.
  3764. function runMode(cm, text, mode, state, f) {
  3765. var flattenSpans = mode.flattenSpans;
  3766. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  3767. var curStart = 0, curStyle = null;
  3768. var stream = new StringStream(text, cm.options.tabSize), style;
  3769. if (text == "" && mode.blankLine) mode.blankLine(state);
  3770. while (!stream.eol()) {
  3771. if (stream.pos > cm.options.maxHighlightLength) {
  3772. flattenSpans = false;
  3773. // Webkit seems to refuse to render text nodes longer than 57444 characters
  3774. stream.pos = Math.min(text.length, stream.start + 50000);
  3775. style = null;
  3776. } else {
  3777. style = mode.token(stream, state);
  3778. }
  3779. if (!flattenSpans || curStyle != style) {
  3780. if (curStart < stream.start) f(stream.start, curStyle);
  3781. curStart = stream.start; curStyle = style;
  3782. }
  3783. stream.start = stream.pos;
  3784. }
  3785. if (curStart < stream.pos) f(stream.pos, curStyle);
  3786. }
  3787. function highlightLine(cm, line, state) {
  3788. // A styles array always starts with a number identifying the
  3789. // mode/overlays that it is based on (for easy invalidation).
  3790. var st = [cm.state.modeGen];
  3791. // Compute the base array of styles
  3792. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);});
  3793. // Run overlays, adjust style array.
  3794. for (var o = 0; o < cm.state.overlays.length; ++o) {
  3795. var overlay = cm.state.overlays[o], i = 1, at = 0;
  3796. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  3797. var start = i;
  3798. // Ensure there's a token end at the current position, and that i points at it
  3799. while (at < end) {
  3800. var i_end = st[i];
  3801. if (i_end > end)
  3802. st.splice(i, 1, end, st[i+1], i_end);
  3803. i += 2;
  3804. at = Math.min(end, i_end);
  3805. }
  3806. if (!style) return;
  3807. if (overlay.opaque) {
  3808. st.splice(start, i - start, end, style);
  3809. i = start + 2;
  3810. } else {
  3811. for (; start < i; start += 2) {
  3812. var cur = st[start+1];
  3813. st[start+1] = cur ? cur + " " + style : style;
  3814. }
  3815. }
  3816. });
  3817. }
  3818. return st;
  3819. }
  3820. function getLineStyles(cm, line) {
  3821. if (!line.styles || line.styles[0] != cm.state.modeGen)
  3822. line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  3823. return line.styles;
  3824. }
  3825. // Lightweight form of highlight -- proceed over this line and
  3826. // update state, but don't save a style array.
  3827. function processLine(cm, line, state) {
  3828. var mode = cm.doc.mode;
  3829. var stream = new StringStream(line.text, cm.options.tabSize);
  3830. if (line.text == "" && mode.blankLine) mode.blankLine(state);
  3831. while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
  3832. mode.token(stream, state);
  3833. stream.start = stream.pos;
  3834. }
  3835. }
  3836. var styleToClassCache = {};
  3837. function styleToClass(style) {
  3838. if (!style) return null;
  3839. return styleToClassCache[style] ||
  3840. (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
  3841. }
  3842. function lineContent(cm, realLine, measure, copyWidgets) {
  3843. var merged, line = realLine, empty = true;
  3844. while (merged = collapsedSpanAtStart(line))
  3845. line = getLine(cm.doc, merged.find().from.line);
  3846. var builder = {pre: elt("pre"), col: 0, pos: 0,
  3847. measure: null, measuredSomething: false, cm: cm,
  3848. copyWidgets: copyWidgets};
  3849. if (line.textClass) builder.pre.className = line.textClass;
  3850. do {
  3851. if (line.text) empty = false;
  3852. builder.measure = line == realLine && measure;
  3853. builder.pos = 0;
  3854. builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
  3855. if ((ie || webkit) && cm.getOption("lineWrapping"))
  3856. builder.addToken = buildTokenSplitSpaces(builder.addToken);
  3857. var next = insertLineContent(line, builder, getLineStyles(cm, line));
  3858. if (measure && line == realLine && !builder.measuredSomething) {
  3859. measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
  3860. builder.measuredSomething = true;
  3861. }
  3862. if (next) line = getLine(cm.doc, next.to.line);
  3863. } while (next);
  3864. if (measure && !builder.measuredSomething && !measure[0])
  3865. measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
  3866. if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine))
  3867. builder.pre.appendChild(document.createTextNode("\u00a0"));
  3868. var order;
  3869. // Work around problem with the reported dimensions of single-char
  3870. // direction spans on IE (issue #1129). See also the comment in
  3871. // cursorCoords.
  3872. if (measure && ie && (order = getOrder(line))) {
  3873. var l = order.length - 1;
  3874. if (order[l].from == order[l].to) --l;
  3875. var last = order[l], prev = order[l - 1];
  3876. if (last.from + 1 == last.to && prev && last.level < prev.level) {
  3877. var span = measure[builder.pos - 1];
  3878. if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure),
  3879. span.nextSibling);
  3880. }
  3881. }
  3882. signal(cm, "renderLine", cm, realLine, builder.pre);
  3883. return builder.pre;
  3884. }
  3885. var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g;
  3886. function buildToken(builder, text, style, startStyle, endStyle, title) {
  3887. if (!text) return;
  3888. if (!tokenSpecialChars.test(text)) {
  3889. builder.col += text.length;
  3890. var content = document.createTextNode(text);
  3891. } else {
  3892. var content = document.createDocumentFragment(), pos = 0;
  3893. while (true) {
  3894. tokenSpecialChars.lastIndex = pos;
  3895. var m = tokenSpecialChars.exec(text);
  3896. var skipped = m ? m.index - pos : text.length - pos;
  3897. if (skipped) {
  3898. content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
  3899. builder.col += skipped;
  3900. }
  3901. if (!m) break;
  3902. pos += skipped + 1;
  3903. if (m[0] == "\t") {
  3904. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  3905. content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  3906. builder.col += tabWidth;
  3907. } else {
  3908. var token = elt("span", "\u2022", "cm-invalidchar");
  3909. token.title = "\\u" + m[0].charCodeAt(0).toString(16);
  3910. content.appendChild(token);
  3911. builder.col += 1;
  3912. }
  3913. }
  3914. }
  3915. if (style || startStyle || endStyle || builder.measure) {
  3916. var fullStyle = style || "";
  3917. if (startStyle) fullStyle += startStyle;
  3918. if (endStyle) fullStyle += endStyle;
  3919. var token = elt("span", [content], fullStyle);
  3920. if (title) token.title = title;
  3921. return builder.pre.appendChild(token);
  3922. }
  3923. builder.pre.appendChild(content);
  3924. }
  3925. function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
  3926. var wrapping = builder.cm.options.lineWrapping;
  3927. for (var i = 0; i < text.length; ++i) {
  3928. var ch = text.charAt(i), start = i == 0;
  3929. if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) {
  3930. ch = text.slice(i, i + 2);
  3931. ++i;
  3932. } else if (i && wrapping && spanAffectsWrapping(text, i)) {
  3933. builder.pre.appendChild(elt("wbr"));
  3934. }
  3935. var old = builder.measure[builder.pos];
  3936. var span = builder.measure[builder.pos] =
  3937. buildToken(builder, ch, style,
  3938. start && startStyle, i == text.length - 1 && endStyle);
  3939. if (old) span.leftSide = old.leftSide || old;
  3940. // In IE single-space nodes wrap differently than spaces
  3941. // embedded in larger text nodes, except when set to
  3942. // white-space: normal (issue #1268).
  3943. if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) &&
  3944. i < text.length - 1 && !/\s/.test(text.charAt(i + 1)))
  3945. span.style.whiteSpace = "normal";
  3946. builder.pos += ch.length;
  3947. }
  3948. if (text.length) builder.measuredSomething = true;
  3949. }
  3950. function buildTokenSplitSpaces(inner) {
  3951. function split(old) {
  3952. var out = " ";
  3953. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  3954. out += " ";
  3955. return out;
  3956. }
  3957. return function(builder, text, style, startStyle, endStyle, title) {
  3958. return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle, title);
  3959. };
  3960. }
  3961. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  3962. var widget = !ignoreWidget && marker.replacedWith;
  3963. if (widget) {
  3964. if (builder.copyWidgets) widget = widget.cloneNode(true);
  3965. builder.pre.appendChild(widget);
  3966. if (builder.measure) {
  3967. if (size) {
  3968. builder.measure[builder.pos] = widget;
  3969. } else {
  3970. var elt = builder.measure[builder.pos] = zeroWidthElement(builder.cm.display.measure);
  3971. if (marker.type != "bookmark" || marker.insertLeft)
  3972. builder.pre.insertBefore(elt, widget);
  3973. else
  3974. builder.pre.appendChild(elt);
  3975. }
  3976. builder.measuredSomething = true;
  3977. }
  3978. }
  3979. builder.pos += size;
  3980. }
  3981. // Outputs a number of spans to make up a line, taking highlighting
  3982. // and marked text into account.
  3983. function insertLineContent(line, builder, styles) {
  3984. var spans = line.markedSpans, allText = line.text, at = 0;
  3985. if (!spans) {
  3986. for (var i = 1; i < styles.length; i+=2)
  3987. builder.addToken(builder, allText.slice(at, at = styles[i]), styleToClass(styles[i+1]));
  3988. return;
  3989. }
  3990. var len = allText.length, pos = 0, i = 1, text = "", style;
  3991. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  3992. for (;;) {
  3993. if (nextChange == pos) { // Update current marker set
  3994. spanStyle = spanEndStyle = spanStartStyle = title = "";
  3995. collapsed = null; nextChange = Infinity;
  3996. var foundBookmark = null;
  3997. for (var j = 0; j < spans.length; ++j) {
  3998. var sp = spans[j], m = sp.marker;
  3999. if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
  4000. if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
  4001. if (m.className) spanStyle += " " + m.className;
  4002. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  4003. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  4004. if (m.title && !title) title = m.title;
  4005. if (m.collapsed && (!collapsed || collapsed.marker.size < m.size))
  4006. collapsed = sp;
  4007. } else if (sp.from > pos && nextChange > sp.from) {
  4008. nextChange = sp.from;
  4009. }
  4010. if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmark = m;
  4011. }
  4012. if (collapsed && (collapsed.from || 0) == pos) {
  4013. buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
  4014. collapsed.marker, collapsed.from == null);
  4015. if (collapsed.to == null) return collapsed.marker.find();
  4016. }
  4017. if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
  4018. }
  4019. if (pos >= len) break;
  4020. var upto = Math.min(len, nextChange);
  4021. while (true) {
  4022. if (text) {
  4023. var end = pos + text.length;
  4024. if (!collapsed) {
  4025. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  4026. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  4027. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
  4028. }
  4029. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  4030. pos = end;
  4031. spanStartStyle = "";
  4032. }
  4033. text = allText.slice(at, at = styles[i++]);
  4034. style = styleToClass(styles[i++]);
  4035. }
  4036. }
  4037. }
  4038. // DOCUMENT DATA STRUCTURE
  4039. function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) {
  4040. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  4041. function update(line, text, spans) {
  4042. updateLine(line, text, spans, estimateHeight);
  4043. signalLater(line, "change", line, change);
  4044. }
  4045. var from = change.from, to = change.to, text = change.text;
  4046. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4047. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4048. // First adjust the line structure
  4049. if (from.ch == 0 && to.ch == 0 && lastText == "") {
  4050. // This is a whole-line replace. Treated specially to make
  4051. // sure line objects move the way they are supposed to.
  4052. for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
  4053. added.push(new Line(text[i], spansFor(i), estimateHeight));
  4054. update(lastLine, lastLine.text, lastSpans);
  4055. if (nlines) doc.remove(from.line, nlines);
  4056. if (added.length) doc.insert(from.line, added);
  4057. } else if (firstLine == lastLine) {
  4058. if (text.length == 1) {
  4059. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4060. } else {
  4061. for (var added = [], i = 1, e = text.length - 1; i < e; ++i)
  4062. added.push(new Line(text[i], spansFor(i), estimateHeight));
  4063. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4064. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4065. doc.insert(from.line + 1, added);
  4066. }
  4067. } else if (text.length == 1) {
  4068. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4069. doc.remove(from.line + 1, nlines);
  4070. } else {
  4071. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4072. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4073. for (var i = 1, e = text.length - 1, added = []; i < e; ++i)
  4074. added.push(new Line(text[i], spansFor(i), estimateHeight));
  4075. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  4076. doc.insert(from.line + 1, added);
  4077. }
  4078. signalLater(doc, "change", doc, change);
  4079. setSelection(doc, selAfter.anchor, selAfter.head, null, true);
  4080. }
  4081. function LeafChunk(lines) {
  4082. this.lines = lines;
  4083. this.parent = null;
  4084. for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
  4085. lines[i].parent = this;
  4086. height += lines[i].height;
  4087. }
  4088. this.height = height;
  4089. }
  4090. LeafChunk.prototype = {
  4091. chunkSize: function() { return this.lines.length; },
  4092. removeInner: function(at, n) {
  4093. for (var i = at, e = at + n; i < e; ++i) {
  4094. var line = this.lines[i];
  4095. this.height -= line.height;
  4096. cleanUpLine(line);
  4097. signalLater(line, "delete");
  4098. }
  4099. this.lines.splice(at, n);
  4100. },
  4101. collapse: function(lines) {
  4102. lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
  4103. },
  4104. insertInner: function(at, lines, height) {
  4105. this.height += height;
  4106. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  4107. for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
  4108. },
  4109. iterN: function(at, n, op) {
  4110. for (var e = at + n; at < e; ++at)
  4111. if (op(this.lines[at])) return true;
  4112. }
  4113. };
  4114. function BranchChunk(children) {
  4115. this.children = children;
  4116. var size = 0, height = 0;
  4117. for (var i = 0, e = children.length; i < e; ++i) {
  4118. var ch = children[i];
  4119. size += ch.chunkSize(); height += ch.height;
  4120. ch.parent = this;
  4121. }
  4122. this.size = size;
  4123. this.height = height;
  4124. this.parent = null;
  4125. }
  4126. BranchChunk.prototype = {
  4127. chunkSize: function() { return this.size; },
  4128. removeInner: function(at, n) {
  4129. this.size -= n;
  4130. for (var i = 0; i < this.children.length; ++i) {
  4131. var child = this.children[i], sz = child.chunkSize();
  4132. if (at < sz) {
  4133. var rm = Math.min(n, sz - at), oldHeight = child.height;
  4134. child.removeInner(at, rm);
  4135. this.height -= oldHeight - child.height;
  4136. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  4137. if ((n -= rm) == 0) break;
  4138. at = 0;
  4139. } else at -= sz;
  4140. }
  4141. if (this.size - n < 25) {
  4142. var lines = [];
  4143. this.collapse(lines);
  4144. this.children = [new LeafChunk(lines)];
  4145. this.children[0].parent = this;
  4146. }
  4147. },
  4148. collapse: function(lines) {
  4149. for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
  4150. },
  4151. insertInner: function(at, lines, height) {
  4152. this.size += lines.length;
  4153. this.height += height;
  4154. for (var i = 0, e = this.children.length; i < e; ++i) {
  4155. var child = this.children[i], sz = child.chunkSize();
  4156. if (at <= sz) {
  4157. child.insertInner(at, lines, height);
  4158. if (child.lines && child.lines.length > 50) {
  4159. while (child.lines.length > 50) {
  4160. var spilled = child.lines.splice(child.lines.length - 25, 25);
  4161. var newleaf = new LeafChunk(spilled);
  4162. child.height -= newleaf.height;
  4163. this.children.splice(i + 1, 0, newleaf);
  4164. newleaf.parent = this;
  4165. }
  4166. this.maybeSpill();
  4167. }
  4168. break;
  4169. }
  4170. at -= sz;
  4171. }
  4172. },
  4173. maybeSpill: function() {
  4174. if (this.children.length <= 10) return;
  4175. var me = this;
  4176. do {
  4177. var spilled = me.children.splice(me.children.length - 5, 5);
  4178. var sibling = new BranchChunk(spilled);
  4179. if (!me.parent) { // Become the parent node
  4180. var copy = new BranchChunk(me.children);
  4181. copy.parent = me;
  4182. me.children = [copy, sibling];
  4183. me = copy;
  4184. } else {
  4185. me.size -= sibling.size;
  4186. me.height -= sibling.height;
  4187. var myIndex = indexOf(me.parent.children, me);
  4188. me.parent.children.splice(myIndex + 1, 0, sibling);
  4189. }
  4190. sibling.parent = me.parent;
  4191. } while (me.children.length > 10);
  4192. me.parent.maybeSpill();
  4193. },
  4194. iterN: function(at, n, op) {
  4195. for (var i = 0, e = this.children.length; i < e; ++i) {
  4196. var child = this.children[i], sz = child.chunkSize();
  4197. if (at < sz) {
  4198. var used = Math.min(n, sz - at);
  4199. if (child.iterN(at, used, op)) return true;
  4200. if ((n -= used) == 0) break;
  4201. at = 0;
  4202. } else at -= sz;
  4203. }
  4204. }
  4205. };
  4206. var nextDocId = 0;
  4207. var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
  4208. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  4209. if (firstLine == null) firstLine = 0;
  4210. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  4211. this.first = firstLine;
  4212. this.scrollTop = this.scrollLeft = 0;
  4213. this.cantEdit = false;
  4214. this.history = makeHistory();
  4215. this.cleanGeneration = 1;
  4216. this.frontier = firstLine;
  4217. var start = Pos(firstLine, 0);
  4218. this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null};
  4219. this.id = ++nextDocId;
  4220. this.modeOption = mode;
  4221. if (typeof text == "string") text = splitLines(text);
  4222. updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start});
  4223. };
  4224. Doc.prototype = createObj(BranchChunk.prototype, {
  4225. constructor: Doc,
  4226. iter: function(from, to, op) {
  4227. if (op) this.iterN(from - this.first, to - from, op);
  4228. else this.iterN(this.first, this.first + this.size, from);
  4229. },
  4230. insert: function(at, lines) {
  4231. var height = 0;
  4232. for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
  4233. this.insertInner(at - this.first, lines, height);
  4234. },
  4235. remove: function(at, n) { this.removeInner(at - this.first, n); },
  4236. getValue: function(lineSep) {
  4237. var lines = getLines(this, this.first, this.first + this.size);
  4238. if (lineSep === false) return lines;
  4239. return lines.join(lineSep || "\n");
  4240. },
  4241. setValue: function(code) {
  4242. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  4243. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  4244. text: splitLines(code), origin: "setValue"},
  4245. {head: top, anchor: top}, true);
  4246. },
  4247. replaceRange: function(code, from, to, origin) {
  4248. from = clipPos(this, from);
  4249. to = to ? clipPos(this, to) : from;
  4250. replaceRange(this, code, from, to, origin);
  4251. },
  4252. getRange: function(from, to, lineSep) {
  4253. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  4254. if (lineSep === false) return lines;
  4255. return lines.join(lineSep || "\n");
  4256. },
  4257. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  4258. setLine: function(line, text) {
  4259. if (isLine(this, line))
  4260. replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line)));
  4261. },
  4262. removeLine: function(line) {
  4263. if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line)));
  4264. else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0)));
  4265. },
  4266. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  4267. getLineNumber: function(line) {return lineNo(line);},
  4268. getLineHandleVisualStart: function(line) {
  4269. if (typeof line == "number") line = getLine(this, line);
  4270. return visualLine(this, line);
  4271. },
  4272. lineCount: function() {return this.size;},
  4273. firstLine: function() {return this.first;},
  4274. lastLine: function() {return this.first + this.size - 1;},
  4275. clipPos: function(pos) {return clipPos(this, pos);},
  4276. getCursor: function(start) {
  4277. var sel = this.sel, pos;
  4278. if (start == null || start == "head") pos = sel.head;
  4279. else if (start == "anchor") pos = sel.anchor;
  4280. else if (start == "end" || start === false) pos = sel.to;
  4281. else pos = sel.from;
  4282. return copyPos(pos);
  4283. },
  4284. somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);},
  4285. setCursor: docOperation(function(line, ch, extend) {
  4286. var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line);
  4287. if (extend) extendSelection(this, pos);
  4288. else setSelection(this, pos, pos);
  4289. }),
  4290. setSelection: docOperation(function(anchor, head) {
  4291. setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor));
  4292. }),
  4293. extendSelection: docOperation(function(from, to) {
  4294. extendSelection(this, clipPos(this, from), to && clipPos(this, to));
  4295. }),
  4296. getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
  4297. replaceSelection: function(code, collapse, origin) {
  4298. makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around");
  4299. },
  4300. undo: docOperation(function() {makeChangeFromHistory(this, "undo");}),
  4301. redo: docOperation(function() {makeChangeFromHistory(this, "redo");}),
  4302. setExtending: function(val) {this.sel.extend = val;},
  4303. historySize: function() {
  4304. var hist = this.history;
  4305. return {undo: hist.done.length, redo: hist.undone.length};
  4306. },
  4307. clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);},
  4308. markClean: function() {
  4309. this.cleanGeneration = this.changeGeneration();
  4310. },
  4311. changeGeneration: function() {
  4312. this.history.lastOp = this.history.lastOrigin = null;
  4313. return this.history.generation;
  4314. },
  4315. isClean: function (gen) {
  4316. return this.history.generation == (gen || this.cleanGeneration);
  4317. },
  4318. getHistory: function() {
  4319. return {done: copyHistoryArray(this.history.done),
  4320. undone: copyHistoryArray(this.history.undone)};
  4321. },
  4322. setHistory: function(histData) {
  4323. var hist = this.history = makeHistory(this.history.maxGeneration);
  4324. hist.done = histData.done.slice(0);
  4325. hist.undone = histData.undone.slice(0);
  4326. },
  4327. markText: function(from, to, options) {
  4328. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  4329. },
  4330. setBookmark: function(pos, options) {
  4331. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  4332. insertLeft: options && options.insertLeft};
  4333. pos = clipPos(this, pos);
  4334. return markText(this, pos, pos, realOpts, "bookmark");
  4335. },
  4336. findMarksAt: function(pos) {
  4337. pos = clipPos(this, pos);
  4338. var markers = [], spans = getLine(this, pos.line).markedSpans;
  4339. if (spans) for (var i = 0; i < spans.length; ++i) {
  4340. var span = spans[i];
  4341. if ((span.from == null || span.from <= pos.ch) &&
  4342. (span.to == null || span.to >= pos.ch))
  4343. markers.push(span.marker.parent || span.marker);
  4344. }
  4345. return markers;
  4346. },
  4347. getAllMarks: function() {
  4348. var markers = [];
  4349. this.iter(function(line) {
  4350. var sps = line.markedSpans;
  4351. if (sps) for (var i = 0; i < sps.length; ++i)
  4352. if (sps[i].from != null) markers.push(sps[i].marker);
  4353. });
  4354. return markers;
  4355. },
  4356. posFromIndex: function(off) {
  4357. var ch, lineNo = this.first;
  4358. this.iter(function(line) {
  4359. var sz = line.text.length + 1;
  4360. if (sz > off) { ch = off; return true; }
  4361. off -= sz;
  4362. ++lineNo;
  4363. });
  4364. return clipPos(this, Pos(lineNo, ch));
  4365. },
  4366. indexFromPos: function (coords) {
  4367. coords = clipPos(this, coords);
  4368. var index = coords.ch;
  4369. if (coords.line < this.first || coords.ch < 0) return 0;
  4370. this.iter(this.first, coords.line, function (line) {
  4371. index += line.text.length + 1;
  4372. });
  4373. return index;
  4374. },
  4375. copy: function(copyHistory) {
  4376. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  4377. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  4378. doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor,
  4379. shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn};
  4380. if (copyHistory) {
  4381. doc.history.undoDepth = this.history.undoDepth;
  4382. doc.setHistory(this.getHistory());
  4383. }
  4384. return doc;
  4385. },
  4386. linkedDoc: function(options) {
  4387. if (!options) options = {};
  4388. var from = this.first, to = this.first + this.size;
  4389. if (options.from != null && options.from > from) from = options.from;
  4390. if (options.to != null && options.to < to) to = options.to;
  4391. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  4392. if (options.sharedHist) copy.history = this.history;
  4393. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  4394. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  4395. return copy;
  4396. },
  4397. unlinkDoc: function(other) {
  4398. if (other instanceof CodeMirror) other = other.doc;
  4399. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  4400. var link = this.linked[i];
  4401. if (link.doc != other) continue;
  4402. this.linked.splice(i, 1);
  4403. other.unlinkDoc(this);
  4404. break;
  4405. }
  4406. // If the histories were shared, split them again
  4407. if (other.history == this.history) {
  4408. var splitIds = [other.id];
  4409. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  4410. other.history = makeHistory();
  4411. other.history.done = copyHistoryArray(this.history.done, splitIds);
  4412. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  4413. }
  4414. },
  4415. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  4416. getMode: function() {return this.mode;},
  4417. getEditor: function() {return this.cm;}
  4418. });
  4419. Doc.prototype.eachLine = Doc.prototype.iter;
  4420. // The Doc methods that should be available on CodeMirror instances
  4421. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  4422. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  4423. CodeMirror.prototype[prop] = (function(method) {
  4424. return function() {return method.apply(this.doc, arguments);};
  4425. })(Doc.prototype[prop]);
  4426. eventMixin(Doc);
  4427. function linkedDocs(doc, f, sharedHistOnly) {
  4428. function propagate(doc, skip, sharedHist) {
  4429. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  4430. var rel = doc.linked[i];
  4431. if (rel.doc == skip) continue;
  4432. var shared = sharedHist && rel.sharedHist;
  4433. if (sharedHistOnly && !shared) continue;
  4434. f(rel.doc, shared);
  4435. propagate(rel.doc, doc, shared);
  4436. }
  4437. }
  4438. propagate(doc, null, true);
  4439. }
  4440. function attachDoc(cm, doc) {
  4441. if (doc.cm) throw new Error("This document is already in use.");
  4442. cm.doc = doc;
  4443. doc.cm = cm;
  4444. estimateLineHeights(cm);
  4445. loadMode(cm);
  4446. if (!cm.options.lineWrapping) computeMaxLength(cm);
  4447. cm.options.mode = doc.modeOption;
  4448. regChange(cm);
  4449. }
  4450. // LINE UTILITIES
  4451. function getLine(chunk, n) {
  4452. n -= chunk.first;
  4453. while (!chunk.lines) {
  4454. for (var i = 0;; ++i) {
  4455. var child = chunk.children[i], sz = child.chunkSize();
  4456. if (n < sz) { chunk = child; break; }
  4457. n -= sz;
  4458. }
  4459. }
  4460. return chunk.lines[n];
  4461. }
  4462. function getBetween(doc, start, end) {
  4463. var out = [], n = start.line;
  4464. doc.iter(start.line, end.line + 1, function(line) {
  4465. var text = line.text;
  4466. if (n == end.line) text = text.slice(0, end.ch);
  4467. if (n == start.line) text = text.slice(start.ch);
  4468. out.push(text);
  4469. ++n;
  4470. });
  4471. return out;
  4472. }
  4473. function getLines(doc, from, to) {
  4474. var out = [];
  4475. doc.iter(from, to, function(line) { out.push(line.text); });
  4476. return out;
  4477. }
  4478. function updateLineHeight(line, height) {
  4479. var diff = height - line.height;
  4480. for (var n = line; n; n = n.parent) n.height += diff;
  4481. }
  4482. function lineNo(line) {
  4483. if (line.parent == null) return null;
  4484. var cur = line.parent, no = indexOf(cur.lines, line);
  4485. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  4486. for (var i = 0;; ++i) {
  4487. if (chunk.children[i] == cur) break;
  4488. no += chunk.children[i].chunkSize();
  4489. }
  4490. }
  4491. return no + cur.first;
  4492. }
  4493. function lineAtHeight(chunk, h) {
  4494. var n = chunk.first;
  4495. outer: do {
  4496. for (var i = 0, e = chunk.children.length; i < e; ++i) {
  4497. var child = chunk.children[i], ch = child.height;
  4498. if (h < ch) { chunk = child; continue outer; }
  4499. h -= ch;
  4500. n += child.chunkSize();
  4501. }
  4502. return n;
  4503. } while (!chunk.lines);
  4504. for (var i = 0, e = chunk.lines.length; i < e; ++i) {
  4505. var line = chunk.lines[i], lh = line.height;
  4506. if (h < lh) break;
  4507. h -= lh;
  4508. }
  4509. return n + i;
  4510. }
  4511. function heightAtLine(cm, lineObj) {
  4512. lineObj = visualLine(cm.doc, lineObj);
  4513. var h = 0, chunk = lineObj.parent;
  4514. for (var i = 0; i < chunk.lines.length; ++i) {
  4515. var line = chunk.lines[i];
  4516. if (line == lineObj) break;
  4517. else h += line.height;
  4518. }
  4519. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  4520. for (var i = 0; i < p.children.length; ++i) {
  4521. var cur = p.children[i];
  4522. if (cur == chunk) break;
  4523. else h += cur.height;
  4524. }
  4525. }
  4526. return h;
  4527. }
  4528. function getOrder(line) {
  4529. var order = line.order;
  4530. if (order == null) order = line.order = bidiOrdering(line.text);
  4531. return order;
  4532. }
  4533. // HISTORY
  4534. function makeHistory(startGen) {
  4535. return {
  4536. // Arrays of history events. Doing something adds an event to
  4537. // done and clears undo. Undoing moves events from done to
  4538. // undone, redoing moves them in the other direction.
  4539. done: [], undone: [], undoDepth: Infinity,
  4540. // Used to track when changes can be merged into a single undo
  4541. // event
  4542. lastTime: 0, lastOp: null, lastOrigin: null,
  4543. // Used by the isClean() method
  4544. generation: startGen || 1, maxGeneration: startGen || 1
  4545. };
  4546. }
  4547. function attachLocalSpans(doc, change, from, to) {
  4548. var existing = change["spans_" + doc.id], n = 0;
  4549. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  4550. if (line.markedSpans)
  4551. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  4552. ++n;
  4553. });
  4554. }
  4555. function historyChangeFromChange(doc, change) {
  4556. var from = { line: change.from.line, ch: change.from.ch };
  4557. var histChange = {from: from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4558. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4559. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  4560. return histChange;
  4561. }
  4562. function addToHistory(doc, change, selAfter, opId) {
  4563. var hist = doc.history;
  4564. hist.undone.length = 0;
  4565. var time = +new Date, cur = lst(hist.done);
  4566. if (cur &&
  4567. (hist.lastOp == opId ||
  4568. hist.lastOrigin == change.origin && change.origin &&
  4569. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) ||
  4570. change.origin.charAt(0) == "*"))) {
  4571. // Merge this change into the last event
  4572. var last = lst(cur.changes);
  4573. if (posEq(change.from, change.to) && posEq(change.from, last.to)) {
  4574. // Optimized case for simple insertion -- don't want to add
  4575. // new changesets for every character typed
  4576. last.to = changeEnd(change);
  4577. } else {
  4578. // Add new sub-event
  4579. cur.changes.push(historyChangeFromChange(doc, change));
  4580. }
  4581. cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head;
  4582. } else {
  4583. // Can not be merged, start a new event.
  4584. cur = {changes: [historyChangeFromChange(doc, change)],
  4585. generation: hist.generation,
  4586. anchorBefore: doc.sel.anchor, headBefore: doc.sel.head,
  4587. anchorAfter: selAfter.anchor, headAfter: selAfter.head};
  4588. hist.done.push(cur);
  4589. hist.generation = ++hist.maxGeneration;
  4590. while (hist.done.length > hist.undoDepth)
  4591. hist.done.shift();
  4592. }
  4593. hist.lastTime = time;
  4594. hist.lastOp = opId;
  4595. hist.lastOrigin = change.origin;
  4596. }
  4597. function removeClearedSpans(spans) {
  4598. if (!spans) return null;
  4599. for (var i = 0, out; i < spans.length; ++i) {
  4600. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  4601. else if (out) out.push(spans[i]);
  4602. }
  4603. return !out ? spans : out.length ? out : null;
  4604. }
  4605. function getOldSpans(doc, change) {
  4606. var found = change["spans_" + doc.id];
  4607. if (!found) return null;
  4608. for (var i = 0, nw = []; i < change.text.length; ++i)
  4609. nw.push(removeClearedSpans(found[i]));
  4610. return nw;
  4611. }
  4612. // Used both to provide a JSON-safe object in .getHistory, and, when
  4613. // detaching a document, to split the history in two
  4614. function copyHistoryArray(events, newGroup) {
  4615. for (var i = 0, copy = []; i < events.length; ++i) {
  4616. var event = events[i], changes = event.changes, newChanges = [];
  4617. copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore,
  4618. anchorAfter: event.anchorAfter, headAfter: event.headAfter});
  4619. for (var j = 0; j < changes.length; ++j) {
  4620. var change = changes[j], m;
  4621. newChanges.push({from: change.from, to: change.to, text: change.text});
  4622. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  4623. if (indexOf(newGroup, Number(m[1])) > -1) {
  4624. lst(newChanges)[prop] = change[prop];
  4625. delete change[prop];
  4626. }
  4627. }
  4628. }
  4629. }
  4630. return copy;
  4631. }
  4632. // Rebasing/resetting history to deal with externally-sourced changes
  4633. function rebaseHistSel(pos, from, to, diff) {
  4634. if (to < pos.line) {
  4635. pos.line += diff;
  4636. } else if (from < pos.line) {
  4637. pos.line = from;
  4638. pos.ch = 0;
  4639. }
  4640. }
  4641. // Tries to rebase an array of history events given a change in the
  4642. // document. If the change touches the same lines as the event, the
  4643. // event, and everything 'behind' it, is discarded. If the change is
  4644. // before the event, the event's positions are updated. Uses a
  4645. // copy-on-write scheme for the positions, to avoid having to
  4646. // reallocate them all on every rebase, but also avoid problems with
  4647. // shared position objects being unsafely updated.
  4648. function rebaseHistArray(array, from, to, diff) {
  4649. for (var i = 0; i < array.length; ++i) {
  4650. var sub = array[i], ok = true;
  4651. for (var j = 0; j < sub.changes.length; ++j) {
  4652. var cur = sub.changes[j];
  4653. if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); }
  4654. if (to < cur.from.line) {
  4655. cur.from.line += diff;
  4656. cur.to.line += diff;
  4657. } else if (from <= cur.to.line) {
  4658. ok = false;
  4659. break;
  4660. }
  4661. }
  4662. if (!sub.copied) {
  4663. sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore);
  4664. sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter);
  4665. sub.copied = true;
  4666. }
  4667. if (!ok) {
  4668. array.splice(0, i + 1);
  4669. i = 0;
  4670. } else {
  4671. rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore);
  4672. rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter);
  4673. }
  4674. }
  4675. }
  4676. function rebaseHist(hist, change) {
  4677. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  4678. rebaseHistArray(hist.done, from, to, diff);
  4679. rebaseHistArray(hist.undone, from, to, diff);
  4680. }
  4681. // EVENT OPERATORS
  4682. function stopMethod() {e_stop(this);}
  4683. // Ensure an event has a stop method.
  4684. function addStop(event) {
  4685. if (!event.stop) event.stop = stopMethod;
  4686. return event;
  4687. }
  4688. function e_preventDefault(e) {
  4689. if (e.preventDefault) e.preventDefault();
  4690. else e.returnValue = false;
  4691. }
  4692. function e_stopPropagation(e) {
  4693. if (e.stopPropagation) e.stopPropagation();
  4694. else e.cancelBubble = true;
  4695. }
  4696. function e_defaultPrevented(e) {
  4697. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  4698. }
  4699. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  4700. CodeMirror.e_stop = e_stop;
  4701. CodeMirror.e_preventDefault = e_preventDefault;
  4702. CodeMirror.e_stopPropagation = e_stopPropagation;
  4703. function e_target(e) {return e.target || e.srcElement;}
  4704. function e_button(e) {
  4705. var b = e.which;
  4706. if (b == null) {
  4707. if (e.button & 1) b = 1;
  4708. else if (e.button & 2) b = 3;
  4709. else if (e.button & 4) b = 2;
  4710. }
  4711. if (mac && e.ctrlKey && b == 1) b = 3;
  4712. return b;
  4713. }
  4714. // EVENT HANDLING
  4715. function on(emitter, type, f) {
  4716. if (emitter.addEventListener)
  4717. emitter.addEventListener(type, f, false);
  4718. else if (emitter.attachEvent)
  4719. emitter.attachEvent("on" + type, f);
  4720. else {
  4721. var map = emitter._handlers || (emitter._handlers = {});
  4722. var arr = map[type] || (map[type] = []);
  4723. arr.push(f);
  4724. }
  4725. }
  4726. function off(emitter, type, f) {
  4727. if (emitter.removeEventListener)
  4728. emitter.removeEventListener(type, f, false);
  4729. else if (emitter.detachEvent)
  4730. emitter.detachEvent("on" + type, f);
  4731. else {
  4732. var arr = emitter._handlers && emitter._handlers[type];
  4733. if (!arr) return;
  4734. for (var i = 0; i < arr.length; ++i)
  4735. if (arr[i] == f) { arr.splice(i, 1); break; }
  4736. }
  4737. }
  4738. function signal(emitter, type /*, values...*/) {
  4739. var arr = emitter._handlers && emitter._handlers[type];
  4740. if (!arr) return;
  4741. var args = Array.prototype.slice.call(arguments, 2);
  4742. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  4743. }
  4744. var delayedCallbacks, delayedCallbackDepth = 0;
  4745. function signalLater(emitter, type /*, values...*/) {
  4746. var arr = emitter._handlers && emitter._handlers[type];
  4747. if (!arr) return;
  4748. var args = Array.prototype.slice.call(arguments, 2);
  4749. if (!delayedCallbacks) {
  4750. ++delayedCallbackDepth;
  4751. delayedCallbacks = [];
  4752. setTimeout(fireDelayed, 0);
  4753. }
  4754. function bnd(f) {return function(){f.apply(null, args);};};
  4755. for (var i = 0; i < arr.length; ++i)
  4756. delayedCallbacks.push(bnd(arr[i]));
  4757. }
  4758. function signalDOMEvent(cm, e, override) {
  4759. signal(cm, override || e.type, cm, e);
  4760. return e_defaultPrevented(e) || e.codemirrorIgnore;
  4761. }
  4762. function fireDelayed() {
  4763. --delayedCallbackDepth;
  4764. var delayed = delayedCallbacks;
  4765. delayedCallbacks = null;
  4766. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  4767. }
  4768. function hasHandler(emitter, type) {
  4769. var arr = emitter._handlers && emitter._handlers[type];
  4770. return arr && arr.length > 0;
  4771. }
  4772. CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
  4773. function eventMixin(ctor) {
  4774. ctor.prototype.on = function(type, f) {on(this, type, f);};
  4775. ctor.prototype.off = function(type, f) {off(this, type, f);};
  4776. }
  4777. // MISC UTILITIES
  4778. // Number of pixels added to scroller and sizer to hide scrollbar
  4779. var scrollerCutOff = 30;
  4780. // Returned or thrown by various protocols to signal 'I'm not
  4781. // handling this'.
  4782. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  4783. function Delayed() {this.id = null;}
  4784. Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
  4785. // Counts the column offset in a string, taking tabs into account.
  4786. // Used mostly to find indentation.
  4787. function countColumn(string, end, tabSize, startIndex, startValue) {
  4788. if (end == null) {
  4789. end = string.search(/[^\s\u00a0]/);
  4790. if (end == -1) end = string.length;
  4791. }
  4792. for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) {
  4793. if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
  4794. else ++n;
  4795. }
  4796. return n;
  4797. }
  4798. CodeMirror.countColumn = countColumn;
  4799. var spaceStrs = [""];
  4800. function spaceStr(n) {
  4801. while (spaceStrs.length <= n)
  4802. spaceStrs.push(lst(spaceStrs) + " ");
  4803. return spaceStrs[n];
  4804. }
  4805. function lst(arr) { return arr[arr.length-1]; }
  4806. function selectInput(node) {
  4807. if (ios) { // Mobile Safari apparently has a bug where select() is broken.
  4808. node.selectionStart = 0;
  4809. node.selectionEnd = node.value.length;
  4810. } else {
  4811. // Suppress mysterious IE10 errors
  4812. try { node.select(); }
  4813. catch(_e) {}
  4814. }
  4815. }
  4816. function indexOf(collection, elt) {
  4817. if (collection.indexOf) return collection.indexOf(elt);
  4818. for (var i = 0, e = collection.length; i < e; ++i)
  4819. if (collection[i] == elt) return i;
  4820. return -1;
  4821. }
  4822. function createObj(base, props) {
  4823. function Obj() {}
  4824. Obj.prototype = base;
  4825. var inst = new Obj();
  4826. if (props) copyObj(props, inst);
  4827. return inst;
  4828. }
  4829. function copyObj(obj, target) {
  4830. if (!target) target = {};
  4831. for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
  4832. return target;
  4833. }
  4834. function emptyArray(size) {
  4835. for (var a = [], i = 0; i < size; ++i) a.push(undefined);
  4836. return a;
  4837. }
  4838. function bind(f) {
  4839. var args = Array.prototype.slice.call(arguments, 1);
  4840. return function(){return f.apply(null, args);};
  4841. }
  4842. var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  4843. function isWordChar(ch) {
  4844. return /\w/.test(ch) || ch > "\x80" &&
  4845. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  4846. }
  4847. function isEmpty(obj) {
  4848. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  4849. return true;
  4850. }
  4851. var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/;
  4852. // DOM UTILITIES
  4853. function elt(tag, content, className, style) {
  4854. var e = document.createElement(tag);
  4855. if (className) e.className = className;
  4856. if (style) e.style.cssText = style;
  4857. if (typeof content == "string") setTextContent(e, content);
  4858. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  4859. return e;
  4860. }
  4861. function removeChildren(e) {
  4862. for (var count = e.childNodes.length; count > 0; --count)
  4863. e.removeChild(e.firstChild);
  4864. return e;
  4865. }
  4866. function removeChildrenAndAdd(parent, e) {
  4867. return removeChildren(parent).appendChild(e);
  4868. }
  4869. function setTextContent(e, str) {
  4870. if (ie_lt9) {
  4871. e.innerHTML = "";
  4872. e.appendChild(document.createTextNode(str));
  4873. } else e.textContent = str;
  4874. }
  4875. function getRect(node) {
  4876. return node.getBoundingClientRect();
  4877. }
  4878. CodeMirror.replaceGetRect = function(f) { getRect = f; };
  4879. // FEATURE DETECTION
  4880. // Detect drag-and-drop
  4881. var dragAndDrop = function() {
  4882. // There is *some* kind of drag-and-drop support in IE6-8, but I
  4883. // couldn't get it to work yet.
  4884. if (ie_lt9) return false;
  4885. var div = elt('div');
  4886. return "draggable" in div || "dragDrop" in div;
  4887. }();
  4888. // For a reason I have yet to figure out, some browsers disallow
  4889. // word wrapping between certain characters *only* if a new inline
  4890. // element is started between them. This makes it hard to reliably
  4891. // measure the position of things, since that requires inserting an
  4892. // extra span. This terribly fragile set of tests matches the
  4893. // character combinations that suffer from this phenomenon on the
  4894. // various browsers.
  4895. function spanAffectsWrapping() { return false; }
  4896. if (gecko) // Only for "$'"
  4897. spanAffectsWrapping = function(str, i) {
  4898. return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39;
  4899. };
  4900. else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent))
  4901. spanAffectsWrapping = function(str, i) {
  4902. return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1));
  4903. };
  4904. else if (webkit && !/Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent))
  4905. spanAffectsWrapping = function(str, i) {
  4906. if (i > 1 && str.charCodeAt(i - 1) == 45) {
  4907. if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) return true;
  4908. if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.charAt(i))) return false;
  4909. }
  4910. return /[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1));
  4911. };
  4912. var knownScrollbarWidth;
  4913. function scrollbarWidth(measure) {
  4914. if (knownScrollbarWidth != null) return knownScrollbarWidth;
  4915. var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
  4916. removeChildrenAndAdd(measure, test);
  4917. if (test.offsetWidth)
  4918. knownScrollbarWidth = test.offsetHeight - test.clientHeight;
  4919. return knownScrollbarWidth || 0;
  4920. }
  4921. var zwspSupported;
  4922. function zeroWidthElement(measure) {
  4923. if (zwspSupported == null) {
  4924. var test = elt("span", "\u200b");
  4925. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  4926. if (measure.firstChild.offsetHeight != 0)
  4927. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
  4928. }
  4929. if (zwspSupported) return elt("span", "\u200b");
  4930. else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  4931. }
  4932. // See if "".split is the broken IE version, if so, provide an
  4933. // alternative way to split lines.
  4934. var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  4935. var pos = 0, result = [], l = string.length;
  4936. while (pos <= l) {
  4937. var nl = string.indexOf("\n", pos);
  4938. if (nl == -1) nl = string.length;
  4939. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  4940. var rt = line.indexOf("\r");
  4941. if (rt != -1) {
  4942. result.push(line.slice(0, rt));
  4943. pos += rt + 1;
  4944. } else {
  4945. result.push(line);
  4946. pos = nl + 1;
  4947. }
  4948. }
  4949. return result;
  4950. } : function(string){return string.split(/\r\n?|\n/);};
  4951. CodeMirror.splitLines = splitLines;
  4952. var hasSelection = window.getSelection ? function(te) {
  4953. try { return te.selectionStart != te.selectionEnd; }
  4954. catch(e) { return false; }
  4955. } : function(te) {
  4956. try {var range = te.ownerDocument.selection.createRange();}
  4957. catch(e) {}
  4958. if (!range || range.parentElement() != te) return false;
  4959. return range.compareEndPoints("StartToEnd", range) != 0;
  4960. };
  4961. var hasCopyEvent = (function() {
  4962. var e = elt("div");
  4963. if ("oncopy" in e) return true;
  4964. e.setAttribute("oncopy", "return;");
  4965. return typeof e.oncopy == 'function';
  4966. })();
  4967. // KEY NAMING
  4968. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  4969. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  4970. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  4971. 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
  4972. 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  4973. 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
  4974. 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
  4975. CodeMirror.keyNames = keyNames;
  4976. (function() {
  4977. // Number keys
  4978. for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
  4979. // Alphabetic keys
  4980. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  4981. // Function keys
  4982. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  4983. })();
  4984. // BIDI HELPERS
  4985. function iterateBidiSections(order, from, to, f) {
  4986. if (!order) return f(from, to, "ltr");
  4987. var found = false;
  4988. for (var i = 0; i < order.length; ++i) {
  4989. var part = order[i];
  4990. if (part.from < to && part.to > from || from == to && part.to == from) {
  4991. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  4992. found = true;
  4993. }
  4994. }
  4995. if (!found) f(from, to, "ltr");
  4996. }
  4997. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  4998. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  4999. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  5000. function lineRight(line) {
  5001. var order = getOrder(line);
  5002. if (!order) return line.text.length;
  5003. return bidiRight(lst(order));
  5004. }
  5005. function lineStart(cm, lineN) {
  5006. var line = getLine(cm.doc, lineN);
  5007. var visual = visualLine(cm.doc, line);
  5008. if (visual != line) lineN = lineNo(visual);
  5009. var order = getOrder(visual);
  5010. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  5011. return Pos(lineN, ch);
  5012. }
  5013. function lineEnd(cm, lineN) {
  5014. var merged, line;
  5015. while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN)))
  5016. lineN = merged.find().to.line;
  5017. var order = getOrder(line);
  5018. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  5019. return Pos(lineN, ch);
  5020. }
  5021. function compareBidiLevel(order, a, b) {
  5022. var linedir = order[0].level;
  5023. if (a == linedir) return true;
  5024. if (b == linedir) return false;
  5025. return a < b;
  5026. }
  5027. var bidiOther;
  5028. function getBidiPartAt(order, pos) {
  5029. for (var i = 0, found; i < order.length; ++i) {
  5030. var cur = order[i];
  5031. if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; }
  5032. if (cur.from == pos || cur.to == pos) {
  5033. if (found == null) {
  5034. found = i;
  5035. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  5036. bidiOther = found;
  5037. return i;
  5038. } else {
  5039. bidiOther = i;
  5040. return found;
  5041. }
  5042. }
  5043. }
  5044. bidiOther = null;
  5045. return found;
  5046. }
  5047. function moveInLine(line, pos, dir, byUnit) {
  5048. if (!byUnit) return pos + dir;
  5049. do pos += dir;
  5050. while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
  5051. return pos;
  5052. }
  5053. // This is somewhat involved. It is needed in order to move
  5054. // 'visually' through bi-directional text -- i.e., pressing left
  5055. // should make the cursor go left, even when in RTL text. The
  5056. // tricky part is the 'jumps', where RTL and LTR text touch each
  5057. // other. This often requires the cursor offset to move more than
  5058. // one unit, in order to visually move one unit.
  5059. function moveVisually(line, start, dir, byUnit) {
  5060. var bidi = getOrder(line);
  5061. if (!bidi) return moveLogically(line, start, dir, byUnit);
  5062. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  5063. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  5064. for (;;) {
  5065. if (target > part.from && target < part.to) return target;
  5066. if (target == part.from || target == part.to) {
  5067. if (getBidiPartAt(bidi, target) == pos) return target;
  5068. part = bidi[pos += dir];
  5069. return (dir > 0) == part.level % 2 ? part.to : part.from;
  5070. } else {
  5071. part = bidi[pos += dir];
  5072. if (!part) return null;
  5073. if ((dir > 0) == part.level % 2)
  5074. target = moveInLine(line, part.to, -1, byUnit);
  5075. else
  5076. target = moveInLine(line, part.from, 1, byUnit);
  5077. }
  5078. }
  5079. }
  5080. function moveLogically(line, start, dir, byUnit) {
  5081. var target = start + dir;
  5082. if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
  5083. return target < 0 || target > line.text.length ? null : target;
  5084. }
  5085. // Bidirectional ordering algorithm
  5086. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  5087. // that this (partially) implements.
  5088. // One-char codes used for character types:
  5089. // L (L): Left-to-Right
  5090. // R (R): Right-to-Left
  5091. // r (AL): Right-to-Left Arabic
  5092. // 1 (EN): European Number
  5093. // + (ES): European Number Separator
  5094. // % (ET): European Number Terminator
  5095. // n (AN): Arabic Number
  5096. // , (CS): Common Number Separator
  5097. // m (NSM): Non-Spacing Mark
  5098. // b (BN): Boundary Neutral
  5099. // s (B): Paragraph Separator
  5100. // t (S): Segment Separator
  5101. // w (WS): Whitespace
  5102. // N (ON): Other Neutrals
  5103. // Returns null if characters are ordered as they appear
  5104. // (left-to-right), or an array of sections ({from, to, level}
  5105. // objects) in the order in which they occur visually.
  5106. var bidiOrdering = (function() {
  5107. // Character types for codepoints 0 to 0xff
  5108. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
  5109. // Character types for codepoints 0x600 to 0x6ff
  5110. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
  5111. function charType(code) {
  5112. if (code <= 0xff) return lowTypes.charAt(code);
  5113. else if (0x590 <= code && code <= 0x5f4) return "R";
  5114. else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
  5115. else if (0x700 <= code && code <= 0x8ac) return "r";
  5116. else return "L";
  5117. }
  5118. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  5119. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  5120. // Browsers seem to always treat the boundaries of block elements as being L.
  5121. var outerType = "L";
  5122. return function(str) {
  5123. if (!bidiRE.test(str)) return false;
  5124. var len = str.length, types = [];
  5125. for (var i = 0, type; i < len; ++i)
  5126. types.push(type = charType(str.charCodeAt(i)));
  5127. // W1. Examine each non-spacing mark (NSM) in the level run, and
  5128. // change the type of the NSM to the type of the previous
  5129. // character. If the NSM is at the start of the level run, it will
  5130. // get the type of sor.
  5131. for (var i = 0, prev = outerType; i < len; ++i) {
  5132. var type = types[i];
  5133. if (type == "m") types[i] = prev;
  5134. else prev = type;
  5135. }
  5136. // W2. Search backwards from each instance of a European number
  5137. // until the first strong type (R, L, AL, or sor) is found. If an
  5138. // AL is found, change the type of the European number to Arabic
  5139. // number.
  5140. // W3. Change all ALs to R.
  5141. for (var i = 0, cur = outerType; i < len; ++i) {
  5142. var type = types[i];
  5143. if (type == "1" && cur == "r") types[i] = "n";
  5144. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  5145. }
  5146. // W4. A single European separator between two European numbers
  5147. // changes to a European number. A single common separator between
  5148. // two numbers of the same type changes to that type.
  5149. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  5150. var type = types[i];
  5151. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  5152. else if (type == "," && prev == types[i+1] &&
  5153. (prev == "1" || prev == "n")) types[i] = prev;
  5154. prev = type;
  5155. }
  5156. // W5. A sequence of European terminators adjacent to European
  5157. // numbers changes to all European numbers.
  5158. // W6. Otherwise, separators and terminators change to Other
  5159. // Neutral.
  5160. for (var i = 0; i < len; ++i) {
  5161. var type = types[i];
  5162. if (type == ",") types[i] = "N";
  5163. else if (type == "%") {
  5164. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  5165. var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
  5166. for (var j = i; j < end; ++j) types[j] = replace;
  5167. i = end - 1;
  5168. }
  5169. }
  5170. // W7. Search backwards from each instance of a European number
  5171. // until the first strong type (R, L, or sor) is found. If an L is
  5172. // found, then change the type of the European number to L.
  5173. for (var i = 0, cur = outerType; i < len; ++i) {
  5174. var type = types[i];
  5175. if (cur == "L" && type == "1") types[i] = "L";
  5176. else if (isStrong.test(type)) cur = type;
  5177. }
  5178. // N1. A sequence of neutrals takes the direction of the
  5179. // surrounding strong text if the text on both sides has the same
  5180. // direction. European and Arabic numbers act as if they were R in
  5181. // terms of their influence on neutrals. Start-of-level-run (sor)
  5182. // and end-of-level-run (eor) are used at level run boundaries.
  5183. // N2. Any remaining neutrals take the embedding direction.
  5184. for (var i = 0; i < len; ++i) {
  5185. if (isNeutral.test(types[i])) {
  5186. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  5187. var before = (i ? types[i-1] : outerType) == "L";
  5188. var after = (end < len - 1 ? types[end] : outerType) == "L";
  5189. var replace = before || after ? "L" : "R";
  5190. for (var j = i; j < end; ++j) types[j] = replace;
  5191. i = end - 1;
  5192. }
  5193. }
  5194. // Here we depart from the documented algorithm, in order to avoid
  5195. // building up an actual levels array. Since there are only three
  5196. // levels (0, 1, 2) in an implementation that doesn't take
  5197. // explicit embedding into account, we can build up the order on
  5198. // the fly, without following the level-based algorithm.
  5199. var order = [], m;
  5200. for (var i = 0; i < len;) {
  5201. if (countsAsLeft.test(types[i])) {
  5202. var start = i;
  5203. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  5204. order.push({from: start, to: i, level: 0});
  5205. } else {
  5206. var pos = i, at = order.length;
  5207. for (++i; i < len && types[i] != "L"; ++i) {}
  5208. for (var j = pos; j < i;) {
  5209. if (countsAsNum.test(types[j])) {
  5210. if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
  5211. var nstart = j;
  5212. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  5213. order.splice(at, 0, {from: nstart, to: j, level: 2});
  5214. pos = j;
  5215. } else ++j;
  5216. }
  5217. if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
  5218. }
  5219. }
  5220. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  5221. order[0].from = m[0].length;
  5222. order.unshift({from: 0, to: m[0].length, level: 0});
  5223. }
  5224. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  5225. lst(order).to -= m[0].length;
  5226. order.push({from: len - m[0].length, to: len, level: 0});
  5227. }
  5228. if (order[0].level != lst(order).level)
  5229. order.push({from: len, to: len, level: order[0].level});
  5230. return order;
  5231. };
  5232. })();
  5233. // THE END
  5234. CodeMirror.version = "3.15.0";
  5235. return CodeMirror;
  5236. })();