codemirror.js 310 KB

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