codemirror.js 314 KB

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