codemirror.js 339 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113
  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 (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global.CodeMirror = factory());
  12. }(this, (function () { 'use strict';
  13. // Kludges for bugs and behavior differences that can't be feature
  14. // detected are enabled based on userAgent etc sniffing.
  15. var userAgent = navigator.userAgent
  16. var platform = navigator.platform
  17. var gecko = /gecko\/\d/i.test(userAgent)
  18. var ie_upto10 = /MSIE \d/.test(userAgent)
  19. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
  20. var ie = ie_upto10 || ie_11up
  21. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1])
  22. var webkit = /WebKit\//.test(userAgent)
  23. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
  24. var chrome = /Chrome\//.test(userAgent)
  25. var presto = /Opera\//.test(userAgent)
  26. var safari = /Apple Computer/.test(navigator.vendor)
  27. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
  28. var phantom = /PhantomJS/.test(userAgent)
  29. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent)
  30. // This is woefully incomplete. Suggestions for alternative methods welcome.
  31. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
  32. var mac = ios || /Mac/.test(platform)
  33. var chromeOS = /\bCrOS\b/.test(userAgent)
  34. var windows = /win/i.test(platform)
  35. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
  36. if (presto_version) { presto_version = Number(presto_version[1]) }
  37. if (presto_version && presto_version >= 15) { presto = false; webkit = true }
  38. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  39. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))
  40. var captureRightClick = gecko || (ie && ie_version >= 9)
  41. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  42. var rmClass = function(node, cls) {
  43. var current = node.className
  44. var match = classTest(cls).exec(current)
  45. if (match) {
  46. var after = current.slice(match.index + match[0].length)
  47. node.className = current.slice(0, match.index) + (after ? match[1] + after : "")
  48. }
  49. }
  50. function removeChildren(e) {
  51. for (var count = e.childNodes.length; count > 0; --count)
  52. { e.removeChild(e.firstChild) }
  53. return e
  54. }
  55. function removeChildrenAndAdd(parent, e) {
  56. return removeChildren(parent).appendChild(e)
  57. }
  58. function elt(tag, content, className, style) {
  59. var e = document.createElement(tag)
  60. if (className) { e.className = className }
  61. if (style) { e.style.cssText = style }
  62. if (typeof content == "string") { e.appendChild(document.createTextNode(content)) }
  63. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } }
  64. return e
  65. }
  66. var range
  67. if (document.createRange) { range = function(node, start, end, endNode) {
  68. var r = document.createRange()
  69. r.setEnd(endNode || node, end)
  70. r.setStart(node, start)
  71. return r
  72. } }
  73. else { range = function(node, start, end) {
  74. var r = document.body.createTextRange()
  75. try { r.moveToElementText(node.parentNode) }
  76. catch(e) { return r }
  77. r.collapse(true)
  78. r.moveEnd("character", end)
  79. r.moveStart("character", start)
  80. return r
  81. } }
  82. function contains(parent, child) {
  83. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  84. { child = child.parentNode }
  85. if (parent.contains)
  86. { return parent.contains(child) }
  87. do {
  88. if (child.nodeType == 11) { child = child.host }
  89. if (child == parent) { return true }
  90. } while (child = child.parentNode)
  91. }
  92. function activeElt() {
  93. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  94. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  95. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  96. var activeElement
  97. try {
  98. activeElement = document.activeElement
  99. } catch(e) {
  100. activeElement = document.body || null
  101. }
  102. while (activeElement && activeElement.root && activeElement.root.activeElement)
  103. { activeElement = activeElement.root.activeElement }
  104. return activeElement
  105. }
  106. function addClass(node, cls) {
  107. var current = node.className
  108. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
  109. }
  110. function joinClasses(a, b) {
  111. var as = a.split(" ")
  112. for (var i = 0; i < as.length; i++)
  113. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
  114. return b
  115. }
  116. var selectInput = function(node) { node.select() }
  117. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  118. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
  119. else if (ie) // Suppress mysterious IE10 errors
  120. { selectInput = function(node) { try { node.select() } catch(_e) {} } }
  121. function bind(f) {
  122. var args = Array.prototype.slice.call(arguments, 1)
  123. return function(){return f.apply(null, args)}
  124. }
  125. function copyObj(obj, target, overwrite) {
  126. if (!target) { target = {} }
  127. for (var prop in obj)
  128. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  129. { target[prop] = obj[prop] } }
  130. return target
  131. }
  132. // Counts the column offset in a string, taking tabs into account.
  133. // Used mostly to find indentation.
  134. function countColumn(string, end, tabSize, startIndex, startValue) {
  135. if (end == null) {
  136. end = string.search(/[^\s\u00a0]/)
  137. if (end == -1) { end = string.length }
  138. }
  139. for (var i = startIndex || 0, n = startValue || 0;;) {
  140. var nextTab = string.indexOf("\t", i)
  141. if (nextTab < 0 || nextTab >= end)
  142. { return n + (end - i) }
  143. n += nextTab - i
  144. n += tabSize - (n % tabSize)
  145. i = nextTab + 1
  146. }
  147. }
  148. function Delayed() {this.id = null}
  149. Delayed.prototype.set = function(ms, f) {
  150. clearTimeout(this.id)
  151. this.id = setTimeout(f, ms)
  152. }
  153. function indexOf(array, elt) {
  154. for (var i = 0; i < array.length; ++i)
  155. { if (array[i] == elt) { return i } }
  156. return -1
  157. }
  158. // Number of pixels added to scroller and sizer to hide scrollbar
  159. var scrollerGap = 30
  160. // Returned or thrown by various protocols to signal 'I'm not
  161. // handling this'.
  162. var Pass = {toString: function(){return "CodeMirror.Pass"}}
  163. // Reused option objects for setSelection & friends
  164. var sel_dontScroll = {scroll: false};
  165. var sel_mouse = {origin: "*mouse"};
  166. var sel_move = {origin: "+move"};
  167. // The inverse of countColumn -- find the offset that corresponds to
  168. // a particular column.
  169. function findColumn(string, goal, tabSize) {
  170. for (var pos = 0, col = 0;;) {
  171. var nextTab = string.indexOf("\t", pos)
  172. if (nextTab == -1) { nextTab = string.length }
  173. var skipped = nextTab - pos
  174. if (nextTab == string.length || col + skipped >= goal)
  175. { return pos + Math.min(skipped, goal - col) }
  176. col += nextTab - pos
  177. col += tabSize - (col % tabSize)
  178. pos = nextTab + 1
  179. if (col >= goal) { return pos }
  180. }
  181. }
  182. var spaceStrs = [""]
  183. function spaceStr(n) {
  184. while (spaceStrs.length <= n)
  185. { spaceStrs.push(lst(spaceStrs) + " ") }
  186. return spaceStrs[n]
  187. }
  188. function lst(arr) { return arr[arr.length-1] }
  189. function map(array, f) {
  190. var out = []
  191. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
  192. return out
  193. }
  194. function insertSorted(array, value, score) {
  195. var pos = 0, priority = score(value)
  196. while (pos < array.length && score(array[pos]) <= priority) { pos++ }
  197. array.splice(pos, 0, value)
  198. }
  199. function nothing() {}
  200. function createObj(base, props) {
  201. var inst
  202. if (Object.create) {
  203. inst = Object.create(base)
  204. } else {
  205. nothing.prototype = base
  206. inst = new nothing()
  207. }
  208. if (props) { copyObj(props, inst) }
  209. return inst
  210. }
  211. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
  212. function isWordCharBasic(ch) {
  213. return /\w/.test(ch) || ch > "\x80" &&
  214. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  215. }
  216. function isWordChar(ch, helper) {
  217. if (!helper) { return isWordCharBasic(ch) }
  218. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  219. return helper.test(ch)
  220. }
  221. function isEmpty(obj) {
  222. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  223. return true
  224. }
  225. // Extending unicode characters. A series of a non-extending char +
  226. // any number of extending chars is treated as a single unit as far
  227. // as editing and measuring is concerned. This is not fully correct,
  228. // since some scripts/fonts/browsers also treat other configurations
  229. // of code points as a group.
  230. 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]/
  231. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  232. // The display handles the DOM integration, both for input reading
  233. // and content drawing. It holds references to DOM nodes and
  234. // display-related state.
  235. function Display(place, doc, input) {
  236. var d = this
  237. this.input = input
  238. // Covers bottom-right square when both scrollbars are present.
  239. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
  240. d.scrollbarFiller.setAttribute("cm-not-content", "true")
  241. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  242. // and h scrollbar is present.
  243. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
  244. d.gutterFiller.setAttribute("cm-not-content", "true")
  245. // Will contain the actual code, positioned to cover the viewport.
  246. d.lineDiv = elt("div", null, "CodeMirror-code")
  247. // Elements are added to these to represent selection and cursors.
  248. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
  249. d.cursorDiv = elt("div", null, "CodeMirror-cursors")
  250. // A visibility: hidden element used to find the size of things.
  251. d.measure = elt("div", null, "CodeMirror-measure")
  252. // When lines outside of the viewport are measured, they are drawn in this.
  253. d.lineMeasure = elt("div", null, "CodeMirror-measure")
  254. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  255. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  256. null, "position: relative; outline: none")
  257. // Moved around its parent to cover visible view.
  258. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative")
  259. // Set to the height of the document, allowing scrolling.
  260. d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
  261. d.sizerWidth = null
  262. // Behavior of elts with overflow: auto and padding is
  263. // inconsistent across browsers. This is used to ensure the
  264. // scrollable area is big enough.
  265. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
  266. // Will contain the gutters, if any.
  267. d.gutters = elt("div", null, "CodeMirror-gutters")
  268. d.lineGutter = null
  269. // Actual scrollable element.
  270. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
  271. d.scroller.setAttribute("tabIndex", "-1")
  272. // The element in which the editor lives.
  273. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
  274. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  275. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
  276. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
  277. if (place) {
  278. if (place.appendChild) { place.appendChild(d.wrapper) }
  279. else { place(d.wrapper) }
  280. }
  281. // Current rendered range (may be bigger than the view window).
  282. d.viewFrom = d.viewTo = doc.first
  283. d.reportedViewFrom = d.reportedViewTo = doc.first
  284. // Information about the rendered lines.
  285. d.view = []
  286. d.renderedView = null
  287. // Holds info about a single rendered line when it was rendered
  288. // for measurement, while not in view.
  289. d.externalMeasured = null
  290. // Empty space (in pixels) above the view
  291. d.viewOffset = 0
  292. d.lastWrapHeight = d.lastWrapWidth = 0
  293. d.updateLineNumbers = null
  294. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  295. d.scrollbarsClipped = false
  296. // Used to only resize the line number gutter when necessary (when
  297. // the amount of lines crosses a boundary that makes its width change)
  298. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  299. // Set to true when a non-horizontal-scrolling line widget is
  300. // added. As an optimization, line widget aligning is skipped when
  301. // this is false.
  302. d.alignWidgets = false
  303. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  304. // Tracks the maximum line length so that the horizontal scrollbar
  305. // can be kept static when scrolling.
  306. d.maxLine = null
  307. d.maxLineLength = 0
  308. d.maxLineChanged = false
  309. // Used for measuring wheel scrolling granularity
  310. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  311. // True when shift is held down.
  312. d.shift = false
  313. // Used to track whether anything happened since the context menu
  314. // was opened.
  315. d.selForContextMenu = null
  316. d.activeTouch = null
  317. input.init(d)
  318. }
  319. // Find the line object corresponding to the given line number.
  320. function getLine(doc, n) {
  321. n -= doc.first
  322. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  323. var chunk = doc
  324. while (!chunk.lines) {
  325. for (var i = 0;; ++i) {
  326. var child = chunk.children[i], sz = child.chunkSize()
  327. if (n < sz) { chunk = child; break }
  328. n -= sz
  329. }
  330. }
  331. return chunk.lines[n]
  332. }
  333. // Get the part of a document between two positions, as an array of
  334. // strings.
  335. function getBetween(doc, start, end) {
  336. var out = [], n = start.line
  337. doc.iter(start.line, end.line + 1, function (line) {
  338. var text = line.text
  339. if (n == end.line) { text = text.slice(0, end.ch) }
  340. if (n == start.line) { text = text.slice(start.ch) }
  341. out.push(text)
  342. ++n
  343. })
  344. return out
  345. }
  346. // Get the lines between from and to, as array of strings.
  347. function getLines(doc, from, to) {
  348. var out = []
  349. doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
  350. return out
  351. }
  352. // Update the height of a line, propagating the height change
  353. // upwards to parent nodes.
  354. function updateLineHeight(line, height) {
  355. var diff = height - line.height
  356. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
  357. }
  358. // Given a line object, find its line number by walking up through
  359. // its parent links.
  360. function lineNo(line) {
  361. if (line.parent == null) { return null }
  362. var cur = line.parent, no = indexOf(cur.lines, line)
  363. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  364. for (var i = 0;; ++i) {
  365. if (chunk.children[i] == cur) { break }
  366. no += chunk.children[i].chunkSize()
  367. }
  368. }
  369. return no + cur.first
  370. }
  371. // Find the line at the given vertical position, using the height
  372. // information in the document tree.
  373. function lineAtHeight(chunk, h) {
  374. var n = chunk.first
  375. outer: do {
  376. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  377. var child = chunk.children[i$1], ch = child.height
  378. if (h < ch) { chunk = child; continue outer }
  379. h -= ch
  380. n += child.chunkSize()
  381. }
  382. return n
  383. } while (!chunk.lines)
  384. var i = 0
  385. for (; i < chunk.lines.length; ++i) {
  386. var line = chunk.lines[i], lh = line.height
  387. if (h < lh) { break }
  388. h -= lh
  389. }
  390. return n + i
  391. }
  392. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  393. function lineNumberFor(options, i) {
  394. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  395. }
  396. // A Pos instance represents a position within the text.
  397. function Pos (line, ch) {
  398. if (!(this instanceof Pos)) { return new Pos(line, ch) }
  399. this.line = line; this.ch = ch
  400. }
  401. // Compare two positions, return 0 if they are the same, a negative
  402. // number when a is less, and a positive number otherwise.
  403. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  404. function copyPos(x) {return Pos(x.line, x.ch)}
  405. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  406. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  407. // Most of the external API clips given positions to make sure they
  408. // actually exist within the document.
  409. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  410. function clipPos(doc, pos) {
  411. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  412. var last = doc.first + doc.size - 1
  413. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  414. return clipToLen(pos, getLine(doc, pos.line).text.length)
  415. }
  416. function clipToLen(pos, linelen) {
  417. var ch = pos.ch
  418. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  419. else if (ch < 0) { return Pos(pos.line, 0) }
  420. else { return pos }
  421. }
  422. function clipPosArray(doc, array) {
  423. var out = []
  424. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
  425. return out
  426. }
  427. // Optimize some code when these features are not used.
  428. var sawReadOnlySpans = false;
  429. var sawCollapsedSpans = false;
  430. function seeReadOnlySpans() {
  431. sawReadOnlySpans = true
  432. }
  433. function seeCollapsedSpans() {
  434. sawCollapsedSpans = true
  435. }
  436. // TEXTMARKER SPANS
  437. function MarkedSpan(marker, from, to) {
  438. this.marker = marker
  439. this.from = from; this.to = to
  440. }
  441. // Search an array of spans for a span matching the given marker.
  442. function getMarkedSpanFor(spans, marker) {
  443. if (spans) { for (var i = 0; i < spans.length; ++i) {
  444. var span = spans[i]
  445. if (span.marker == marker) { return span }
  446. } }
  447. }
  448. // Remove a span from an array, returning undefined if no spans are
  449. // left (we don't store arrays for lines without spans).
  450. function removeMarkedSpan(spans, span) {
  451. var r
  452. for (var i = 0; i < spans.length; ++i)
  453. { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
  454. return r
  455. }
  456. // Add a span to a line.
  457. function addMarkedSpan(line, span) {
  458. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  459. span.marker.attachLine(line)
  460. }
  461. // Used for the algorithm that adjusts markers for a change in the
  462. // document. These functions cut an array of spans at a given
  463. // character position, returning an array of remaining chunks (or
  464. // undefined if nothing remains).
  465. function markedSpansBefore(old, startCh, isInsert) {
  466. var nw
  467. if (old) { for (var i = 0; i < old.length; ++i) {
  468. var span = old[i], marker = span.marker
  469. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  470. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  471. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  472. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
  473. }
  474. } }
  475. return nw
  476. }
  477. function markedSpansAfter(old, endCh, isInsert) {
  478. var nw
  479. if (old) { for (var i = 0; i < old.length; ++i) {
  480. var span = old[i], marker = span.marker
  481. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
  482. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  483. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  484. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  485. span.to == null ? null : span.to - endCh))
  486. }
  487. } }
  488. return nw
  489. }
  490. // Given a change object, compute the new set of marker spans that
  491. // cover the line in which the change took place. Removes spans
  492. // entirely within the change, reconnects spans belonging to the
  493. // same marker that appear on both sides of the change, and cuts off
  494. // spans partially within the change. Returns an array of span
  495. // arrays with one element for each line in (after) the change.
  496. function stretchSpansOverChange(doc, change) {
  497. if (change.full) { return null }
  498. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
  499. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
  500. if (!oldFirst && !oldLast) { return null }
  501. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
  502. // Get the spans that 'stick out' on both sides
  503. var first = markedSpansBefore(oldFirst, startCh, isInsert)
  504. var last = markedSpansAfter(oldLast, endCh, isInsert)
  505. // Next, merge those two ends
  506. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
  507. if (first) {
  508. // Fix up .to properties of first
  509. for (var i = 0; i < first.length; ++i) {
  510. var span = first[i]
  511. if (span.to == null) {
  512. var found = getMarkedSpanFor(last, span.marker)
  513. if (!found) { span.to = startCh }
  514. else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
  515. }
  516. }
  517. }
  518. if (last) {
  519. // Fix up .from in last (or move them into first in case of sameLine)
  520. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  521. var span$1 = last[i$1]
  522. if (span$1.to != null) { span$1.to += offset }
  523. if (span$1.from == null) {
  524. var found$1 = getMarkedSpanFor(first, span$1.marker)
  525. if (!found$1) {
  526. span$1.from = offset
  527. if (sameLine) { (first || (first = [])).push(span$1) }
  528. }
  529. } else {
  530. span$1.from += offset
  531. if (sameLine) { (first || (first = [])).push(span$1) }
  532. }
  533. }
  534. }
  535. // Make sure we didn't create any zero-length spans
  536. if (first) { first = clearEmptySpans(first) }
  537. if (last && last != first) { last = clearEmptySpans(last) }
  538. var newMarkers = [first]
  539. if (!sameLine) {
  540. // Fill gap with whole-line-spans
  541. var gap = change.text.length - 2, gapMarkers
  542. if (gap > 0 && first)
  543. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  544. { if (first[i$2].to == null)
  545. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
  546. for (var i$3 = 0; i$3 < gap; ++i$3)
  547. { newMarkers.push(gapMarkers) }
  548. newMarkers.push(last)
  549. }
  550. return newMarkers
  551. }
  552. // Remove spans that are empty and don't have a clearWhenEmpty
  553. // option of false.
  554. function clearEmptySpans(spans) {
  555. for (var i = 0; i < spans.length; ++i) {
  556. var span = spans[i]
  557. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  558. { spans.splice(i--, 1) }
  559. }
  560. if (!spans.length) { return null }
  561. return spans
  562. }
  563. // Used to 'clip' out readOnly ranges when making a change.
  564. function removeReadOnlyRanges(doc, from, to) {
  565. var markers = null
  566. doc.iter(from.line, to.line + 1, function (line) {
  567. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  568. var mark = line.markedSpans[i].marker
  569. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  570. { (markers || (markers = [])).push(mark) }
  571. } }
  572. })
  573. if (!markers) { return null }
  574. var parts = [{from: from, to: to}]
  575. for (var i = 0; i < markers.length; ++i) {
  576. var mk = markers[i], m = mk.find(0)
  577. for (var j = 0; j < parts.length; ++j) {
  578. var p = parts[j]
  579. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  580. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
  581. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  582. { newParts.push({from: p.from, to: m.from}) }
  583. if (dto > 0 || !mk.inclusiveRight && !dto)
  584. { newParts.push({from: m.to, to: p.to}) }
  585. parts.splice.apply(parts, newParts)
  586. j += newParts.length - 1
  587. }
  588. }
  589. return parts
  590. }
  591. // Connect or disconnect spans from a line.
  592. function detachMarkedSpans(line) {
  593. var spans = line.markedSpans
  594. if (!spans) { return }
  595. for (var i = 0; i < spans.length; ++i)
  596. { spans[i].marker.detachLine(line) }
  597. line.markedSpans = null
  598. }
  599. function attachMarkedSpans(line, spans) {
  600. if (!spans) { return }
  601. for (var i = 0; i < spans.length; ++i)
  602. { spans[i].marker.attachLine(line) }
  603. line.markedSpans = spans
  604. }
  605. // Helpers used when computing which overlapping collapsed span
  606. // counts as the larger one.
  607. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  608. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  609. // Returns a number indicating which of two overlapping collapsed
  610. // spans is larger (and thus includes the other). Falls back to
  611. // comparing ids when the spans cover exactly the same range.
  612. function compareCollapsedMarkers(a, b) {
  613. var lenDiff = a.lines.length - b.lines.length
  614. if (lenDiff != 0) { return lenDiff }
  615. var aPos = a.find(), bPos = b.find()
  616. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
  617. if (fromCmp) { return -fromCmp }
  618. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
  619. if (toCmp) { return toCmp }
  620. return b.id - a.id
  621. }
  622. // Find out whether a line ends or starts in a collapsed span. If
  623. // so, return the marker for that span.
  624. function collapsedSpanAtSide(line, start) {
  625. var sps = sawCollapsedSpans && line.markedSpans, found
  626. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  627. sp = sps[i]
  628. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  629. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  630. { found = sp.marker }
  631. } }
  632. return found
  633. }
  634. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  635. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  636. // Test whether there exists a collapsed span that partially
  637. // overlaps (covers the start or end, but not both) of a new span.
  638. // Such overlap is not allowed.
  639. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  640. var line = getLine(doc, lineNo)
  641. var sps = sawCollapsedSpans && line.markedSpans
  642. if (sps) { for (var i = 0; i < sps.length; ++i) {
  643. var sp = sps[i]
  644. if (!sp.marker.collapsed) { continue }
  645. var found = sp.marker.find(0)
  646. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  647. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  648. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  649. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  650. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  651. { return true }
  652. } }
  653. }
  654. // A visual line is a line as drawn on the screen. Folding, for
  655. // example, can cause multiple logical lines to appear on the same
  656. // visual line. This finds the start of the visual line that the
  657. // given line is part of (usually that is the line itself).
  658. function visualLine(line) {
  659. var merged
  660. while (merged = collapsedSpanAtStart(line))
  661. { line = merged.find(-1, true).line }
  662. return line
  663. }
  664. // Returns an array of logical lines that continue the visual line
  665. // started by the argument, or undefined if there are no such lines.
  666. function visualLineContinued(line) {
  667. var merged, lines
  668. while (merged = collapsedSpanAtEnd(line)) {
  669. line = merged.find(1, true).line
  670. ;(lines || (lines = [])).push(line)
  671. }
  672. return lines
  673. }
  674. // Get the line number of the start of the visual line that the
  675. // given line number is part of.
  676. function visualLineNo(doc, lineN) {
  677. var line = getLine(doc, lineN), vis = visualLine(line)
  678. if (line == vis) { return lineN }
  679. return lineNo(vis)
  680. }
  681. // Get the line number of the start of the next visual line after
  682. // the given line.
  683. function visualLineEndNo(doc, lineN) {
  684. if (lineN > doc.lastLine()) { return lineN }
  685. var line = getLine(doc, lineN), merged
  686. if (!lineIsHidden(doc, line)) { return lineN }
  687. while (merged = collapsedSpanAtEnd(line))
  688. { line = merged.find(1, true).line }
  689. return lineNo(line) + 1
  690. }
  691. // Compute whether a line is hidden. Lines count as hidden when they
  692. // are part of a visual line that starts with another line, or when
  693. // they are entirely covered by collapsed, non-widget span.
  694. function lineIsHidden(doc, line) {
  695. var sps = sawCollapsedSpans && line.markedSpans
  696. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  697. sp = sps[i]
  698. if (!sp.marker.collapsed) { continue }
  699. if (sp.from == null) { return true }
  700. if (sp.marker.widgetNode) { continue }
  701. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  702. { return true }
  703. } }
  704. }
  705. function lineIsHiddenInner(doc, line, span) {
  706. if (span.to == null) {
  707. var end = span.marker.find(1, true)
  708. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  709. }
  710. if (span.marker.inclusiveRight && span.to == line.text.length)
  711. { return true }
  712. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  713. sp = line.markedSpans[i]
  714. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  715. (sp.to == null || sp.to != span.from) &&
  716. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  717. lineIsHiddenInner(doc, line, sp)) { return true }
  718. }
  719. }
  720. // Find the height above the given line.
  721. function heightAtLine(lineObj) {
  722. lineObj = visualLine(lineObj)
  723. var h = 0, chunk = lineObj.parent
  724. for (var i = 0; i < chunk.lines.length; ++i) {
  725. var line = chunk.lines[i]
  726. if (line == lineObj) { break }
  727. else { h += line.height }
  728. }
  729. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  730. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  731. var cur = p.children[i$1]
  732. if (cur == chunk) { break }
  733. else { h += cur.height }
  734. }
  735. }
  736. return h
  737. }
  738. // Compute the character length of a line, taking into account
  739. // collapsed ranges (see markText) that might hide parts, and join
  740. // other lines onto it.
  741. function lineLength(line) {
  742. if (line.height == 0) { return 0 }
  743. var len = line.text.length, merged, cur = line
  744. while (merged = collapsedSpanAtStart(cur)) {
  745. var found = merged.find(0, true)
  746. cur = found.from.line
  747. len += found.from.ch - found.to.ch
  748. }
  749. cur = line
  750. while (merged = collapsedSpanAtEnd(cur)) {
  751. var found$1 = merged.find(0, true)
  752. len -= cur.text.length - found$1.from.ch
  753. cur = found$1.to.line
  754. len += cur.text.length - found$1.to.ch
  755. }
  756. return len
  757. }
  758. // Find the longest line in the document.
  759. function findMaxLine(cm) {
  760. var d = cm.display, doc = cm.doc
  761. d.maxLine = getLine(doc, doc.first)
  762. d.maxLineLength = lineLength(d.maxLine)
  763. d.maxLineChanged = true
  764. doc.iter(function (line) {
  765. var len = lineLength(line)
  766. if (len > d.maxLineLength) {
  767. d.maxLineLength = len
  768. d.maxLine = line
  769. }
  770. })
  771. }
  772. // BIDI HELPERS
  773. function iterateBidiSections(order, from, to, f) {
  774. if (!order) { return f(from, to, "ltr") }
  775. var found = false
  776. for (var i = 0; i < order.length; ++i) {
  777. var part = order[i]
  778. if (part.from < to && part.to > from || from == to && part.to == from) {
  779. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr")
  780. found = true
  781. }
  782. }
  783. if (!found) { f(from, to, "ltr") }
  784. }
  785. function bidiLeft(part) { return part.level % 2 ? part.to : part.from }
  786. function bidiRight(part) { return part.level % 2 ? part.from : part.to }
  787. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0 }
  788. function lineRight(line) {
  789. var order = getOrder(line)
  790. if (!order) { return line.text.length }
  791. return bidiRight(lst(order))
  792. }
  793. function compareBidiLevel(order, a, b) {
  794. var linedir = order[0].level
  795. if (a == linedir) { return true }
  796. if (b == linedir) { return false }
  797. return a < b
  798. }
  799. var bidiOther = null
  800. function getBidiPartAt(order, pos) {
  801. var found
  802. bidiOther = null
  803. for (var i = 0; i < order.length; ++i) {
  804. var cur = order[i]
  805. if (cur.from < pos && cur.to > pos) { return i }
  806. if ((cur.from == pos || cur.to == pos)) {
  807. if (found == null) {
  808. found = i
  809. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  810. if (cur.from != cur.to) { bidiOther = found }
  811. return i
  812. } else {
  813. if (cur.from != cur.to) { bidiOther = i }
  814. return found
  815. }
  816. }
  817. }
  818. return found
  819. }
  820. function moveInLine(line, pos, dir, byUnit) {
  821. if (!byUnit) { return pos + dir }
  822. do { pos += dir }
  823. while (pos > 0 && isExtendingChar(line.text.charAt(pos)))
  824. return pos
  825. }
  826. // This is needed in order to move 'visually' through bi-directional
  827. // text -- i.e., pressing left should make the cursor go left, even
  828. // when in RTL text. The tricky part is the 'jumps', where RTL and
  829. // LTR text touch each other. This often requires the cursor offset
  830. // to move more than one unit, in order to visually move one unit.
  831. function moveVisually(line, start, dir, byUnit) {
  832. var bidi = getOrder(line)
  833. if (!bidi) { return moveLogically(line, start, dir, byUnit) }
  834. var pos = getBidiPartAt(bidi, start), part = bidi[pos]
  835. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit)
  836. for (;;) {
  837. if (target > part.from && target < part.to) { return target }
  838. if (target == part.from || target == part.to) {
  839. if (getBidiPartAt(bidi, target) == pos) { return target }
  840. part = bidi[pos += dir]
  841. return (dir > 0) == part.level % 2 ? part.to : part.from
  842. } else {
  843. part = bidi[pos += dir]
  844. if (!part) { return null }
  845. if ((dir > 0) == part.level % 2)
  846. { target = moveInLine(line, part.to, -1, byUnit) }
  847. else
  848. { target = moveInLine(line, part.from, 1, byUnit) }
  849. }
  850. }
  851. }
  852. function moveLogically(line, start, dir, byUnit) {
  853. var target = start + dir
  854. if (byUnit) { while (target > 0 && isExtendingChar(line.text.charAt(target))) { target += dir } }
  855. return target < 0 || target > line.text.length ? null : target
  856. }
  857. // Bidirectional ordering algorithm
  858. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  859. // that this (partially) implements.
  860. // One-char codes used for character types:
  861. // L (L): Left-to-Right
  862. // R (R): Right-to-Left
  863. // r (AL): Right-to-Left Arabic
  864. // 1 (EN): European Number
  865. // + (ES): European Number Separator
  866. // % (ET): European Number Terminator
  867. // n (AN): Arabic Number
  868. // , (CS): Common Number Separator
  869. // m (NSM): Non-Spacing Mark
  870. // b (BN): Boundary Neutral
  871. // s (B): Paragraph Separator
  872. // t (S): Segment Separator
  873. // w (WS): Whitespace
  874. // N (ON): Other Neutrals
  875. // Returns null if characters are ordered as they appear
  876. // (left-to-right), or an array of sections ({from, to, level}
  877. // objects) in the order in which they occur visually.
  878. var bidiOrdering = (function() {
  879. // Character types for codepoints 0 to 0xff
  880. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
  881. // Character types for codepoints 0x600 to 0x6f9
  882. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"
  883. function charType(code) {
  884. if (code <= 0xf7) { return lowTypes.charAt(code) }
  885. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  886. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  887. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  888. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  889. else if (code == 0x200c) { return "b" }
  890. else { return "L" }
  891. }
  892. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  893. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
  894. // Browsers seem to always treat the boundaries of block elements as being L.
  895. var outerType = "L"
  896. function BidiSpan(level, from, to) {
  897. this.level = level
  898. this.from = from; this.to = to
  899. }
  900. return function(str) {
  901. if (!bidiRE.test(str)) { return false }
  902. var len = str.length, types = []
  903. for (var i = 0; i < len; ++i)
  904. { types.push(charType(str.charCodeAt(i))) }
  905. // W1. Examine each non-spacing mark (NSM) in the level run, and
  906. // change the type of the NSM to the type of the previous
  907. // character. If the NSM is at the start of the level run, it will
  908. // get the type of sor.
  909. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  910. var type = types[i$1]
  911. if (type == "m") { types[i$1] = prev }
  912. else { prev = type }
  913. }
  914. // W2. Search backwards from each instance of a European number
  915. // until the first strong type (R, L, AL, or sor) is found. If an
  916. // AL is found, change the type of the European number to Arabic
  917. // number.
  918. // W3. Change all ALs to R.
  919. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  920. var type$1 = types[i$2]
  921. if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
  922. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
  923. }
  924. // W4. A single European separator between two European numbers
  925. // changes to a European number. A single common separator between
  926. // two numbers of the same type changes to that type.
  927. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  928. var type$2 = types[i$3]
  929. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
  930. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  931. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
  932. prev$1 = type$2
  933. }
  934. // W5. A sequence of European terminators adjacent to European
  935. // numbers changes to all European numbers.
  936. // W6. Otherwise, separators and terminators change to Other
  937. // Neutral.
  938. for (var i$4 = 0; i$4 < len; ++i$4) {
  939. var type$3 = types[i$4]
  940. if (type$3 == ",") { types[i$4] = "N" }
  941. else if (type$3 == "%") {
  942. var end = (void 0)
  943. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  944. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
  945. for (var j = i$4; j < end; ++j) { types[j] = replace }
  946. i$4 = end - 1
  947. }
  948. }
  949. // W7. Search backwards from each instance of a European number
  950. // until the first strong type (R, L, or sor) is found. If an L is
  951. // found, then change the type of the European number to L.
  952. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  953. var type$4 = types[i$5]
  954. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
  955. else if (isStrong.test(type$4)) { cur$1 = type$4 }
  956. }
  957. // N1. A sequence of neutrals takes the direction of the
  958. // surrounding strong text if the text on both sides has the same
  959. // direction. European and Arabic numbers act as if they were R in
  960. // terms of their influence on neutrals. Start-of-level-run (sor)
  961. // and end-of-level-run (eor) are used at level run boundaries.
  962. // N2. Any remaining neutrals take the embedding direction.
  963. for (var i$6 = 0; i$6 < len; ++i$6) {
  964. if (isNeutral.test(types[i$6])) {
  965. var end$1 = (void 0)
  966. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  967. var before = (i$6 ? types[i$6-1] : outerType) == "L"
  968. var after = (end$1 < len ? types[end$1] : outerType) == "L"
  969. var replace$1 = before || after ? "L" : "R"
  970. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
  971. i$6 = end$1 - 1
  972. }
  973. }
  974. // Here we depart from the documented algorithm, in order to avoid
  975. // building up an actual levels array. Since there are only three
  976. // levels (0, 1, 2) in an implementation that doesn't take
  977. // explicit embedding into account, we can build up the order on
  978. // the fly, without following the level-based algorithm.
  979. var order = [], m
  980. for (var i$7 = 0; i$7 < len;) {
  981. if (countsAsLeft.test(types[i$7])) {
  982. var start = i$7
  983. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  984. order.push(new BidiSpan(0, start, i$7))
  985. } else {
  986. var pos = i$7, at = order.length
  987. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  988. for (var j$2 = pos; j$2 < i$7;) {
  989. if (countsAsNum.test(types[j$2])) {
  990. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
  991. var nstart = j$2
  992. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  993. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  994. pos = j$2
  995. } else { ++j$2 }
  996. }
  997. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
  998. }
  999. }
  1000. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  1001. order[0].from = m[0].length
  1002. order.unshift(new BidiSpan(0, 0, m[0].length))
  1003. }
  1004. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  1005. lst(order).to -= m[0].length
  1006. order.push(new BidiSpan(0, len - m[0].length, len))
  1007. }
  1008. if (order[0].level == 2)
  1009. { order.unshift(new BidiSpan(1, order[0].to, order[0].to)) }
  1010. if (order[0].level != lst(order).level)
  1011. { order.push(new BidiSpan(order[0].level, len, len)) }
  1012. return order
  1013. }
  1014. })()
  1015. // Get the bidi ordering for the given line (and cache it). Returns
  1016. // false for lines that are fully left-to-right, and an array of
  1017. // BidiSpan objects otherwise.
  1018. function getOrder(line) {
  1019. var order = line.order
  1020. if (order == null) { order = line.order = bidiOrdering(line.text) }
  1021. return order
  1022. }
  1023. // EVENT HANDLING
  1024. // Lightweight event framework. on/off also work on DOM nodes,
  1025. // registering native DOM handlers.
  1026. var noHandlers = []
  1027. var on = function(emitter, type, f) {
  1028. if (emitter.addEventListener) {
  1029. emitter.addEventListener(type, f, false)
  1030. } else if (emitter.attachEvent) {
  1031. emitter.attachEvent("on" + type, f)
  1032. } else {
  1033. var map = emitter._handlers || (emitter._handlers = {})
  1034. map[type] = (map[type] || noHandlers).concat(f)
  1035. }
  1036. }
  1037. function getHandlers(emitter, type) {
  1038. return emitter._handlers && emitter._handlers[type] || noHandlers
  1039. }
  1040. function off(emitter, type, f) {
  1041. if (emitter.removeEventListener) {
  1042. emitter.removeEventListener(type, f, false)
  1043. } else if (emitter.detachEvent) {
  1044. emitter.detachEvent("on" + type, f)
  1045. } else {
  1046. var map = emitter._handlers, arr = map && map[type]
  1047. if (arr) {
  1048. var index = indexOf(arr, f)
  1049. if (index > -1)
  1050. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
  1051. }
  1052. }
  1053. }
  1054. function signal(emitter, type /*, values...*/) {
  1055. var handlers = getHandlers(emitter, type)
  1056. if (!handlers.length) { return }
  1057. var args = Array.prototype.slice.call(arguments, 2)
  1058. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
  1059. }
  1060. // The DOM events that CodeMirror handles can be overridden by
  1061. // registering a (non-DOM) handler on the editor for the event name,
  1062. // and preventDefault-ing the event in that handler.
  1063. function signalDOMEvent(cm, e, override) {
  1064. if (typeof e == "string")
  1065. { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
  1066. signal(cm, override || e.type, cm, e)
  1067. return e_defaultPrevented(e) || e.codemirrorIgnore
  1068. }
  1069. function signalCursorActivity(cm) {
  1070. var arr = cm._handlers && cm._handlers.cursorActivity
  1071. if (!arr) { return }
  1072. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  1073. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1074. { set.push(arr[i]) } }
  1075. }
  1076. function hasHandler(emitter, type) {
  1077. return getHandlers(emitter, type).length > 0
  1078. }
  1079. // Add on and off methods to a constructor's prototype, to make
  1080. // registering events on such objects more convenient.
  1081. function eventMixin(ctor) {
  1082. ctor.prototype.on = function(type, f) {on(this, type, f)}
  1083. ctor.prototype.off = function(type, f) {off(this, type, f)}
  1084. }
  1085. // Due to the fact that we still support jurassic IE versions, some
  1086. // compatibility wrappers are needed.
  1087. function e_preventDefault(e) {
  1088. if (e.preventDefault) { e.preventDefault() }
  1089. else { e.returnValue = false }
  1090. }
  1091. function e_stopPropagation(e) {
  1092. if (e.stopPropagation) { e.stopPropagation() }
  1093. else { e.cancelBubble = true }
  1094. }
  1095. function e_defaultPrevented(e) {
  1096. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1097. }
  1098. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
  1099. function e_target(e) {return e.target || e.srcElement}
  1100. function e_button(e) {
  1101. var b = e.which
  1102. if (b == null) {
  1103. if (e.button & 1) { b = 1 }
  1104. else if (e.button & 2) { b = 3 }
  1105. else if (e.button & 4) { b = 2 }
  1106. }
  1107. if (mac && e.ctrlKey && b == 1) { b = 3 }
  1108. return b
  1109. }
  1110. // Detect drag-and-drop
  1111. var dragAndDrop = function() {
  1112. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1113. // couldn't get it to work yet.
  1114. if (ie && ie_version < 9) { return false }
  1115. var div = elt('div')
  1116. return "draggable" in div || "dragDrop" in div
  1117. }()
  1118. var zwspSupported
  1119. function zeroWidthElement(measure) {
  1120. if (zwspSupported == null) {
  1121. var test = elt("span", "\u200b")
  1122. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
  1123. if (measure.firstChild.offsetHeight != 0)
  1124. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
  1125. }
  1126. var node = zwspSupported ? elt("span", "\u200b") :
  1127. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  1128. node.setAttribute("cm-text", "")
  1129. return node
  1130. }
  1131. // Feature-detect IE's crummy client rect reporting for bidi text
  1132. var badBidiRects
  1133. function hasBadBidiRects(measure) {
  1134. if (badBidiRects != null) { return badBidiRects }
  1135. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  1136. var r0 = range(txt, 0, 1).getBoundingClientRect()
  1137. var r1 = range(txt, 1, 2).getBoundingClientRect()
  1138. removeChildren(measure)
  1139. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1140. return badBidiRects = (r1.right - r0.right < 3)
  1141. }
  1142. // See if "".split is the broken IE version, if so, provide an
  1143. // alternative way to split lines.
  1144. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1145. var pos = 0, result = [], l = string.length
  1146. while (pos <= l) {
  1147. var nl = string.indexOf("\n", pos)
  1148. if (nl == -1) { nl = string.length }
  1149. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
  1150. var rt = line.indexOf("\r")
  1151. if (rt != -1) {
  1152. result.push(line.slice(0, rt))
  1153. pos += rt + 1
  1154. } else {
  1155. result.push(line)
  1156. pos = nl + 1
  1157. }
  1158. }
  1159. return result
  1160. } : function (string) { return string.split(/\r\n?|\n/); }
  1161. var hasSelection = window.getSelection ? function (te) {
  1162. try { return te.selectionStart != te.selectionEnd }
  1163. catch(e) { return false }
  1164. } : function (te) {
  1165. var range
  1166. try {range = te.ownerDocument.selection.createRange()}
  1167. catch(e) {}
  1168. if (!range || range.parentElement() != te) { return false }
  1169. return range.compareEndPoints("StartToEnd", range) != 0
  1170. }
  1171. var hasCopyEvent = (function () {
  1172. var e = elt("div")
  1173. if ("oncopy" in e) { return true }
  1174. e.setAttribute("oncopy", "return;")
  1175. return typeof e.oncopy == "function"
  1176. })()
  1177. var badZoomedRects = null
  1178. function hasBadZoomedRects(measure) {
  1179. if (badZoomedRects != null) { return badZoomedRects }
  1180. var node = removeChildrenAndAdd(measure, elt("span", "x"))
  1181. var normal = node.getBoundingClientRect()
  1182. var fromRange = range(node, 0, 1).getBoundingClientRect()
  1183. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1184. }
  1185. var modes = {};
  1186. var mimeModes = {};
  1187. // Extra arguments are stored as the mode's dependencies, which is
  1188. // used by (legacy) mechanisms like loadmode.js to automatically
  1189. // load a mode. (Preferred mechanism is the require/define calls.)
  1190. function defineMode(name, mode) {
  1191. if (arguments.length > 2)
  1192. { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
  1193. modes[name] = mode
  1194. }
  1195. function defineMIME(mime, spec) {
  1196. mimeModes[mime] = spec
  1197. }
  1198. // Given a MIME type, a {name, ...options} config object, or a name
  1199. // string, return a mode config object.
  1200. function resolveMode(spec) {
  1201. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1202. spec = mimeModes[spec]
  1203. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1204. var found = mimeModes[spec.name]
  1205. if (typeof found == "string") { found = {name: found} }
  1206. spec = createObj(found, spec)
  1207. spec.name = found.name
  1208. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1209. return resolveMode("application/xml")
  1210. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1211. return resolveMode("application/json")
  1212. }
  1213. if (typeof spec == "string") { return {name: spec} }
  1214. else { return spec || {name: "null"} }
  1215. }
  1216. // Given a mode spec (anything that resolveMode accepts), find and
  1217. // initialize an actual mode object.
  1218. function getMode(options, spec) {
  1219. spec = resolveMode(spec)
  1220. var mfactory = modes[spec.name]
  1221. if (!mfactory) { return getMode(options, "text/plain") }
  1222. var modeObj = mfactory(options, spec)
  1223. if (modeExtensions.hasOwnProperty(spec.name)) {
  1224. var exts = modeExtensions[spec.name]
  1225. for (var prop in exts) {
  1226. if (!exts.hasOwnProperty(prop)) { continue }
  1227. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
  1228. modeObj[prop] = exts[prop]
  1229. }
  1230. }
  1231. modeObj.name = spec.name
  1232. if (spec.helperType) { modeObj.helperType = spec.helperType }
  1233. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1234. { modeObj[prop$1] = spec.modeProps[prop$1] } }
  1235. return modeObj
  1236. }
  1237. // This can be used to attach properties to mode objects from
  1238. // outside the actual mode definition.
  1239. var modeExtensions = {}
  1240. function extendMode(mode, properties) {
  1241. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  1242. copyObj(properties, exts)
  1243. }
  1244. function copyState(mode, state) {
  1245. if (state === true) { return state }
  1246. if (mode.copyState) { return mode.copyState(state) }
  1247. var nstate = {}
  1248. for (var n in state) {
  1249. var val = state[n]
  1250. if (val instanceof Array) { val = val.concat([]) }
  1251. nstate[n] = val
  1252. }
  1253. return nstate
  1254. }
  1255. // Given a mode and a state (for that mode), find the inner mode and
  1256. // state at the position that the state refers to.
  1257. function innerMode(mode, state) {
  1258. var info
  1259. while (mode.innerMode) {
  1260. info = mode.innerMode(state)
  1261. if (!info || info.mode == mode) { break }
  1262. state = info.state
  1263. mode = info.mode
  1264. }
  1265. return info || {mode: mode, state: state}
  1266. }
  1267. function startState(mode, a1, a2) {
  1268. return mode.startState ? mode.startState(a1, a2) : true
  1269. }
  1270. // STRING STREAM
  1271. // Fed to the mode parsers, provides helper functions to make
  1272. // parsers more succinct.
  1273. var StringStream = function(string, tabSize) {
  1274. this.pos = this.start = 0
  1275. this.string = string
  1276. this.tabSize = tabSize || 8
  1277. this.lastColumnPos = this.lastColumnValue = 0
  1278. this.lineStart = 0
  1279. }
  1280. StringStream.prototype = {
  1281. eol: function() {return this.pos >= this.string.length},
  1282. sol: function() {return this.pos == this.lineStart},
  1283. peek: function() {return this.string.charAt(this.pos) || undefined},
  1284. next: function() {
  1285. if (this.pos < this.string.length)
  1286. { return this.string.charAt(this.pos++) }
  1287. },
  1288. eat: function(match) {
  1289. var ch = this.string.charAt(this.pos)
  1290. var ok
  1291. if (typeof match == "string") { ok = ch == match }
  1292. else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
  1293. if (ok) {++this.pos; return ch}
  1294. },
  1295. eatWhile: function(match) {
  1296. var start = this.pos
  1297. while (this.eat(match)){}
  1298. return this.pos > start
  1299. },
  1300. eatSpace: function() {
  1301. var this$1 = this;
  1302. var start = this.pos
  1303. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
  1304. return this.pos > start
  1305. },
  1306. skipToEnd: function() {this.pos = this.string.length},
  1307. skipTo: function(ch) {
  1308. var found = this.string.indexOf(ch, this.pos)
  1309. if (found > -1) {this.pos = found; return true}
  1310. },
  1311. backUp: function(n) {this.pos -= n},
  1312. column: function() {
  1313. if (this.lastColumnPos < this.start) {
  1314. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1315. this.lastColumnPos = this.start
  1316. }
  1317. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1318. },
  1319. indentation: function() {
  1320. return countColumn(this.string, null, this.tabSize) -
  1321. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1322. },
  1323. match: function(pattern, consume, caseInsensitive) {
  1324. if (typeof pattern == "string") {
  1325. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
  1326. var substr = this.string.substr(this.pos, pattern.length)
  1327. if (cased(substr) == cased(pattern)) {
  1328. if (consume !== false) { this.pos += pattern.length }
  1329. return true
  1330. }
  1331. } else {
  1332. var match = this.string.slice(this.pos).match(pattern)
  1333. if (match && match.index > 0) { return null }
  1334. if (match && consume !== false) { this.pos += match[0].length }
  1335. return match
  1336. }
  1337. },
  1338. current: function(){return this.string.slice(this.start, this.pos)},
  1339. hideFirstChars: function(n, inner) {
  1340. this.lineStart += n
  1341. try { return inner() }
  1342. finally { this.lineStart -= n }
  1343. }
  1344. }
  1345. // Compute a style array (an array starting with a mode generation
  1346. // -- for invalidation -- followed by pairs of end positions and
  1347. // style strings), which is used to highlight the tokens on the
  1348. // line.
  1349. function highlightLine(cm, line, state, forceToEnd) {
  1350. // A styles array always starts with a number identifying the
  1351. // mode/overlays that it is based on (for easy invalidation).
  1352. var st = [cm.state.modeGen], lineClasses = {}
  1353. // Compute the base array of styles
  1354. runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); },
  1355. lineClasses, forceToEnd)
  1356. // Run overlays, adjust style array.
  1357. var loop = function ( o ) {
  1358. var overlay = cm.state.overlays[o], i = 1, at = 0
  1359. runMode(cm, line.text, overlay.mode, true, function (end, style) {
  1360. var start = i
  1361. // Ensure there's a token end at the current position, and that i points at it
  1362. while (at < end) {
  1363. var i_end = st[i]
  1364. if (i_end > end)
  1365. { st.splice(i, 1, end, st[i+1], i_end) }
  1366. i += 2
  1367. at = Math.min(end, i_end)
  1368. }
  1369. if (!style) { return }
  1370. if (overlay.opaque) {
  1371. st.splice(start, i - start, end, "overlay " + style)
  1372. i = start + 2
  1373. } else {
  1374. for (; start < i; start += 2) {
  1375. var cur = st[start+1]
  1376. st[start+1] = (cur ? cur + " " : "") + "overlay " + style
  1377. }
  1378. }
  1379. }, lineClasses)
  1380. };
  1381. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1382. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1383. }
  1384. function getLineStyles(cm, line, updateFrontier) {
  1385. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1386. var state = getStateBefore(cm, lineNo(line))
  1387. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state)
  1388. line.stateAfter = state
  1389. line.styles = result.styles
  1390. if (result.classes) { line.styleClasses = result.classes }
  1391. else if (line.styleClasses) { line.styleClasses = null }
  1392. if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ }
  1393. }
  1394. return line.styles
  1395. }
  1396. function getStateBefore(cm, n, precise) {
  1397. var doc = cm.doc, display = cm.display
  1398. if (!doc.mode.startState) { return true }
  1399. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter
  1400. if (!state) { state = startState(doc.mode) }
  1401. else { state = copyState(doc.mode, state) }
  1402. doc.iter(pos, n, function (line) {
  1403. processLine(cm, line.text, state)
  1404. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo
  1405. line.stateAfter = save ? copyState(doc.mode, state) : null
  1406. ++pos
  1407. })
  1408. if (precise) { doc.frontier = pos }
  1409. return state
  1410. }
  1411. // Lightweight form of highlight -- proceed over this line and
  1412. // update state, but don't save a style array. Used for lines that
  1413. // aren't currently visible.
  1414. function processLine(cm, text, state, startAt) {
  1415. var mode = cm.doc.mode
  1416. var stream = new StringStream(text, cm.options.tabSize)
  1417. stream.start = stream.pos = startAt || 0
  1418. if (text == "") { callBlankLine(mode, state) }
  1419. while (!stream.eol()) {
  1420. readToken(mode, stream, state)
  1421. stream.start = stream.pos
  1422. }
  1423. }
  1424. function callBlankLine(mode, state) {
  1425. if (mode.blankLine) { return mode.blankLine(state) }
  1426. if (!mode.innerMode) { return }
  1427. var inner = innerMode(mode, state)
  1428. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1429. }
  1430. function readToken(mode, stream, state, inner) {
  1431. for (var i = 0; i < 10; i++) {
  1432. if (inner) { inner[0] = innerMode(mode, state).mode }
  1433. var style = mode.token(stream, state)
  1434. if (stream.pos > stream.start) { return style }
  1435. }
  1436. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1437. }
  1438. // Utility for getTokenAt and getLineTokens
  1439. function takeToken(cm, pos, precise, asArray) {
  1440. var getObj = function (copy) { return ({
  1441. start: stream.start, end: stream.pos,
  1442. string: stream.current(),
  1443. type: style || null,
  1444. state: copy ? copyState(doc.mode, state) : state
  1445. }); }
  1446. var doc = cm.doc, mode = doc.mode, style
  1447. pos = clipPos(doc, pos)
  1448. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise)
  1449. var stream = new StringStream(line.text, cm.options.tabSize), tokens
  1450. if (asArray) { tokens = [] }
  1451. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1452. stream.start = stream.pos
  1453. style = readToken(mode, stream, state)
  1454. if (asArray) { tokens.push(getObj(true)) }
  1455. }
  1456. return asArray ? tokens : getObj()
  1457. }
  1458. function extractLineClasses(type, output) {
  1459. if (type) { for (;;) {
  1460. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1461. if (!lineClass) { break }
  1462. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1463. var prop = lineClass[1] ? "bgClass" : "textClass"
  1464. if (output[prop] == null)
  1465. { output[prop] = lineClass[2] }
  1466. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1467. { output[prop] += " " + lineClass[2] }
  1468. } }
  1469. return type
  1470. }
  1471. // Run the given mode's parser over a line, calling f for each token.
  1472. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  1473. var flattenSpans = mode.flattenSpans
  1474. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
  1475. var curStart = 0, curStyle = null
  1476. var stream = new StringStream(text, cm.options.tabSize), style
  1477. var inner = cm.options.addModeClass && [null]
  1478. if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses) }
  1479. while (!stream.eol()) {
  1480. if (stream.pos > cm.options.maxHighlightLength) {
  1481. flattenSpans = false
  1482. if (forceToEnd) { processLine(cm, text, state, stream.pos) }
  1483. stream.pos = text.length
  1484. style = null
  1485. } else {
  1486. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses)
  1487. }
  1488. if (inner) {
  1489. var mName = inner[0].name
  1490. if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
  1491. }
  1492. if (!flattenSpans || curStyle != style) {
  1493. while (curStart < stream.start) {
  1494. curStart = Math.min(stream.start, curStart + 5000)
  1495. f(curStart, curStyle)
  1496. }
  1497. curStyle = style
  1498. }
  1499. stream.start = stream.pos
  1500. }
  1501. while (curStart < stream.pos) {
  1502. // Webkit seems to refuse to render text nodes longer than 57444
  1503. // characters, and returns inaccurate measurements in nodes
  1504. // starting around 5000 chars.
  1505. var pos = Math.min(stream.pos, curStart + 5000)
  1506. f(pos, curStyle)
  1507. curStart = pos
  1508. }
  1509. }
  1510. // Finds the line to start with when starting a parse. Tries to
  1511. // find a line with a stateAfter, so that it can start with a
  1512. // valid state. If that fails, it returns the line with the
  1513. // smallest indentation, which tends to need the least context to
  1514. // parse correctly.
  1515. function findStartLine(cm, n, precise) {
  1516. var minindent, minline, doc = cm.doc
  1517. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1518. for (var search = n; search > lim; --search) {
  1519. if (search <= doc.first) { return doc.first }
  1520. var line = getLine(doc, search - 1)
  1521. if (line.stateAfter && (!precise || search <= doc.frontier)) { return search }
  1522. var indented = countColumn(line.text, null, cm.options.tabSize)
  1523. if (minline == null || minindent > indented) {
  1524. minline = search - 1
  1525. minindent = indented
  1526. }
  1527. }
  1528. return minline
  1529. }
  1530. // LINE DATA STRUCTURE
  1531. // Line objects. These hold state related to a line, including
  1532. // highlighting info (the styles array).
  1533. function Line(text, markedSpans, estimateHeight) {
  1534. this.text = text
  1535. attachMarkedSpans(this, markedSpans)
  1536. this.height = estimateHeight ? estimateHeight(this) : 1
  1537. }
  1538. eventMixin(Line)
  1539. Line.prototype.lineNo = function() { return lineNo(this) }
  1540. // Change the content (text, markers) of a line. Automatically
  1541. // invalidates cached information and tries to re-estimate the
  1542. // line's height.
  1543. function updateLine(line, text, markedSpans, estimateHeight) {
  1544. line.text = text
  1545. if (line.stateAfter) { line.stateAfter = null }
  1546. if (line.styles) { line.styles = null }
  1547. if (line.order != null) { line.order = null }
  1548. detachMarkedSpans(line)
  1549. attachMarkedSpans(line, markedSpans)
  1550. var estHeight = estimateHeight ? estimateHeight(line) : 1
  1551. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  1552. }
  1553. // Detach a line from the document tree and its markers.
  1554. function cleanUpLine(line) {
  1555. line.parent = null
  1556. detachMarkedSpans(line)
  1557. }
  1558. // Convert a style as returned by a mode (either null, or a string
  1559. // containing one or more styles) to a CSS style. This is cached,
  1560. // and also looks for line-wide styles.
  1561. var styleToClassCache = {};
  1562. var styleToClassCacheWithMode = {};
  1563. function interpretTokenStyle(style, options) {
  1564. if (!style || /^\s*$/.test(style)) { return null }
  1565. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  1566. return cache[style] ||
  1567. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1568. }
  1569. // Render the DOM representation of the text of a line. Also builds
  1570. // up a 'line map', which points at the DOM nodes that represent
  1571. // specific stretches of text, and is used by the measuring code.
  1572. // The returned object contains the DOM node, this map, and
  1573. // information about line-wide styles that were set by the mode.
  1574. function buildLineContent(cm, lineView) {
  1575. // The padding-right forces the element to have a 'border', which
  1576. // is needed on Webkit to be able to get line-level bounding
  1577. // rectangles for it (in measureChar).
  1578. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null)
  1579. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  1580. col: 0, pos: 0, cm: cm,
  1581. trailingSpace: false,
  1582. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
  1583. // hide from accessibility tree
  1584. content.setAttribute("role", "presentation")
  1585. builder.pre.setAttribute("role", "presentation")
  1586. lineView.measure = {}
  1587. // Iterate over the logical lines that make up this visual line.
  1588. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1589. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0)
  1590. builder.pos = 0
  1591. builder.addToken = buildToken
  1592. // Optionally wire in some hacks into the token-rendering
  1593. // algorithm, to deal with browser quirks.
  1594. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  1595. { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
  1596. builder.map = []
  1597. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  1598. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  1599. if (line.styleClasses) {
  1600. if (line.styleClasses.bgClass)
  1601. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
  1602. if (line.styleClasses.textClass)
  1603. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
  1604. }
  1605. // Ensure at least a single node is present, for measuring.
  1606. if (builder.map.length == 0)
  1607. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
  1608. // Store the map and a cache object for the current logical line
  1609. if (i == 0) {
  1610. lineView.measure.map = builder.map
  1611. lineView.measure.cache = {}
  1612. } else {
  1613. ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1614. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  1615. }
  1616. }
  1617. // See issue #2901
  1618. if (webkit) {
  1619. var last = builder.content.lastChild
  1620. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1621. { builder.content.className = "cm-tab-wrap-hack" }
  1622. }
  1623. signal(cm, "renderLine", cm, lineView.line, builder.pre)
  1624. if (builder.pre.className)
  1625. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
  1626. return builder
  1627. }
  1628. function defaultSpecialCharPlaceholder(ch) {
  1629. var token = elt("span", "\u2022", "cm-invalidchar")
  1630. token.title = "\\u" + ch.charCodeAt(0).toString(16)
  1631. token.setAttribute("aria-label", token.title)
  1632. return token
  1633. }
  1634. // Build up the DOM representation for a single token, and add it to
  1635. // the line map. Takes care to render special characters separately.
  1636. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1637. if (!text) { return }
  1638. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  1639. var special = builder.cm.state.specialChars, mustWrap = false
  1640. var content
  1641. if (!special.test(text)) {
  1642. builder.col += text.length
  1643. content = document.createTextNode(displayText)
  1644. builder.map.push(builder.pos, builder.pos + text.length, content)
  1645. if (ie && ie_version < 9) { mustWrap = true }
  1646. builder.pos += text.length
  1647. } else {
  1648. content = document.createDocumentFragment()
  1649. var pos = 0
  1650. while (true) {
  1651. special.lastIndex = pos
  1652. var m = special.exec(text)
  1653. var skipped = m ? m.index - pos : text.length - pos
  1654. if (skipped) {
  1655. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  1656. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
  1657. else { content.appendChild(txt) }
  1658. builder.map.push(builder.pos, builder.pos + skipped, txt)
  1659. builder.col += skipped
  1660. builder.pos += skipped
  1661. }
  1662. if (!m) { break }
  1663. pos += skipped + 1
  1664. var txt$1 = (void 0)
  1665. if (m[0] == "\t") {
  1666. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
  1667. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
  1668. txt$1.setAttribute("role", "presentation")
  1669. txt$1.setAttribute("cm-text", "\t")
  1670. builder.col += tabWidth
  1671. } else if (m[0] == "\r" || m[0] == "\n") {
  1672. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
  1673. txt$1.setAttribute("cm-text", m[0])
  1674. builder.col += 1
  1675. } else {
  1676. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  1677. txt$1.setAttribute("cm-text", m[0])
  1678. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
  1679. else { content.appendChild(txt$1) }
  1680. builder.col += 1
  1681. }
  1682. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  1683. builder.pos++
  1684. }
  1685. }
  1686. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  1687. if (style || startStyle || endStyle || mustWrap || css) {
  1688. var fullStyle = style || ""
  1689. if (startStyle) { fullStyle += startStyle }
  1690. if (endStyle) { fullStyle += endStyle }
  1691. var token = elt("span", [content], fullStyle, css)
  1692. if (title) { token.title = title }
  1693. return builder.content.appendChild(token)
  1694. }
  1695. builder.content.appendChild(content)
  1696. }
  1697. function splitSpaces(text, trailingBefore) {
  1698. if (text.length > 1 && !/ /.test(text)) { return text }
  1699. var spaceBefore = trailingBefore, result = ""
  1700. for (var i = 0; i < text.length; i++) {
  1701. var ch = text.charAt(i)
  1702. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1703. { ch = "\u00a0" }
  1704. result += ch
  1705. spaceBefore = ch == " "
  1706. }
  1707. return result
  1708. }
  1709. // Work around nonsense dimensions being reported for stretches of
  1710. // right-to-left text.
  1711. function buildTokenBadBidi(inner, order) {
  1712. return function (builder, text, style, startStyle, endStyle, title, css) {
  1713. style = style ? style + " cm-force-border" : "cm-force-border"
  1714. var start = builder.pos, end = start + text.length
  1715. for (;;) {
  1716. // Find the part that overlaps with the start of this text
  1717. var part = (void 0)
  1718. for (var i = 0; i < order.length; i++) {
  1719. part = order[i]
  1720. if (part.to > start && part.from <= start) { break }
  1721. }
  1722. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1723. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
  1724. startStyle = null
  1725. text = text.slice(part.to - start)
  1726. start = part.to
  1727. }
  1728. }
  1729. }
  1730. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1731. var widget = !ignoreWidget && marker.widgetNode
  1732. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
  1733. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1734. if (!widget)
  1735. { widget = builder.content.appendChild(document.createElement("span")) }
  1736. widget.setAttribute("cm-marker", marker.id)
  1737. }
  1738. if (widget) {
  1739. builder.cm.display.input.setUneditable(widget)
  1740. builder.content.appendChild(widget)
  1741. }
  1742. builder.pos += size
  1743. builder.trailingSpace = false
  1744. }
  1745. // Outputs a number of spans to make up a line, taking highlighting
  1746. // and marked text into account.
  1747. function insertLineContent(line, builder, styles) {
  1748. var spans = line.markedSpans, allText = line.text, at = 0
  1749. if (!spans) {
  1750. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1751. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
  1752. return
  1753. }
  1754. var len = allText.length, pos = 0, i = 1, text = "", style, css
  1755. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
  1756. for (;;) {
  1757. if (nextChange == pos) { // Update current marker set
  1758. spanStyle = spanEndStyle = spanStartStyle = title = css = ""
  1759. collapsed = null; nextChange = Infinity
  1760. var foundBookmarks = [], endStyles = (void 0)
  1761. for (var j = 0; j < spans.length; ++j) {
  1762. var sp = spans[j], m = sp.marker
  1763. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1764. foundBookmarks.push(m)
  1765. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1766. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1767. nextChange = sp.to
  1768. spanEndStyle = ""
  1769. }
  1770. if (m.className) { spanStyle += " " + m.className }
  1771. if (m.css) { css = (css ? css + ";" : "") + m.css }
  1772. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
  1773. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
  1774. if (m.title && !title) { title = m.title }
  1775. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1776. { collapsed = sp }
  1777. } else if (sp.from > pos && nextChange > sp.from) {
  1778. nextChange = sp.from
  1779. }
  1780. }
  1781. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1782. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
  1783. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1784. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
  1785. if (collapsed && (collapsed.from || 0) == pos) {
  1786. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1787. collapsed.marker, collapsed.from == null)
  1788. if (collapsed.to == null) { return }
  1789. if (collapsed.to == pos) { collapsed = false }
  1790. }
  1791. }
  1792. if (pos >= len) { break }
  1793. var upto = Math.min(len, nextChange)
  1794. while (true) {
  1795. if (text) {
  1796. var end = pos + text.length
  1797. if (!collapsed) {
  1798. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  1799. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1800. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
  1801. }
  1802. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1803. pos = end
  1804. spanStartStyle = ""
  1805. }
  1806. text = allText.slice(at, at = styles[i++])
  1807. style = interpretTokenStyle(styles[i++], builder.cm.options)
  1808. }
  1809. }
  1810. }
  1811. // These objects are used to represent the visible (currently drawn)
  1812. // part of the document. A LineView may correspond to multiple
  1813. // logical lines, if those are connected by collapsed ranges.
  1814. function LineView(doc, line, lineN) {
  1815. // The starting line
  1816. this.line = line
  1817. // Continuing lines, if any
  1818. this.rest = visualLineContinued(line)
  1819. // Number of logical lines in this visual line
  1820. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  1821. this.node = this.text = null
  1822. this.hidden = lineIsHidden(doc, line)
  1823. }
  1824. // Create a range of LineView objects for the given lines.
  1825. function buildViewArray(cm, from, to) {
  1826. var array = [], nextPos
  1827. for (var pos = from; pos < to; pos = nextPos) {
  1828. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  1829. nextPos = pos + view.size
  1830. array.push(view)
  1831. }
  1832. return array
  1833. }
  1834. var operationGroup = null
  1835. function pushOperation(op) {
  1836. if (operationGroup) {
  1837. operationGroup.ops.push(op)
  1838. } else {
  1839. op.ownsGroup = operationGroup = {
  1840. ops: [op],
  1841. delayedCallbacks: []
  1842. }
  1843. }
  1844. }
  1845. function fireCallbacksForOps(group) {
  1846. // Calls delayed callbacks and cursorActivity handlers until no
  1847. // new ones appear
  1848. var callbacks = group.delayedCallbacks, i = 0
  1849. do {
  1850. for (; i < callbacks.length; i++)
  1851. { callbacks[i].call(null) }
  1852. for (var j = 0; j < group.ops.length; j++) {
  1853. var op = group.ops[j]
  1854. if (op.cursorActivityHandlers)
  1855. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1856. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
  1857. }
  1858. } while (i < callbacks.length)
  1859. }
  1860. function finishOperation(op, endCb) {
  1861. var group = op.ownsGroup
  1862. if (!group) { return }
  1863. try { fireCallbacksForOps(group) }
  1864. finally {
  1865. operationGroup = null
  1866. endCb(group)
  1867. }
  1868. }
  1869. var orphanDelayedCallbacks = null
  1870. // Often, we want to signal events at a point where we are in the
  1871. // middle of some work, but don't want the handler to start calling
  1872. // other methods on the editor, which might be in an inconsistent
  1873. // state or simply not expect any other events to happen.
  1874. // signalLater looks whether there are any handlers, and schedules
  1875. // them to be executed when the last operation ends, or, if no
  1876. // operation is active, when a timeout fires.
  1877. function signalLater(emitter, type /*, values...*/) {
  1878. var arr = getHandlers(emitter, type)
  1879. if (!arr.length) { return }
  1880. var args = Array.prototype.slice.call(arguments, 2), list
  1881. if (operationGroup) {
  1882. list = operationGroup.delayedCallbacks
  1883. } else if (orphanDelayedCallbacks) {
  1884. list = orphanDelayedCallbacks
  1885. } else {
  1886. list = orphanDelayedCallbacks = []
  1887. setTimeout(fireOrphanDelayed, 0)
  1888. }
  1889. var loop = function ( i ) {
  1890. list.push(function () { return arr[i].apply(null, args); })
  1891. };
  1892. for (var i = 0; i < arr.length; ++i)
  1893. loop( i );
  1894. }
  1895. function fireOrphanDelayed() {
  1896. var delayed = orphanDelayedCallbacks
  1897. orphanDelayedCallbacks = null
  1898. for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
  1899. }
  1900. // When an aspect of a line changes, a string is added to
  1901. // lineView.changes. This updates the relevant part of the line's
  1902. // DOM structure.
  1903. function updateLineForChanges(cm, lineView, lineN, dims) {
  1904. for (var j = 0; j < lineView.changes.length; j++) {
  1905. var type = lineView.changes[j]
  1906. if (type == "text") { updateLineText(cm, lineView) }
  1907. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
  1908. else if (type == "class") { updateLineClasses(lineView) }
  1909. else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
  1910. }
  1911. lineView.changes = null
  1912. }
  1913. // Lines with gutter elements, widgets or a background class need to
  1914. // be wrapped, and have the extra elements added to the wrapper div
  1915. function ensureLineWrapped(lineView) {
  1916. if (lineView.node == lineView.text) {
  1917. lineView.node = elt("div", null, null, "position: relative")
  1918. if (lineView.text.parentNode)
  1919. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
  1920. lineView.node.appendChild(lineView.text)
  1921. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
  1922. }
  1923. return lineView.node
  1924. }
  1925. function updateLineBackground(lineView) {
  1926. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
  1927. if (cls) { cls += " CodeMirror-linebackground" }
  1928. if (lineView.background) {
  1929. if (cls) { lineView.background.className = cls }
  1930. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
  1931. } else if (cls) {
  1932. var wrap = ensureLineWrapped(lineView)
  1933. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
  1934. }
  1935. }
  1936. // Wrapper around buildLineContent which will reuse the structure
  1937. // in display.externalMeasured when possible.
  1938. function getLineContent(cm, lineView) {
  1939. var ext = cm.display.externalMeasured
  1940. if (ext && ext.line == lineView.line) {
  1941. cm.display.externalMeasured = null
  1942. lineView.measure = ext.measure
  1943. return ext.built
  1944. }
  1945. return buildLineContent(cm, lineView)
  1946. }
  1947. // Redraw the line's text. Interacts with the background and text
  1948. // classes because the mode may output tokens that influence these
  1949. // classes.
  1950. function updateLineText(cm, lineView) {
  1951. var cls = lineView.text.className
  1952. var built = getLineContent(cm, lineView)
  1953. if (lineView.text == lineView.node) { lineView.node = built.pre }
  1954. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  1955. lineView.text = built.pre
  1956. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1957. lineView.bgClass = built.bgClass
  1958. lineView.textClass = built.textClass
  1959. updateLineClasses(lineView)
  1960. } else if (cls) {
  1961. lineView.text.className = cls
  1962. }
  1963. }
  1964. function updateLineClasses(lineView) {
  1965. updateLineBackground(lineView)
  1966. if (lineView.line.wrapClass)
  1967. { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
  1968. else if (lineView.node != lineView.text)
  1969. { lineView.node.className = "" }
  1970. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
  1971. lineView.text.className = textClass || ""
  1972. }
  1973. function updateLineGutter(cm, lineView, lineN, dims) {
  1974. if (lineView.gutter) {
  1975. lineView.node.removeChild(lineView.gutter)
  1976. lineView.gutter = null
  1977. }
  1978. if (lineView.gutterBackground) {
  1979. lineView.node.removeChild(lineView.gutterBackground)
  1980. lineView.gutterBackground = null
  1981. }
  1982. if (lineView.line.gutterClass) {
  1983. var wrap = ensureLineWrapped(lineView)
  1984. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1985. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
  1986. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  1987. }
  1988. var markers = lineView.line.gutterMarkers
  1989. if (cm.options.lineNumbers || markers) {
  1990. var wrap$1 = ensureLineWrapped(lineView)
  1991. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
  1992. cm.display.input.setUneditable(gutterWrap)
  1993. wrap$1.insertBefore(gutterWrap, lineView.text)
  1994. if (lineView.line.gutterClass)
  1995. { gutterWrap.className += " " + lineView.line.gutterClass }
  1996. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  1997. { lineView.lineNumber = gutterWrap.appendChild(
  1998. elt("div", lineNumberFor(cm.options, lineN),
  1999. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2000. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
  2001. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2002. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
  2003. if (found)
  2004. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2005. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
  2006. } }
  2007. }
  2008. }
  2009. function updateLineWidgets(cm, lineView, dims) {
  2010. if (lineView.alignable) { lineView.alignable = null }
  2011. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2012. next = node.nextSibling
  2013. if (node.className == "CodeMirror-linewidget")
  2014. { lineView.node.removeChild(node) }
  2015. }
  2016. insertLineWidgets(cm, lineView, dims)
  2017. }
  2018. // Build a line's DOM representation from scratch
  2019. function buildLineElement(cm, lineView, lineN, dims) {
  2020. var built = getLineContent(cm, lineView)
  2021. lineView.text = lineView.node = built.pre
  2022. if (built.bgClass) { lineView.bgClass = built.bgClass }
  2023. if (built.textClass) { lineView.textClass = built.textClass }
  2024. updateLineClasses(lineView)
  2025. updateLineGutter(cm, lineView, lineN, dims)
  2026. insertLineWidgets(cm, lineView, dims)
  2027. return lineView.node
  2028. }
  2029. // A lineView may contain multiple logical lines (when merged by
  2030. // collapsed spans). The widgets for all of them need to be drawn.
  2031. function insertLineWidgets(cm, lineView, dims) {
  2032. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2033. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2034. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
  2035. }
  2036. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2037. if (!line.widgets) { return }
  2038. var wrap = ensureLineWrapped(lineView)
  2039. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2040. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
  2041. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
  2042. positionLineWidget(widget, node, lineView, dims)
  2043. cm.display.input.setUneditable(node)
  2044. if (allowAbove && widget.above)
  2045. { wrap.insertBefore(node, lineView.gutter || lineView.text) }
  2046. else
  2047. { wrap.appendChild(node) }
  2048. signalLater(widget, "redraw")
  2049. }
  2050. }
  2051. function positionLineWidget(widget, node, lineView, dims) {
  2052. if (widget.noHScroll) {
  2053. ;(lineView.alignable || (lineView.alignable = [])).push(node)
  2054. var width = dims.wrapperWidth
  2055. node.style.left = dims.fixedPos + "px"
  2056. if (!widget.coverGutter) {
  2057. width -= dims.gutterTotalWidth
  2058. node.style.paddingLeft = dims.gutterTotalWidth + "px"
  2059. }
  2060. node.style.width = width + "px"
  2061. }
  2062. if (widget.coverGutter) {
  2063. node.style.zIndex = 5
  2064. node.style.position = "relative"
  2065. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
  2066. }
  2067. }
  2068. function widgetHeight(widget) {
  2069. if (widget.height != null) { return widget.height }
  2070. var cm = widget.doc.cm
  2071. if (!cm) { return 0 }
  2072. if (!contains(document.body, widget.node)) {
  2073. var parentStyle = "position: relative;"
  2074. if (widget.coverGutter)
  2075. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
  2076. if (widget.noHScroll)
  2077. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
  2078. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
  2079. }
  2080. return widget.height = widget.node.parentNode.offsetHeight
  2081. }
  2082. // Return true when the given mouse event happened in a widget
  2083. function eventInWidget(display, e) {
  2084. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2085. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2086. (n.parentNode == display.sizer && n != display.mover))
  2087. { return true }
  2088. }
  2089. }
  2090. // POSITION MEASUREMENT
  2091. function paddingTop(display) {return display.lineSpace.offsetTop}
  2092. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2093. function paddingH(display) {
  2094. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2095. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  2096. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2097. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  2098. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
  2099. return data
  2100. }
  2101. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2102. function displayWidth(cm) {
  2103. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2104. }
  2105. function displayHeight(cm) {
  2106. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2107. }
  2108. // Ensure the lineView.wrapping.heights array is populated. This is
  2109. // an array of bottom offsets for the lines that make up a drawn
  2110. // line. When lineWrapping is on, there might be more than one
  2111. // height.
  2112. function ensureLineHeights(cm, lineView, rect) {
  2113. var wrapping = cm.options.lineWrapping
  2114. var curWidth = wrapping && displayWidth(cm)
  2115. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2116. var heights = lineView.measure.heights = []
  2117. if (wrapping) {
  2118. lineView.measure.width = curWidth
  2119. var rects = lineView.text.firstChild.getClientRects()
  2120. for (var i = 0; i < rects.length - 1; i++) {
  2121. var cur = rects[i], next = rects[i + 1]
  2122. if (Math.abs(cur.bottom - next.bottom) > 2)
  2123. { heights.push((cur.bottom + next.top) / 2 - rect.top) }
  2124. }
  2125. }
  2126. heights.push(rect.bottom - rect.top)
  2127. }
  2128. }
  2129. // Find a line map (mapping character offsets to text nodes) and a
  2130. // measurement cache for the given line number. (A line view might
  2131. // contain multiple lines when collapsed ranges are present.)
  2132. function mapFromLineView(lineView, line, lineN) {
  2133. if (lineView.line == line)
  2134. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2135. for (var i = 0; i < lineView.rest.length; i++)
  2136. { if (lineView.rest[i] == line)
  2137. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2138. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2139. { if (lineNo(lineView.rest[i$1]) > lineN)
  2140. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2141. }
  2142. // Render a line into the hidden node display.externalMeasured. Used
  2143. // when measurement is needed for a line that's not in the viewport.
  2144. function updateExternalMeasurement(cm, line) {
  2145. line = visualLine(line)
  2146. var lineN = lineNo(line)
  2147. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  2148. view.lineN = lineN
  2149. var built = view.built = buildLineContent(cm, view)
  2150. view.text = built.pre
  2151. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2152. return view
  2153. }
  2154. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2155. // for a given character.
  2156. function measureChar(cm, line, ch, bias) {
  2157. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2158. }
  2159. // Find a line view that corresponds to the given line number.
  2160. function findViewForLine(cm, lineN) {
  2161. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2162. { return cm.display.view[findViewIndex(cm, lineN)] }
  2163. var ext = cm.display.externalMeasured
  2164. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2165. { return ext }
  2166. }
  2167. // Measurement can be split in two steps, the set-up work that
  2168. // applies to the whole line, and the measurement of the actual
  2169. // character. Functions like coordsChar, that need to do a lot of
  2170. // measurements in a row, can thus ensure that the set-up work is
  2171. // only done once.
  2172. function prepareMeasureForLine(cm, line) {
  2173. var lineN = lineNo(line)
  2174. var view = findViewForLine(cm, lineN)
  2175. if (view && !view.text) {
  2176. view = null
  2177. } else if (view && view.changes) {
  2178. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2179. cm.curOp.forceUpdate = true
  2180. }
  2181. if (!view)
  2182. { view = updateExternalMeasurement(cm, line) }
  2183. var info = mapFromLineView(view, line, lineN)
  2184. return {
  2185. line: line, view: view, rect: null,
  2186. map: info.map, cache: info.cache, before: info.before,
  2187. hasHeights: false
  2188. }
  2189. }
  2190. // Given a prepared measurement object, measures the position of an
  2191. // actual character (or fetches it from the cache).
  2192. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2193. if (prepared.before) { ch = -1 }
  2194. var key = ch + (bias || ""), found
  2195. if (prepared.cache.hasOwnProperty(key)) {
  2196. found = prepared.cache[key]
  2197. } else {
  2198. if (!prepared.rect)
  2199. { prepared.rect = prepared.view.text.getBoundingClientRect() }
  2200. if (!prepared.hasHeights) {
  2201. ensureLineHeights(cm, prepared.view, prepared.rect)
  2202. prepared.hasHeights = true
  2203. }
  2204. found = measureCharInner(cm, prepared, ch, bias)
  2205. if (!found.bogus) { prepared.cache[key] = found }
  2206. }
  2207. return {left: found.left, right: found.right,
  2208. top: varHeight ? found.rtop : found.top,
  2209. bottom: varHeight ? found.rbottom : found.bottom}
  2210. }
  2211. var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  2212. function nodeAndOffsetInLineMap(map, ch, bias) {
  2213. var node, start, end, collapse, mStart, mEnd
  2214. // First, search the line map for the text node corresponding to,
  2215. // or closest to, the target character.
  2216. for (var i = 0; i < map.length; i += 3) {
  2217. mStart = map[i]
  2218. mEnd = map[i + 1]
  2219. if (ch < mStart) {
  2220. start = 0; end = 1
  2221. collapse = "left"
  2222. } else if (ch < mEnd) {
  2223. start = ch - mStart
  2224. end = start + 1
  2225. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2226. end = mEnd - mStart
  2227. start = end - 1
  2228. if (ch >= mEnd) { collapse = "right" }
  2229. }
  2230. if (start != null) {
  2231. node = map[i + 2]
  2232. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2233. { collapse = bias }
  2234. if (bias == "left" && start == 0)
  2235. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2236. node = map[(i -= 3) + 2]
  2237. collapse = "left"
  2238. } }
  2239. if (bias == "right" && start == mEnd - mStart)
  2240. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2241. node = map[(i += 3) + 2]
  2242. collapse = "right"
  2243. } }
  2244. break
  2245. }
  2246. }
  2247. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2248. }
  2249. function getUsefulRect(rects, bias) {
  2250. var rect = nullRect
  2251. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2252. if ((rect = rects[i]).left != rect.right) { break }
  2253. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2254. if ((rect = rects[i$1]).left != rect.right) { break }
  2255. } }
  2256. return rect
  2257. }
  2258. function measureCharInner(cm, prepared, ch, bias) {
  2259. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  2260. var node = place.node, start = place.start, end = place.end, collapse = place.collapse
  2261. var rect
  2262. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2263. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2264. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
  2265. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
  2266. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2267. { rect = node.parentNode.getBoundingClientRect() }
  2268. else
  2269. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
  2270. if (rect.left || rect.right || start == 0) { break }
  2271. end = start
  2272. start = start - 1
  2273. collapse = "right"
  2274. }
  2275. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
  2276. } else { // If it is a widget, simply get the box for the whole widget.
  2277. if (start > 0) { collapse = bias = "right" }
  2278. var rects
  2279. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2280. { rect = rects[bias == "right" ? rects.length - 1 : 0] }
  2281. else
  2282. { rect = node.getBoundingClientRect() }
  2283. }
  2284. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2285. var rSpan = node.parentNode.getClientRects()[0]
  2286. if (rSpan)
  2287. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
  2288. else
  2289. { rect = nullRect }
  2290. }
  2291. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  2292. var mid = (rtop + rbot) / 2
  2293. var heights = prepared.view.measure.heights
  2294. var i = 0
  2295. for (; i < heights.length - 1; i++)
  2296. { if (mid < heights[i]) { break } }
  2297. var top = i ? heights[i - 1] : 0, bot = heights[i]
  2298. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2299. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2300. top: top, bottom: bot}
  2301. if (!rect.left && !rect.right) { result.bogus = true }
  2302. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  2303. return result
  2304. }
  2305. // Work around problem with bounding client rects on ranges being
  2306. // returned incorrectly when zoomed on IE10 and below.
  2307. function maybeUpdateRectForZooming(measure, rect) {
  2308. if (!window.screen || screen.logicalXDPI == null ||
  2309. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2310. { return rect }
  2311. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  2312. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  2313. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2314. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2315. }
  2316. function clearLineMeasurementCacheFor(lineView) {
  2317. if (lineView.measure) {
  2318. lineView.measure.cache = {}
  2319. lineView.measure.heights = null
  2320. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2321. { lineView.measure.caches[i] = {} } }
  2322. }
  2323. }
  2324. function clearLineMeasurementCache(cm) {
  2325. cm.display.externalMeasure = null
  2326. removeChildren(cm.display.lineMeasure)
  2327. for (var i = 0; i < cm.display.view.length; i++)
  2328. { clearLineMeasurementCacheFor(cm.display.view[i]) }
  2329. }
  2330. function clearCaches(cm) {
  2331. clearLineMeasurementCache(cm)
  2332. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  2333. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
  2334. cm.display.lineNumChars = null
  2335. }
  2336. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft }
  2337. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop }
  2338. // Converts a {top, bottom, left, right} box from line-local
  2339. // coordinates into another coordinate system. Context may be one of
  2340. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2341. // or "page".
  2342. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2343. if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
  2344. var size = widgetHeight(lineObj.widgets[i])
  2345. rect.top += size; rect.bottom += size
  2346. } } }
  2347. if (context == "line") { return rect }
  2348. if (!context) { context = "local" }
  2349. var yOff = heightAtLine(lineObj)
  2350. if (context == "local") { yOff += paddingTop(cm.display) }
  2351. else { yOff -= cm.display.viewOffset }
  2352. if (context == "page" || context == "window") {
  2353. var lOff = cm.display.lineSpace.getBoundingClientRect()
  2354. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  2355. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  2356. rect.left += xOff; rect.right += xOff
  2357. }
  2358. rect.top += yOff; rect.bottom += yOff
  2359. return rect
  2360. }
  2361. // Coverts a box from "div" coords to another coordinate system.
  2362. // Context may be "window", "page", "div", or "local"./null.
  2363. function fromCoordSystem(cm, coords, context) {
  2364. if (context == "div") { return coords }
  2365. var left = coords.left, top = coords.top
  2366. // First move into "page" coordinate system
  2367. if (context == "page") {
  2368. left -= pageScrollX()
  2369. top -= pageScrollY()
  2370. } else if (context == "local" || !context) {
  2371. var localBox = cm.display.sizer.getBoundingClientRect()
  2372. left += localBox.left
  2373. top += localBox.top
  2374. }
  2375. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  2376. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2377. }
  2378. function charCoords(cm, pos, context, lineObj, bias) {
  2379. if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
  2380. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2381. }
  2382. // Returns a box for a given cursor position, which may have an
  2383. // 'other' property containing the position of the secondary cursor
  2384. // on a bidi boundary.
  2385. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2386. lineObj = lineObj || getLine(cm.doc, pos.line)
  2387. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2388. function get(ch, right) {
  2389. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  2390. if (right) { m.left = m.right; } else { m.right = m.left }
  2391. return intoCoordSystem(cm, lineObj, m, context)
  2392. }
  2393. function getBidi(ch, partPos) {
  2394. var part = order[partPos], right = part.level % 2
  2395. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2396. part = order[--partPos]
  2397. ch = bidiRight(part) - (part.level % 2 ? 0 : 1)
  2398. right = true
  2399. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2400. part = order[++partPos]
  2401. ch = bidiLeft(part) - part.level % 2
  2402. right = false
  2403. }
  2404. if (right && ch == part.to && ch > part.from) { return get(ch - 1) }
  2405. return get(ch, right)
  2406. }
  2407. var order = getOrder(lineObj), ch = pos.ch
  2408. if (!order) { return get(ch) }
  2409. var partPos = getBidiPartAt(order, ch)
  2410. var val = getBidi(ch, partPos)
  2411. if (bidiOther != null) { val.other = getBidi(ch, bidiOther) }
  2412. return val
  2413. }
  2414. // Used to cheaply estimate the coordinates for a position. Used for
  2415. // intermediate scroll updates.
  2416. function estimateCoords(cm, pos) {
  2417. var left = 0
  2418. pos = clipPos(cm.doc, pos)
  2419. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
  2420. var lineObj = getLine(cm.doc, pos.line)
  2421. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  2422. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2423. }
  2424. // Positions returned by coordsChar contain some extra information.
  2425. // xRel is the relative x position of the input coordinates compared
  2426. // to the found position (so xRel > 0 means the coordinates are to
  2427. // the right of the character position, for example). When outside
  2428. // is true, that means the coordinates lie outside the line's
  2429. // vertical range.
  2430. function PosWithInfo(line, ch, outside, xRel) {
  2431. var pos = Pos(line, ch)
  2432. pos.xRel = xRel
  2433. if (outside) { pos.outside = true }
  2434. return pos
  2435. }
  2436. // Compute the character position closest to the given coordinates.
  2437. // Input must be lineSpace-local ("div" coordinate system).
  2438. function coordsChar(cm, x, y) {
  2439. var doc = cm.doc
  2440. y += cm.display.viewOffset
  2441. if (y < 0) { return PosWithInfo(doc.first, 0, true, -1) }
  2442. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  2443. if (lineN > last)
  2444. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1) }
  2445. if (x < 0) { x = 0 }
  2446. var lineObj = getLine(doc, lineN)
  2447. for (;;) {
  2448. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  2449. var merged = collapsedSpanAtEnd(lineObj)
  2450. var mergedPos = merged && merged.find(0, true)
  2451. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2452. { lineN = lineNo(lineObj = mergedPos.to.line) }
  2453. else
  2454. { return found }
  2455. }
  2456. }
  2457. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2458. var innerOff = y - heightAtLine(lineObj)
  2459. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth
  2460. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  2461. function getX(ch) {
  2462. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure)
  2463. wrongLine = true
  2464. if (innerOff > sp.bottom) { return sp.left - adjust }
  2465. else if (innerOff < sp.top) { return sp.left + adjust }
  2466. else { wrongLine = false }
  2467. return sp.left
  2468. }
  2469. var bidi = getOrder(lineObj), dist = lineObj.text.length
  2470. var from = lineLeft(lineObj), to = lineRight(lineObj)
  2471. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine
  2472. if (x > toX) { return PosWithInfo(lineNo, to, toOutside, 1) }
  2473. // Do a binary search between these bounds.
  2474. for (;;) {
  2475. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2476. var ch = x < fromX || x - fromX <= toX - x ? from : to
  2477. var outside = ch == from ? fromOutside : toOutside
  2478. var xDiff = x - (ch == from ? fromX : toX)
  2479. // This is a kludge to handle the case where the coordinates
  2480. // are after a line-wrapped line. We should replace it with a
  2481. // more general handling of cursor positions around line
  2482. // breaks. (Issue #4078)
  2483. if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 &&
  2484. ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) {
  2485. var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right")
  2486. if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) {
  2487. outside = false
  2488. ch++
  2489. xDiff = x - charSize.right
  2490. }
  2491. }
  2492. while (isExtendingChar(lineObj.text.charAt(ch))) { ++ch }
  2493. var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0)
  2494. return pos
  2495. }
  2496. var step = Math.ceil(dist / 2), middle = from + step
  2497. if (bidi) {
  2498. middle = from
  2499. for (var i = 0; i < step; ++i) { middle = moveVisually(lineObj, middle, 1) }
  2500. }
  2501. var middleX = getX(middle)
  2502. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) { toX += 1000; } dist = step}
  2503. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step}
  2504. }
  2505. }
  2506. var measureText
  2507. // Compute the default text height.
  2508. function textHeight(display) {
  2509. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2510. if (measureText == null) {
  2511. measureText = elt("pre")
  2512. // Measure a bunch of lines, for browsers that compute
  2513. // fractional heights.
  2514. for (var i = 0; i < 49; ++i) {
  2515. measureText.appendChild(document.createTextNode("x"))
  2516. measureText.appendChild(elt("br"))
  2517. }
  2518. measureText.appendChild(document.createTextNode("x"))
  2519. }
  2520. removeChildrenAndAdd(display.measure, measureText)
  2521. var height = measureText.offsetHeight / 50
  2522. if (height > 3) { display.cachedTextHeight = height }
  2523. removeChildren(display.measure)
  2524. return height || 1
  2525. }
  2526. // Compute the default character width.
  2527. function charWidth(display) {
  2528. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2529. var anchor = elt("span", "xxxxxxxxxx")
  2530. var pre = elt("pre", [anchor])
  2531. removeChildrenAndAdd(display.measure, pre)
  2532. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
  2533. if (width > 2) { display.cachedCharWidth = width }
  2534. return width || 10
  2535. }
  2536. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2537. // view, so that we don't interleave reading and writing to the DOM.
  2538. function getDimensions(cm) {
  2539. var d = cm.display, left = {}, width = {}
  2540. var gutterLeft = d.gutters.clientLeft
  2541. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2542. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
  2543. width[cm.options.gutters[i]] = n.clientWidth
  2544. }
  2545. return {fixedPos: compensateForHScroll(d),
  2546. gutterTotalWidth: d.gutters.offsetWidth,
  2547. gutterLeft: left,
  2548. gutterWidth: width,
  2549. wrapperWidth: d.wrapper.clientWidth}
  2550. }
  2551. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2552. // but using getBoundingClientRect to get a sub-pixel-accurate
  2553. // result.
  2554. function compensateForHScroll(display) {
  2555. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2556. }
  2557. // Returns a function that estimates the height of a line, to use as
  2558. // first approximation until the line becomes visible (and is thus
  2559. // properly measurable).
  2560. function estimateHeight(cm) {
  2561. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
  2562. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  2563. return function (line) {
  2564. if (lineIsHidden(cm.doc, line)) { return 0 }
  2565. var widgetsHeight = 0
  2566. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2567. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
  2568. } }
  2569. if (wrapping)
  2570. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2571. else
  2572. { return widgetsHeight + th }
  2573. }
  2574. }
  2575. function estimateLineHeights(cm) {
  2576. var doc = cm.doc, est = estimateHeight(cm)
  2577. doc.iter(function (line) {
  2578. var estHeight = est(line)
  2579. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  2580. })
  2581. }
  2582. // Given a mouse event, find the corresponding position. If liberal
  2583. // is false, it checks whether a gutter or scrollbar was clicked,
  2584. // and returns null if it was. forRect is used by rectangular
  2585. // selections, and tries to estimate a character position even for
  2586. // coordinates beyond the right of the text.
  2587. function posFromMouse(cm, e, liberal, forRect) {
  2588. var display = cm.display
  2589. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2590. var x, y, space = display.lineSpace.getBoundingClientRect()
  2591. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2592. try { x = e.clientX - space.left; y = e.clientY - space.top }
  2593. catch (e) { return null }
  2594. var coords = coordsChar(cm, x, y), line
  2595. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2596. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  2597. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  2598. }
  2599. return coords
  2600. }
  2601. // Find the view element corresponding to a given line. Return null
  2602. // when the line isn't visible.
  2603. function findViewIndex(cm, n) {
  2604. if (n >= cm.display.viewTo) { return null }
  2605. n -= cm.display.viewFrom
  2606. if (n < 0) { return null }
  2607. var view = cm.display.view
  2608. for (var i = 0; i < view.length; i++) {
  2609. n -= view[i].size
  2610. if (n < 0) { return i }
  2611. }
  2612. }
  2613. function updateSelection(cm) {
  2614. cm.display.input.showSelection(cm.display.input.prepareSelection())
  2615. }
  2616. function prepareSelection(cm, primary) {
  2617. var doc = cm.doc, result = {}
  2618. var curFragment = result.cursors = document.createDocumentFragment()
  2619. var selFragment = result.selection = document.createDocumentFragment()
  2620. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2621. if (primary === false && i == doc.sel.primIndex) { continue }
  2622. var range = doc.sel.ranges[i]
  2623. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2624. var collapsed = range.empty()
  2625. if (collapsed || cm.options.showCursorWhenSelecting)
  2626. { drawSelectionCursor(cm, range.head, curFragment) }
  2627. if (!collapsed)
  2628. { drawSelectionRange(cm, range, selFragment) }
  2629. }
  2630. return result
  2631. }
  2632. // Draws a cursor for the given range
  2633. function drawSelectionCursor(cm, head, output) {
  2634. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
  2635. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
  2636. cursor.style.left = pos.left + "px"
  2637. cursor.style.top = pos.top + "px"
  2638. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
  2639. if (pos.other) {
  2640. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2641. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
  2642. otherCursor.style.display = ""
  2643. otherCursor.style.left = pos.other.left + "px"
  2644. otherCursor.style.top = pos.other.top + "px"
  2645. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
  2646. }
  2647. }
  2648. // Draws the given range as a highlighted selection
  2649. function drawSelectionRange(cm, range, output) {
  2650. var display = cm.display, doc = cm.doc
  2651. var fragment = document.createDocumentFragment()
  2652. var padding = paddingH(cm.display), leftSide = padding.left
  2653. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  2654. function add(left, top, width, bottom) {
  2655. if (top < 0) { top = 0 }
  2656. top = Math.round(top)
  2657. bottom = Math.round(bottom)
  2658. fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")))
  2659. }
  2660. function drawForLine(line, fromArg, toArg) {
  2661. var lineObj = getLine(doc, line)
  2662. var lineLen = lineObj.text.length
  2663. var start, end
  2664. function coords(ch, bias) {
  2665. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2666. }
  2667. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
  2668. var leftPos = coords(from, "left"), rightPos, left, right
  2669. if (from == to) {
  2670. rightPos = leftPos
  2671. left = right = leftPos.left
  2672. } else {
  2673. rightPos = coords(to - 1, "right")
  2674. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp }
  2675. left = leftPos.left
  2676. right = rightPos.right
  2677. }
  2678. if (fromArg == null && from == 0) { left = leftSide }
  2679. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2680. add(left, leftPos.top, null, leftPos.bottom)
  2681. left = leftSide
  2682. if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) }
  2683. }
  2684. if (toArg == null && to == lineLen) { right = rightSide }
  2685. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2686. { start = leftPos }
  2687. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2688. { end = rightPos }
  2689. if (left < leftSide + 1) { left = leftSide }
  2690. add(left, rightPos.top, right - left, rightPos.bottom)
  2691. })
  2692. return {start: start, end: end}
  2693. }
  2694. var sFrom = range.from(), sTo = range.to()
  2695. if (sFrom.line == sTo.line) {
  2696. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  2697. } else {
  2698. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
  2699. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  2700. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  2701. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  2702. if (singleVLine) {
  2703. if (leftEnd.top < rightStart.top - 2) {
  2704. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  2705. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  2706. } else {
  2707. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  2708. }
  2709. }
  2710. if (leftEnd.bottom < rightStart.top)
  2711. { add(leftSide, leftEnd.bottom, null, rightStart.top) }
  2712. }
  2713. output.appendChild(fragment)
  2714. }
  2715. // Cursor-blinking
  2716. function restartBlink(cm) {
  2717. if (!cm.state.focused) { return }
  2718. var display = cm.display
  2719. clearInterval(display.blinker)
  2720. var on = true
  2721. display.cursorDiv.style.visibility = ""
  2722. if (cm.options.cursorBlinkRate > 0)
  2723. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2724. cm.options.cursorBlinkRate) }
  2725. else if (cm.options.cursorBlinkRate < 0)
  2726. { display.cursorDiv.style.visibility = "hidden" }
  2727. }
  2728. function ensureFocus(cm) {
  2729. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
  2730. }
  2731. function delayBlurEvent(cm) {
  2732. cm.state.delayingBlurEvent = true
  2733. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2734. cm.state.delayingBlurEvent = false
  2735. onBlur(cm)
  2736. } }, 100)
  2737. }
  2738. function onFocus(cm, e) {
  2739. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
  2740. if (cm.options.readOnly == "nocursor") { return }
  2741. if (!cm.state.focused) {
  2742. signal(cm, "focus", cm, e)
  2743. cm.state.focused = true
  2744. addClass(cm.display.wrapper, "CodeMirror-focused")
  2745. // This test prevents this from firing when a context
  2746. // menu is closed (since the input reset would kill the
  2747. // select-all detection hack)
  2748. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2749. cm.display.input.reset()
  2750. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
  2751. }
  2752. cm.display.input.receivedFocus()
  2753. }
  2754. restartBlink(cm)
  2755. }
  2756. function onBlur(cm, e) {
  2757. if (cm.state.delayingBlurEvent) { return }
  2758. if (cm.state.focused) {
  2759. signal(cm, "blur", cm, e)
  2760. cm.state.focused = false
  2761. rmClass(cm.display.wrapper, "CodeMirror-focused")
  2762. }
  2763. clearInterval(cm.display.blinker)
  2764. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
  2765. }
  2766. // Re-align line numbers and gutter marks to compensate for
  2767. // horizontal scrolling.
  2768. function alignHorizontally(cm) {
  2769. var display = cm.display, view = display.view
  2770. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  2771. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  2772. var gutterW = display.gutters.offsetWidth, left = comp + "px"
  2773. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  2774. if (cm.options.fixedGutter) {
  2775. if (view[i].gutter)
  2776. { view[i].gutter.style.left = left }
  2777. if (view[i].gutterBackground)
  2778. { view[i].gutterBackground.style.left = left }
  2779. }
  2780. var align = view[i].alignable
  2781. if (align) { for (var j = 0; j < align.length; j++)
  2782. { align[j].style.left = left } }
  2783. } }
  2784. if (cm.options.fixedGutter)
  2785. { display.gutters.style.left = (comp + gutterW) + "px" }
  2786. }
  2787. // Used to ensure that the line number gutter is still the right
  2788. // size for the current document size. Returns true when an update
  2789. // is needed.
  2790. function maybeUpdateLineNumberWidth(cm) {
  2791. if (!cm.options.lineNumbers) { return false }
  2792. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
  2793. if (last.length != display.lineNumChars) {
  2794. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  2795. "CodeMirror-linenumber CodeMirror-gutter-elt"))
  2796. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
  2797. display.lineGutter.style.width = ""
  2798. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  2799. display.lineNumWidth = display.lineNumInnerWidth + padding
  2800. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  2801. display.lineGutter.style.width = display.lineNumWidth + "px"
  2802. updateGutterSpace(cm)
  2803. return true
  2804. }
  2805. return false
  2806. }
  2807. // Read the actual heights of the rendered lines, and update their
  2808. // stored heights to match.
  2809. function updateHeightsInViewport(cm) {
  2810. var display = cm.display
  2811. var prevBottom = display.lineDiv.offsetTop
  2812. for (var i = 0; i < display.view.length; i++) {
  2813. var cur = display.view[i], height = (void 0)
  2814. if (cur.hidden) { continue }
  2815. if (ie && ie_version < 8) {
  2816. var bot = cur.node.offsetTop + cur.node.offsetHeight
  2817. height = bot - prevBottom
  2818. prevBottom = bot
  2819. } else {
  2820. var box = cur.node.getBoundingClientRect()
  2821. height = box.bottom - box.top
  2822. }
  2823. var diff = cur.line.height - height
  2824. if (height < 2) { height = textHeight(display) }
  2825. if (diff > .001 || diff < -.001) {
  2826. updateLineHeight(cur.line, height)
  2827. updateWidgetHeight(cur.line)
  2828. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2829. { updateWidgetHeight(cur.rest[j]) } }
  2830. }
  2831. }
  2832. }
  2833. // Read and store the height of line widgets associated with the
  2834. // given line.
  2835. function updateWidgetHeight(line) {
  2836. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
  2837. { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } }
  2838. }
  2839. // Compute the lines that are visible in a given viewport (defaults
  2840. // the the current scroll position). viewport may contain top,
  2841. // height, and ensure (see op.scrollToPos) properties.
  2842. function visibleLines(display, doc, viewport) {
  2843. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  2844. top = Math.floor(top - paddingTop(display))
  2845. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  2846. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
  2847. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2848. // forces those lines into the viewport (if possible).
  2849. if (viewport && viewport.ensure) {
  2850. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
  2851. if (ensureFrom < from) {
  2852. from = ensureFrom
  2853. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  2854. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2855. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  2856. to = ensureTo
  2857. }
  2858. }
  2859. return {from: from, to: Math.max(to, from + 1)}
  2860. }
  2861. // Sync the scrollable area and scrollbars, ensure the viewport
  2862. // covers the visible area.
  2863. function setScrollTop(cm, val) {
  2864. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  2865. cm.doc.scrollTop = val
  2866. if (!gecko) { updateDisplaySimple(cm, {top: val}) }
  2867. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
  2868. cm.display.scrollbars.setScrollTop(val)
  2869. if (gecko) { updateDisplaySimple(cm) }
  2870. startWorker(cm, 100)
  2871. }
  2872. // Sync scroller and scrollbar, ensure the gutter elements are
  2873. // aligned.
  2874. function setScrollLeft(cm, val, isScroller) {
  2875. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return }
  2876. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
  2877. cm.doc.scrollLeft = val
  2878. alignHorizontally(cm)
  2879. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
  2880. cm.display.scrollbars.setScrollLeft(val)
  2881. }
  2882. // Since the delta values reported on mouse wheel events are
  2883. // unstandardized between browsers and even browser versions, and
  2884. // generally horribly unpredictable, this code starts by measuring
  2885. // the scroll effect that the first few mouse wheel events have,
  2886. // and, from that, detects the way it can convert deltas to pixel
  2887. // offsets afterwards.
  2888. //
  2889. // The reason we want to know the amount a wheel event will scroll
  2890. // is that it gives us a chance to update the display before the
  2891. // actual scrolling happens, reducing flickering.
  2892. var wheelSamples = 0;
  2893. var wheelPixelsPerUnit = null;
  2894. // Fill in a browser-detected starting value on browsers where we
  2895. // know one. These don't have to be accurate -- the result of them
  2896. // being wrong would just be a slight flicker on the first wheel
  2897. // scroll (if it is large enough).
  2898. if (ie) { wheelPixelsPerUnit = -.53 }
  2899. else if (gecko) { wheelPixelsPerUnit = 15 }
  2900. else if (chrome) { wheelPixelsPerUnit = -.7 }
  2901. else if (safari) { wheelPixelsPerUnit = -1/3 }
  2902. function wheelEventDelta(e) {
  2903. var dx = e.wheelDeltaX, dy = e.wheelDeltaY
  2904. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
  2905. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
  2906. else if (dy == null) { dy = e.wheelDelta }
  2907. return {x: dx, y: dy}
  2908. }
  2909. function wheelEventPixels(e) {
  2910. var delta = wheelEventDelta(e)
  2911. delta.x *= wheelPixelsPerUnit
  2912. delta.y *= wheelPixelsPerUnit
  2913. return delta
  2914. }
  2915. function onScrollWheel(cm, e) {
  2916. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
  2917. var display = cm.display, scroll = display.scroller
  2918. // Quit if there's nothing to scroll here
  2919. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  2920. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  2921. if (!(dx && canScrollX || dy && canScrollY)) { return }
  2922. // Webkit browsers on OS X abort momentum scrolls when the target
  2923. // of the scroll event is removed from the scrollable element.
  2924. // This hack (see related code in patchDisplay) makes sure the
  2925. // element is kept around.
  2926. if (dy && mac && webkit) {
  2927. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  2928. for (var i = 0; i < view.length; i++) {
  2929. if (view[i].node == cur) {
  2930. cm.display.currentWheelTarget = cur
  2931. break outer
  2932. }
  2933. }
  2934. }
  2935. }
  2936. // On some browsers, horizontal scrolling will cause redraws to
  2937. // happen before the gutter has been realigned, causing it to
  2938. // wriggle around in a most unseemly way. When we have an
  2939. // estimated pixels/delta value, we just handle horizontal
  2940. // scrolling entirely here. It'll be slightly off from native, but
  2941. // better than glitching out.
  2942. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  2943. if (dy && canScrollY)
  2944. { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) }
  2945. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)))
  2946. // Only prevent default scrolling if vertical scrolling is
  2947. // actually possible. Otherwise, it causes vertical scroll
  2948. // jitter on OSX trackpads when deltaX is small and deltaY
  2949. // is large (issue #3579)
  2950. if (!dy || (dy && canScrollY))
  2951. { e_preventDefault(e) }
  2952. display.wheelStartX = null // Abort measurement, if in progress
  2953. return
  2954. }
  2955. // 'Project' the visible viewport to cover the area that is being
  2956. // scrolled into view (if we know enough to estimate it).
  2957. if (dy && wheelPixelsPerUnit != null) {
  2958. var pixels = dy * wheelPixelsPerUnit
  2959. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
  2960. if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
  2961. else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
  2962. updateDisplaySimple(cm, {top: top, bottom: bot})
  2963. }
  2964. if (wheelSamples < 20) {
  2965. if (display.wheelStartX == null) {
  2966. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
  2967. display.wheelDX = dx; display.wheelDY = dy
  2968. setTimeout(function () {
  2969. if (display.wheelStartX == null) { return }
  2970. var movedX = scroll.scrollLeft - display.wheelStartX
  2971. var movedY = scroll.scrollTop - display.wheelStartY
  2972. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  2973. (movedX && display.wheelDX && movedX / display.wheelDX)
  2974. display.wheelStartX = display.wheelStartY = null
  2975. if (!sample) { return }
  2976. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  2977. ++wheelSamples
  2978. }, 200)
  2979. } else {
  2980. display.wheelDX += dx; display.wheelDY += dy
  2981. }
  2982. }
  2983. }
  2984. // SCROLLBARS
  2985. // Prepare DOM reads needed to update the scrollbars. Done in one
  2986. // shot to minimize update/measure roundtrips.
  2987. function measureForScrollbars(cm) {
  2988. var d = cm.display, gutterW = d.gutters.offsetWidth
  2989. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  2990. return {
  2991. clientHeight: d.scroller.clientHeight,
  2992. viewHeight: d.wrapper.clientHeight,
  2993. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  2994. viewWidth: d.wrapper.clientWidth,
  2995. barLeft: cm.options.fixedGutter ? gutterW : 0,
  2996. docHeight: docH,
  2997. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  2998. nativeBarWidth: d.nativeBarWidth,
  2999. gutterWidth: gutterW
  3000. }
  3001. }
  3002. var NativeScrollbars = function(place, scroll, cm) {
  3003. this.cm = cm
  3004. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
  3005. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
  3006. place(vert); place(horiz)
  3007. on(vert, "scroll", function () {
  3008. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
  3009. })
  3010. on(horiz, "scroll", function () {
  3011. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
  3012. })
  3013. this.checkedZeroWidth = false
  3014. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3015. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
  3016. };
  3017. NativeScrollbars.prototype.update = function (measure) {
  3018. var needsH = measure.scrollWidth > measure.clientWidth + 1
  3019. var needsV = measure.scrollHeight > measure.clientHeight + 1
  3020. var sWidth = measure.nativeBarWidth
  3021. if (needsV) {
  3022. this.vert.style.display = "block"
  3023. this.vert.style.bottom = needsH ? sWidth + "px" : "0"
  3024. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  3025. // A bug in IE8 can cause this value to be negative, so guard it.
  3026. this.vert.firstChild.style.height =
  3027. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
  3028. } else {
  3029. this.vert.style.display = ""
  3030. this.vert.firstChild.style.height = "0"
  3031. }
  3032. if (needsH) {
  3033. this.horiz.style.display = "block"
  3034. this.horiz.style.right = needsV ? sWidth + "px" : "0"
  3035. this.horiz.style.left = measure.barLeft + "px"
  3036. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  3037. this.horiz.firstChild.style.width =
  3038. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
  3039. } else {
  3040. this.horiz.style.display = ""
  3041. this.horiz.firstChild.style.width = "0"
  3042. }
  3043. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3044. if (sWidth == 0) { this.zeroWidthHack() }
  3045. this.checkedZeroWidth = true
  3046. }
  3047. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3048. };
  3049. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3050. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
  3051. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz) }
  3052. };
  3053. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3054. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
  3055. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert) }
  3056. };
  3057. NativeScrollbars.prototype.zeroWidthHack = function () {
  3058. var w = mac && !mac_geMountainLion ? "12px" : "18px"
  3059. this.horiz.style.height = this.vert.style.width = w
  3060. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
  3061. this.disableHoriz = new Delayed
  3062. this.disableVert = new Delayed
  3063. };
  3064. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay) {
  3065. bar.style.pointerEvents = "auto"
  3066. function maybeDisable() {
  3067. // To find out whether the scrollbar is still visible, we
  3068. // check whether the element under the pixel in the bottom
  3069. // left corner of the scrollbar box is the scrollbar box
  3070. // itself (when the bar is still visible) or its filler child
  3071. // (when the bar is hidden). If it is still visible, we keep
  3072. // it enabled, if it's hidden, we disable pointer events.
  3073. var box = bar.getBoundingClientRect()
  3074. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1)
  3075. if (elt != bar) { bar.style.pointerEvents = "none" }
  3076. else { delay.set(1000, maybeDisable) }
  3077. }
  3078. delay.set(1000, maybeDisable)
  3079. };
  3080. NativeScrollbars.prototype.clear = function () {
  3081. var parent = this.horiz.parentNode
  3082. parent.removeChild(this.horiz)
  3083. parent.removeChild(this.vert)
  3084. };
  3085. var NullScrollbars = function () {};
  3086. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3087. NullScrollbars.prototype.setScrollLeft = function () {};
  3088. NullScrollbars.prototype.setScrollTop = function () {};
  3089. NullScrollbars.prototype.clear = function () {};
  3090. function updateScrollbars(cm, measure) {
  3091. if (!measure) { measure = measureForScrollbars(cm) }
  3092. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
  3093. updateScrollbarsInner(cm, measure)
  3094. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3095. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3096. { updateHeightsInViewport(cm) }
  3097. updateScrollbarsInner(cm, measureForScrollbars(cm))
  3098. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
  3099. }
  3100. }
  3101. // Re-synchronize the fake scrollbars with the actual size of the
  3102. // content.
  3103. function updateScrollbarsInner(cm, measure) {
  3104. var d = cm.display
  3105. var sizes = d.scrollbars.update(measure)
  3106. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
  3107. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
  3108. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  3109. if (sizes.right && sizes.bottom) {
  3110. d.scrollbarFiller.style.display = "block"
  3111. d.scrollbarFiller.style.height = sizes.bottom + "px"
  3112. d.scrollbarFiller.style.width = sizes.right + "px"
  3113. } else { d.scrollbarFiller.style.display = "" }
  3114. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3115. d.gutterFiller.style.display = "block"
  3116. d.gutterFiller.style.height = sizes.bottom + "px"
  3117. d.gutterFiller.style.width = measure.gutterWidth + "px"
  3118. } else { d.gutterFiller.style.display = "" }
  3119. }
  3120. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
  3121. function initScrollbars(cm) {
  3122. if (cm.display.scrollbars) {
  3123. cm.display.scrollbars.clear()
  3124. if (cm.display.scrollbars.addClass)
  3125. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3126. }
  3127. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3128. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  3129. // Prevent clicks in the scrollbars from killing focus
  3130. on(node, "mousedown", function () {
  3131. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
  3132. })
  3133. node.setAttribute("cm-not-content", "true")
  3134. }, function (pos, axis) {
  3135. if (axis == "horizontal") { setScrollLeft(cm, pos) }
  3136. else { setScrollTop(cm, pos) }
  3137. }, cm)
  3138. if (cm.display.scrollbars.addClass)
  3139. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3140. }
  3141. // SCROLLING THINGS INTO VIEW
  3142. // If an editor sits on the top or bottom of the window, partially
  3143. // scrolled out of view, this ensures that the cursor is visible.
  3144. function maybeScrollWindow(cm, coords) {
  3145. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3146. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
  3147. if (coords.top + box.top < 0) { doScroll = true }
  3148. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
  3149. if (doScroll != null && !phantom) {
  3150. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (coords.left) + "px; width: 2px;"))
  3151. cm.display.lineSpace.appendChild(scrollNode)
  3152. scrollNode.scrollIntoView(doScroll)
  3153. cm.display.lineSpace.removeChild(scrollNode)
  3154. }
  3155. }
  3156. // Scroll a given position into view (immediately), verifying that
  3157. // it actually became visible (as line heights are accurately
  3158. // measured, the position of something may 'drift' during drawing).
  3159. function scrollPosIntoView(cm, pos, end, margin) {
  3160. if (margin == null) { margin = 0 }
  3161. var coords
  3162. for (var limit = 0; limit < 5; limit++) {
  3163. var changed = false
  3164. coords = cursorCoords(cm, pos)
  3165. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  3166. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  3167. Math.min(coords.top, endCoords.top) - margin,
  3168. Math.max(coords.left, endCoords.left),
  3169. Math.max(coords.bottom, endCoords.bottom) + margin)
  3170. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
  3171. if (scrollPos.scrollTop != null) {
  3172. setScrollTop(cm, scrollPos.scrollTop)
  3173. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
  3174. }
  3175. if (scrollPos.scrollLeft != null) {
  3176. setScrollLeft(cm, scrollPos.scrollLeft)
  3177. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
  3178. }
  3179. if (!changed) { break }
  3180. }
  3181. return coords
  3182. }
  3183. // Scroll a given set of coordinates into view (immediately).
  3184. function scrollIntoView(cm, x1, y1, x2, y2) {
  3185. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2)
  3186. if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop) }
  3187. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
  3188. }
  3189. // Calculate a new scroll position needed to scroll the given
  3190. // rectangle into view. Returns an object with scrollTop and
  3191. // scrollLeft properties. When these are undefined, the
  3192. // vertical/horizontal position does not need to be adjusted.
  3193. function calculateScrollPos(cm, x1, y1, x2, y2) {
  3194. var display = cm.display, snapMargin = textHeight(cm.display)
  3195. if (y1 < 0) { y1 = 0 }
  3196. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  3197. var screen = displayHeight(cm), result = {}
  3198. if (y2 - y1 > screen) { y2 = y1 + screen }
  3199. var docBottom = cm.doc.height + paddingVert(display)
  3200. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin
  3201. if (y1 < screentop) {
  3202. result.scrollTop = atTop ? 0 : y1
  3203. } else if (y2 > screentop + screen) {
  3204. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen)
  3205. if (newTop != screentop) { result.scrollTop = newTop }
  3206. }
  3207. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
  3208. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
  3209. var tooWide = x2 - x1 > screenw
  3210. if (tooWide) { x2 = x1 + screenw }
  3211. if (x1 < 10)
  3212. { result.scrollLeft = 0 }
  3213. else if (x1 < screenleft)
  3214. { result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)) }
  3215. else if (x2 > screenw + screenleft - 3)
  3216. { result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw }
  3217. return result
  3218. }
  3219. // Store a relative adjustment to the scroll position in the current
  3220. // operation (to be applied when the operation finishes).
  3221. function addToScrollPos(cm, left, top) {
  3222. if (left != null || top != null) { resolveScrollToPos(cm) }
  3223. if (left != null)
  3224. { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left }
  3225. if (top != null)
  3226. { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top }
  3227. }
  3228. // Make sure that at the end of the operation the current cursor is
  3229. // shown.
  3230. function ensureCursorVisible(cm) {
  3231. resolveScrollToPos(cm)
  3232. var cur = cm.getCursor(), from = cur, to = cur
  3233. if (!cm.options.lineWrapping) {
  3234. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur
  3235. to = Pos(cur.line, cur.ch + 1)
  3236. }
  3237. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}
  3238. }
  3239. // When an operation has its scrollToPos property set, and another
  3240. // scroll action is applied before the end of the operation, this
  3241. // 'simulates' scrolling that position into view in a cheap way, so
  3242. // that the effect of intermediate scroll commands is not ignored.
  3243. function resolveScrollToPos(cm) {
  3244. var range = cm.curOp.scrollToPos
  3245. if (range) {
  3246. cm.curOp.scrollToPos = null
  3247. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)
  3248. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  3249. Math.min(from.top, to.top) - range.margin,
  3250. Math.max(from.right, to.right),
  3251. Math.max(from.bottom, to.bottom) + range.margin)
  3252. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop)
  3253. }
  3254. }
  3255. // Operations are used to wrap a series of changes to the editor
  3256. // state in such a way that each change won't have to update the
  3257. // cursor and display (which would be awkward, slow, and
  3258. // error-prone). Instead, display updates are batched and then all
  3259. // combined and executed at once.
  3260. var nextOpId = 0
  3261. // Start a new operation.
  3262. function startOperation(cm) {
  3263. cm.curOp = {
  3264. cm: cm,
  3265. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3266. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3267. forceUpdate: false, // Used to force a redraw
  3268. updateInput: null, // Whether to reset the input textarea
  3269. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3270. changeObjs: null, // Accumulated changes, for firing change events
  3271. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3272. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3273. selectionChanged: false, // Whether the selection needs to be redrawn
  3274. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3275. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3276. scrollToPos: null, // Used to scroll to a specific position
  3277. focus: false,
  3278. id: ++nextOpId // Unique ID
  3279. }
  3280. pushOperation(cm.curOp)
  3281. }
  3282. // Finish an operation, updating the display and signalling delayed events
  3283. function endOperation(cm) {
  3284. var op = cm.curOp
  3285. finishOperation(op, function (group) {
  3286. for (var i = 0; i < group.ops.length; i++)
  3287. { group.ops[i].cm.curOp = null }
  3288. endOperations(group)
  3289. })
  3290. }
  3291. // The DOM updates done when an operation finishes are batched so
  3292. // that the minimum number of relayouts are required.
  3293. function endOperations(group) {
  3294. var ops = group.ops
  3295. for (var i = 0; i < ops.length; i++) // Read DOM
  3296. { endOperation_R1(ops[i]) }
  3297. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3298. { endOperation_W1(ops[i$1]) }
  3299. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3300. { endOperation_R2(ops[i$2]) }
  3301. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3302. { endOperation_W2(ops[i$3]) }
  3303. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3304. { endOperation_finish(ops[i$4]) }
  3305. }
  3306. function endOperation_R1(op) {
  3307. var cm = op.cm, display = cm.display
  3308. maybeClipScrollbars(cm)
  3309. if (op.updateMaxLine) { findMaxLine(cm) }
  3310. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3311. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3312. op.scrollToPos.to.line >= display.viewTo) ||
  3313. display.maxLineChanged && cm.options.lineWrapping
  3314. op.update = op.mustUpdate &&
  3315. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
  3316. }
  3317. function endOperation_W1(op) {
  3318. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  3319. }
  3320. function endOperation_R2(op) {
  3321. var cm = op.cm, display = cm.display
  3322. if (op.updatedDisplay) { updateHeightsInViewport(cm) }
  3323. op.barMeasure = measureForScrollbars(cm)
  3324. // If the max line changed since it was last measured, measure it,
  3325. // and ensure the document's width matches it.
  3326. // updateDisplay_W2 will use these properties to do the actual resizing
  3327. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3328. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  3329. cm.display.sizerWidth = op.adjustWidthTo
  3330. op.barMeasure.scrollWidth =
  3331. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  3332. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  3333. }
  3334. if (op.updatedDisplay || op.selectionChanged)
  3335. { op.preparedSelection = display.input.prepareSelection(op.focus) }
  3336. }
  3337. function endOperation_W2(op) {
  3338. var cm = op.cm
  3339. if (op.adjustWidthTo != null) {
  3340. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
  3341. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3342. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
  3343. cm.display.maxLineChanged = false
  3344. }
  3345. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  3346. if (op.preparedSelection)
  3347. { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
  3348. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3349. { updateScrollbars(cm, op.barMeasure) }
  3350. if (op.updatedDisplay)
  3351. { setDocumentHeight(cm, op.barMeasure) }
  3352. if (op.selectionChanged) { restartBlink(cm) }
  3353. if (cm.state.focused && op.updateInput)
  3354. { cm.display.input.reset(op.typing) }
  3355. if (takeFocus) { ensureFocus(op.cm) }
  3356. }
  3357. function endOperation_finish(op) {
  3358. var cm = op.cm, display = cm.display, doc = cm.doc
  3359. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
  3360. // Abort mouse wheel delta measurement, when scrolling explicitly
  3361. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3362. { display.wheelStartX = display.wheelStartY = null }
  3363. // Propagate the scroll position to the actual DOM scroller
  3364. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  3365. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop))
  3366. display.scrollbars.setScrollTop(doc.scrollTop)
  3367. display.scroller.scrollTop = doc.scrollTop
  3368. }
  3369. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  3370. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft))
  3371. display.scrollbars.setScrollLeft(doc.scrollLeft)
  3372. display.scroller.scrollLeft = doc.scrollLeft
  3373. alignHorizontally(cm)
  3374. }
  3375. // If we need to scroll a specific position into view, do so.
  3376. if (op.scrollToPos) {
  3377. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3378. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  3379. if (op.scrollToPos.isCursor && cm.state.focused) { maybeScrollWindow(cm, coords) }
  3380. }
  3381. // Fire events for markers that are hidden/unidden by editing or
  3382. // undoing
  3383. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  3384. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3385. { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
  3386. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3387. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
  3388. if (display.wrapper.offsetHeight)
  3389. { doc.scrollTop = cm.display.scroller.scrollTop }
  3390. // Fire change events, and delayed event handlers
  3391. if (op.changeObjs)
  3392. { signal(cm, "changes", cm, op.changeObjs) }
  3393. if (op.update)
  3394. { op.update.finish() }
  3395. }
  3396. // Run the given function in an operation
  3397. function runInOp(cm, f) {
  3398. if (cm.curOp) { return f() }
  3399. startOperation(cm)
  3400. try { return f() }
  3401. finally { endOperation(cm) }
  3402. }
  3403. // Wraps a function in an operation. Returns the wrapped function.
  3404. function operation(cm, f) {
  3405. return function() {
  3406. if (cm.curOp) { return f.apply(cm, arguments) }
  3407. startOperation(cm)
  3408. try { return f.apply(cm, arguments) }
  3409. finally { endOperation(cm) }
  3410. }
  3411. }
  3412. // Used to add methods to editor and doc instances, wrapping them in
  3413. // operations.
  3414. function methodOp(f) {
  3415. return function() {
  3416. if (this.curOp) { return f.apply(this, arguments) }
  3417. startOperation(this)
  3418. try { return f.apply(this, arguments) }
  3419. finally { endOperation(this) }
  3420. }
  3421. }
  3422. function docMethodOp(f) {
  3423. return function() {
  3424. var cm = this.cm
  3425. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3426. startOperation(cm)
  3427. try { return f.apply(this, arguments) }
  3428. finally { endOperation(cm) }
  3429. }
  3430. }
  3431. // Updates the display.view data structure for a given change to the
  3432. // document. From and to are in pre-change coordinates. Lendiff is
  3433. // the amount of lines added or subtracted by the change. This is
  3434. // used for changes that span multiple lines, or change the way
  3435. // lines are divided into visual lines. regLineChange (below)
  3436. // registers single-line changes.
  3437. function regChange(cm, from, to, lendiff) {
  3438. if (from == null) { from = cm.doc.first }
  3439. if (to == null) { to = cm.doc.first + cm.doc.size }
  3440. if (!lendiff) { lendiff = 0 }
  3441. var display = cm.display
  3442. if (lendiff && to < display.viewTo &&
  3443. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3444. { display.updateLineNumbers = from }
  3445. cm.curOp.viewChanged = true
  3446. if (from >= display.viewTo) { // Change after
  3447. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3448. { resetView(cm) }
  3449. } else if (to <= display.viewFrom) { // Change before
  3450. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3451. resetView(cm)
  3452. } else {
  3453. display.viewFrom += lendiff
  3454. display.viewTo += lendiff
  3455. }
  3456. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3457. resetView(cm)
  3458. } else if (from <= display.viewFrom) { // Top overlap
  3459. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3460. if (cut) {
  3461. display.view = display.view.slice(cut.index)
  3462. display.viewFrom = cut.lineN
  3463. display.viewTo += lendiff
  3464. } else {
  3465. resetView(cm)
  3466. }
  3467. } else if (to >= display.viewTo) { // Bottom overlap
  3468. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3469. if (cut$1) {
  3470. display.view = display.view.slice(0, cut$1.index)
  3471. display.viewTo = cut$1.lineN
  3472. } else {
  3473. resetView(cm)
  3474. }
  3475. } else { // Gap in the middle
  3476. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3477. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3478. if (cutTop && cutBot) {
  3479. display.view = display.view.slice(0, cutTop.index)
  3480. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3481. .concat(display.view.slice(cutBot.index))
  3482. display.viewTo += lendiff
  3483. } else {
  3484. resetView(cm)
  3485. }
  3486. }
  3487. var ext = display.externalMeasured
  3488. if (ext) {
  3489. if (to < ext.lineN)
  3490. { ext.lineN += lendiff }
  3491. else if (from < ext.lineN + ext.size)
  3492. { display.externalMeasured = null }
  3493. }
  3494. }
  3495. // Register a change to a single line. Type must be one of "text",
  3496. // "gutter", "class", "widget"
  3497. function regLineChange(cm, line, type) {
  3498. cm.curOp.viewChanged = true
  3499. var display = cm.display, ext = cm.display.externalMeasured
  3500. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3501. { display.externalMeasured = null }
  3502. if (line < display.viewFrom || line >= display.viewTo) { return }
  3503. var lineView = display.view[findViewIndex(cm, line)]
  3504. if (lineView.node == null) { return }
  3505. var arr = lineView.changes || (lineView.changes = [])
  3506. if (indexOf(arr, type) == -1) { arr.push(type) }
  3507. }
  3508. // Clear the view.
  3509. function resetView(cm) {
  3510. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3511. cm.display.view = []
  3512. cm.display.viewOffset = 0
  3513. }
  3514. function viewCuttingPoint(cm, oldN, newN, dir) {
  3515. var index = findViewIndex(cm, oldN), diff, view = cm.display.view
  3516. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3517. { return {index: index, lineN: newN} }
  3518. var n = cm.display.viewFrom
  3519. for (var i = 0; i < index; i++)
  3520. { n += view[i].size }
  3521. if (n != oldN) {
  3522. if (dir > 0) {
  3523. if (index == view.length - 1) { return null }
  3524. diff = (n + view[index].size) - oldN
  3525. index++
  3526. } else {
  3527. diff = n - oldN
  3528. }
  3529. oldN += diff; newN += diff
  3530. }
  3531. while (visualLineNo(cm.doc, newN) != newN) {
  3532. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3533. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3534. index += dir
  3535. }
  3536. return {index: index, lineN: newN}
  3537. }
  3538. // Force the view to cover a given range, adding empty view element
  3539. // or clipping off existing ones as needed.
  3540. function adjustView(cm, from, to) {
  3541. var display = cm.display, view = display.view
  3542. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3543. display.view = buildViewArray(cm, from, to)
  3544. display.viewFrom = from
  3545. } else {
  3546. if (display.viewFrom > from)
  3547. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
  3548. else if (display.viewFrom < from)
  3549. { display.view = display.view.slice(findViewIndex(cm, from)) }
  3550. display.viewFrom = from
  3551. if (display.viewTo < to)
  3552. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
  3553. else if (display.viewTo > to)
  3554. { display.view = display.view.slice(0, findViewIndex(cm, to)) }
  3555. }
  3556. display.viewTo = to
  3557. }
  3558. // Count the number of lines in the view whose DOM representation is
  3559. // out of date (or nonexistent).
  3560. function countDirtyView(cm) {
  3561. var view = cm.display.view, dirty = 0
  3562. for (var i = 0; i < view.length; i++) {
  3563. var lineView = view[i]
  3564. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
  3565. }
  3566. return dirty
  3567. }
  3568. // HIGHLIGHT WORKER
  3569. function startWorker(cm, time) {
  3570. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  3571. { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
  3572. }
  3573. function highlightWorker(cm) {
  3574. var doc = cm.doc
  3575. if (doc.frontier < doc.first) { doc.frontier = doc.first }
  3576. if (doc.frontier >= cm.display.viewTo) { return }
  3577. var end = +new Date + cm.options.workTime
  3578. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier))
  3579. var changedLines = []
  3580. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3581. if (doc.frontier >= cm.display.viewFrom) { // Visible
  3582. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength
  3583. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true)
  3584. line.styles = highlighted.styles
  3585. var oldCls = line.styleClasses, newCls = highlighted.classes
  3586. if (newCls) { line.styleClasses = newCls }
  3587. else if (oldCls) { line.styleClasses = null }
  3588. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3589. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
  3590. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
  3591. if (ischange) { changedLines.push(doc.frontier) }
  3592. line.stateAfter = tooLong ? state : copyState(doc.mode, state)
  3593. } else {
  3594. if (line.text.length <= cm.options.maxHighlightLength)
  3595. { processLine(cm, line.text, state) }
  3596. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null
  3597. }
  3598. ++doc.frontier
  3599. if (+new Date > end) {
  3600. startWorker(cm, cm.options.workDelay)
  3601. return true
  3602. }
  3603. })
  3604. if (changedLines.length) { runInOp(cm, function () {
  3605. for (var i = 0; i < changedLines.length; i++)
  3606. { regLineChange(cm, changedLines[i], "text") }
  3607. }) }
  3608. }
  3609. // DISPLAY DRAWING
  3610. var DisplayUpdate = function(cm, viewport, force) {
  3611. var display = cm.display
  3612. this.viewport = viewport
  3613. // Store some values that we'll need later (but don't want to force a relayout for)
  3614. this.visible = visibleLines(display, cm.doc, viewport)
  3615. this.editorIsHidden = !display.wrapper.offsetWidth
  3616. this.wrapperHeight = display.wrapper.clientHeight
  3617. this.wrapperWidth = display.wrapper.clientWidth
  3618. this.oldDisplayWidth = displayWidth(cm)
  3619. this.force = force
  3620. this.dims = getDimensions(cm)
  3621. this.events = []
  3622. };
  3623. DisplayUpdate.prototype.signal = function (emitter, type) {
  3624. if (hasHandler(emitter, type))
  3625. { this.events.push(arguments) }
  3626. };
  3627. DisplayUpdate.prototype.finish = function () {
  3628. var this$1 = this;
  3629. for (var i = 0; i < this.events.length; i++)
  3630. { signal.apply(null, this$1.events[i]) }
  3631. };
  3632. function maybeClipScrollbars(cm) {
  3633. var display = cm.display
  3634. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3635. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  3636. display.heightForcer.style.height = scrollGap(cm) + "px"
  3637. display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
  3638. display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
  3639. display.scrollbarsClipped = true
  3640. }
  3641. }
  3642. // Does the actual updating of the line display. Bails out
  3643. // (returning false) when there is nothing to be done and forced is
  3644. // false.
  3645. function updateDisplayIfNeeded(cm, update) {
  3646. var display = cm.display, doc = cm.doc
  3647. if (update.editorIsHidden) {
  3648. resetView(cm)
  3649. return false
  3650. }
  3651. // Bail out if the visible area is already rendered and nothing changed.
  3652. if (!update.force &&
  3653. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3654. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3655. display.renderedView == display.view && countDirtyView(cm) == 0)
  3656. { return false }
  3657. if (maybeUpdateLineNumberWidth(cm)) {
  3658. resetView(cm)
  3659. update.dims = getDimensions(cm)
  3660. }
  3661. // Compute a suitable new viewport (from & to)
  3662. var end = doc.first + doc.size
  3663. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  3664. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  3665. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) }
  3666. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) }
  3667. if (sawCollapsedSpans) {
  3668. from = visualLineNo(cm.doc, from)
  3669. to = visualLineEndNo(cm.doc, to)
  3670. }
  3671. var different = from != display.viewFrom || to != display.viewTo ||
  3672. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  3673. adjustView(cm, from, to)
  3674. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  3675. // Position the mover div to align with the current scroll position
  3676. cm.display.mover.style.top = display.viewOffset + "px"
  3677. var toUpdate = countDirtyView(cm)
  3678. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3679. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3680. { return false }
  3681. // For big changes, we hide the enclosing element during the
  3682. // update, since that speeds up the operations on most browsers.
  3683. var focused = activeElt()
  3684. if (toUpdate > 4) { display.lineDiv.style.display = "none" }
  3685. patchDisplay(cm, display.updateLineNumbers, update.dims)
  3686. if (toUpdate > 4) { display.lineDiv.style.display = "" }
  3687. display.renderedView = display.view
  3688. // There might have been a widget with a focused element that got
  3689. // hidden or updated, if so re-focus it.
  3690. if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus() }
  3691. // Prevent selection and cursors from interfering with the scroll
  3692. // width and height.
  3693. removeChildren(display.cursorDiv)
  3694. removeChildren(display.selectionDiv)
  3695. display.gutters.style.height = display.sizer.style.minHeight = 0
  3696. if (different) {
  3697. display.lastWrapHeight = update.wrapperHeight
  3698. display.lastWrapWidth = update.wrapperWidth
  3699. startWorker(cm, 400)
  3700. }
  3701. display.updateLineNumbers = null
  3702. return true
  3703. }
  3704. function postUpdateDisplay(cm, update) {
  3705. var viewport = update.viewport
  3706. for (var first = true;; first = false) {
  3707. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3708. // Clip forced viewport to actual scrollable area.
  3709. if (viewport && viewport.top != null)
  3710. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
  3711. // Updated line heights might result in the drawn area not
  3712. // actually covering the viewport. Keep looping until it does.
  3713. update.visible = visibleLines(cm.display, cm.doc, viewport)
  3714. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3715. { break }
  3716. }
  3717. if (!updateDisplayIfNeeded(cm, update)) { break }
  3718. updateHeightsInViewport(cm)
  3719. var barMeasure = measureForScrollbars(cm)
  3720. updateSelection(cm)
  3721. updateScrollbars(cm, barMeasure)
  3722. setDocumentHeight(cm, barMeasure)
  3723. }
  3724. update.signal(cm, "update", cm)
  3725. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3726. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
  3727. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
  3728. }
  3729. }
  3730. function updateDisplaySimple(cm, viewport) {
  3731. var update = new DisplayUpdate(cm, viewport)
  3732. if (updateDisplayIfNeeded(cm, update)) {
  3733. updateHeightsInViewport(cm)
  3734. postUpdateDisplay(cm, update)
  3735. var barMeasure = measureForScrollbars(cm)
  3736. updateSelection(cm)
  3737. updateScrollbars(cm, barMeasure)
  3738. setDocumentHeight(cm, barMeasure)
  3739. update.finish()
  3740. }
  3741. }
  3742. // Sync the actual display DOM structure with display.view, removing
  3743. // nodes for lines that are no longer in view, and creating the ones
  3744. // that are not there yet, and updating the ones that are out of
  3745. // date.
  3746. function patchDisplay(cm, updateNumbersFrom, dims) {
  3747. var display = cm.display, lineNumbers = cm.options.lineNumbers
  3748. var container = display.lineDiv, cur = container.firstChild
  3749. function rm(node) {
  3750. var next = node.nextSibling
  3751. // Works around a throw-scroll bug in OS X Webkit
  3752. if (webkit && mac && cm.display.currentWheelTarget == node)
  3753. { node.style.display = "none" }
  3754. else
  3755. { node.parentNode.removeChild(node) }
  3756. return next
  3757. }
  3758. var view = display.view, lineN = display.viewFrom
  3759. // Loop over the elements in the view, syncing cur (the DOM nodes
  3760. // in display.lineDiv) with the view as we go.
  3761. for (var i = 0; i < view.length; i++) {
  3762. var lineView = view[i]
  3763. if (lineView.hidden) {
  3764. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3765. var node = buildLineElement(cm, lineView, lineN, dims)
  3766. container.insertBefore(node, cur)
  3767. } else { // Already drawn
  3768. while (cur != lineView.node) { cur = rm(cur) }
  3769. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3770. updateNumbersFrom <= lineN && lineView.lineNumber
  3771. if (lineView.changes) {
  3772. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
  3773. updateLineForChanges(cm, lineView, lineN, dims)
  3774. }
  3775. if (updateNumber) {
  3776. removeChildren(lineView.lineNumber)
  3777. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  3778. }
  3779. cur = lineView.node.nextSibling
  3780. }
  3781. lineN += lineView.size
  3782. }
  3783. while (cur) { cur = rm(cur) }
  3784. }
  3785. function updateGutterSpace(cm) {
  3786. var width = cm.display.gutters.offsetWidth
  3787. cm.display.sizer.style.marginLeft = width + "px"
  3788. }
  3789. function setDocumentHeight(cm, measure) {
  3790. cm.display.sizer.style.minHeight = measure.docHeight + "px"
  3791. cm.display.heightForcer.style.top = measure.docHeight + "px"
  3792. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
  3793. }
  3794. // Rebuild the gutter elements, ensure the margin to the left of the
  3795. // code matches their width.
  3796. function updateGutters(cm) {
  3797. var gutters = cm.display.gutters, specs = cm.options.gutters
  3798. removeChildren(gutters)
  3799. var i = 0
  3800. for (; i < specs.length; ++i) {
  3801. var gutterClass = specs[i]
  3802. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
  3803. if (gutterClass == "CodeMirror-linenumbers") {
  3804. cm.display.lineGutter = gElt
  3805. gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
  3806. }
  3807. }
  3808. gutters.style.display = i ? "" : "none"
  3809. updateGutterSpace(cm)
  3810. }
  3811. // Make sure the gutters options contains the element
  3812. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3813. function setGuttersForLineNumbers(options) {
  3814. var found = indexOf(options.gutters, "CodeMirror-linenumbers")
  3815. if (found == -1 && options.lineNumbers) {
  3816. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
  3817. } else if (found > -1 && !options.lineNumbers) {
  3818. options.gutters = options.gutters.slice(0)
  3819. options.gutters.splice(found, 1)
  3820. }
  3821. }
  3822. // Selection objects are immutable. A new one is created every time
  3823. // the selection changes. A selection is one or more non-overlapping
  3824. // (and non-touching) ranges, sorted, and an integer that indicates
  3825. // which one is the primary selection (the one that's scrolled into
  3826. // view, that getCursor returns, etc).
  3827. function Selection(ranges, primIndex) {
  3828. this.ranges = ranges
  3829. this.primIndex = primIndex
  3830. }
  3831. Selection.prototype = {
  3832. primary: function() { return this.ranges[this.primIndex] },
  3833. equals: function(other) {
  3834. var this$1 = this;
  3835. if (other == this) { return true }
  3836. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  3837. for (var i = 0; i < this.ranges.length; i++) {
  3838. var here = this$1.ranges[i], there = other.ranges[i]
  3839. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) { return false }
  3840. }
  3841. return true
  3842. },
  3843. deepCopy: function() {
  3844. var this$1 = this;
  3845. var out = []
  3846. for (var i = 0; i < this.ranges.length; i++)
  3847. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
  3848. return new Selection(out, this.primIndex)
  3849. },
  3850. somethingSelected: function() {
  3851. var this$1 = this;
  3852. for (var i = 0; i < this.ranges.length; i++)
  3853. { if (!this$1.ranges[i].empty()) { return true } }
  3854. return false
  3855. },
  3856. contains: function(pos, end) {
  3857. var this$1 = this;
  3858. if (!end) { end = pos }
  3859. for (var i = 0; i < this.ranges.length; i++) {
  3860. var range = this$1.ranges[i]
  3861. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  3862. { return i }
  3863. }
  3864. return -1
  3865. }
  3866. }
  3867. function Range(anchor, head) {
  3868. this.anchor = anchor; this.head = head
  3869. }
  3870. Range.prototype = {
  3871. from: function() { return minPos(this.anchor, this.head) },
  3872. to: function() { return maxPos(this.anchor, this.head) },
  3873. empty: function() {
  3874. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch
  3875. }
  3876. }
  3877. // Take an unsorted, potentially overlapping set of ranges, and
  3878. // build a selection out of it. 'Consumes' ranges array (modifying
  3879. // it).
  3880. function normalizeSelection(ranges, primIndex) {
  3881. var prim = ranges[primIndex]
  3882. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
  3883. primIndex = indexOf(ranges, prim)
  3884. for (var i = 1; i < ranges.length; i++) {
  3885. var cur = ranges[i], prev = ranges[i - 1]
  3886. if (cmp(prev.to(), cur.from()) >= 0) {
  3887. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
  3888. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  3889. if (i <= primIndex) { --primIndex }
  3890. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  3891. }
  3892. }
  3893. return new Selection(ranges, primIndex)
  3894. }
  3895. function simpleSelection(anchor, head) {
  3896. return new Selection([new Range(anchor, head || anchor)], 0)
  3897. }
  3898. // Compute the position of the end of a change (its 'to' property
  3899. // refers to the pre-change end).
  3900. function changeEnd(change) {
  3901. if (!change.text) { return change.to }
  3902. return Pos(change.from.line + change.text.length - 1,
  3903. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  3904. }
  3905. // Adjust a position to refer to the post-change position of the
  3906. // same text, or the end of the change if the change covers it.
  3907. function adjustForChange(pos, change) {
  3908. if (cmp(pos, change.from) < 0) { return pos }
  3909. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  3910. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
  3911. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
  3912. return Pos(line, ch)
  3913. }
  3914. function computeSelAfterChange(doc, change) {
  3915. var out = []
  3916. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3917. var range = doc.sel.ranges[i]
  3918. out.push(new Range(adjustForChange(range.anchor, change),
  3919. adjustForChange(range.head, change)))
  3920. }
  3921. return normalizeSelection(out, doc.sel.primIndex)
  3922. }
  3923. function offsetPos(pos, old, nw) {
  3924. if (pos.line == old.line)
  3925. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  3926. else
  3927. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  3928. }
  3929. // Used by replaceSelections to allow moving the selection to the
  3930. // start or around the replaced test. Hint may be "start" or "around".
  3931. function computeReplacedSel(doc, changes, hint) {
  3932. var out = []
  3933. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
  3934. for (var i = 0; i < changes.length; i++) {
  3935. var change = changes[i]
  3936. var from = offsetPos(change.from, oldPrev, newPrev)
  3937. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  3938. oldPrev = change.to
  3939. newPrev = to
  3940. if (hint == "around") {
  3941. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
  3942. out[i] = new Range(inv ? to : from, inv ? from : to)
  3943. } else {
  3944. out[i] = new Range(from, from)
  3945. }
  3946. }
  3947. return new Selection(out, doc.sel.primIndex)
  3948. }
  3949. // Used to get the editor into a consistent state again when options change.
  3950. function loadMode(cm) {
  3951. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  3952. resetModeState(cm)
  3953. }
  3954. function resetModeState(cm) {
  3955. cm.doc.iter(function (line) {
  3956. if (line.stateAfter) { line.stateAfter = null }
  3957. if (line.styles) { line.styles = null }
  3958. })
  3959. cm.doc.frontier = cm.doc.first
  3960. startWorker(cm, 100)
  3961. cm.state.modeGen++
  3962. if (cm.curOp) { regChange(cm) }
  3963. }
  3964. // DOCUMENT DATA STRUCTURE
  3965. // By default, updates that start and end at the beginning of a line
  3966. // are treated specially, in order to make the association of line
  3967. // widgets and marker elements with the text behave more intuitive.
  3968. function isWholeLineUpdate(doc, change) {
  3969. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  3970. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  3971. }
  3972. // Perform a change on the document data structure.
  3973. function updateDoc(doc, change, markedSpans, estimateHeight) {
  3974. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  3975. function update(line, text, spans) {
  3976. updateLine(line, text, spans, estimateHeight)
  3977. signalLater(line, "change", line, change)
  3978. }
  3979. function linesFor(start, end) {
  3980. var result = []
  3981. for (var i = start; i < end; ++i)
  3982. { result.push(new Line(text[i], spansFor(i), estimateHeight)) }
  3983. return result
  3984. }
  3985. var from = change.from, to = change.to, text = change.text
  3986. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  3987. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
  3988. // Adjust the line structure
  3989. if (change.full) {
  3990. doc.insert(0, linesFor(0, text.length))
  3991. doc.remove(text.length, doc.size - text.length)
  3992. } else if (isWholeLineUpdate(doc, change)) {
  3993. // This is a whole-line replace. Treated specially to make
  3994. // sure line objects move the way they are supposed to.
  3995. var added = linesFor(0, text.length - 1)
  3996. update(lastLine, lastLine.text, lastSpans)
  3997. if (nlines) { doc.remove(from.line, nlines) }
  3998. if (added.length) { doc.insert(from.line, added) }
  3999. } else if (firstLine == lastLine) {
  4000. if (text.length == 1) {
  4001. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  4002. } else {
  4003. var added$1 = linesFor(1, text.length - 1)
  4004. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
  4005. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4006. doc.insert(from.line + 1, added$1)
  4007. }
  4008. } else if (text.length == 1) {
  4009. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  4010. doc.remove(from.line + 1, nlines)
  4011. } else {
  4012. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4013. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  4014. var added$2 = linesFor(1, text.length - 1)
  4015. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) }
  4016. doc.insert(from.line + 1, added$2)
  4017. }
  4018. signalLater(doc, "change", doc, change)
  4019. }
  4020. // Call f for all linked documents.
  4021. function linkedDocs(doc, f, sharedHistOnly) {
  4022. function propagate(doc, skip, sharedHist) {
  4023. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4024. var rel = doc.linked[i]
  4025. if (rel.doc == skip) { continue }
  4026. var shared = sharedHist && rel.sharedHist
  4027. if (sharedHistOnly && !shared) { continue }
  4028. f(rel.doc, shared)
  4029. propagate(rel.doc, doc, shared)
  4030. } }
  4031. }
  4032. propagate(doc, null, true)
  4033. }
  4034. // Attach a document to an editor.
  4035. function attachDoc(cm, doc) {
  4036. if (doc.cm) { throw new Error("This document is already in use.") }
  4037. cm.doc = doc
  4038. doc.cm = cm
  4039. estimateLineHeights(cm)
  4040. loadMode(cm)
  4041. if (!cm.options.lineWrapping) { findMaxLine(cm) }
  4042. cm.options.mode = doc.modeOption
  4043. regChange(cm)
  4044. }
  4045. function History(startGen) {
  4046. // Arrays of change events and selections. Doing something adds an
  4047. // event to done and clears undo. Undoing moves events from done
  4048. // to undone, redoing moves them in the other direction.
  4049. this.done = []; this.undone = []
  4050. this.undoDepth = Infinity
  4051. // Used to track when changes can be merged into a single undo
  4052. // event
  4053. this.lastModTime = this.lastSelTime = 0
  4054. this.lastOp = this.lastSelOp = null
  4055. this.lastOrigin = this.lastSelOrigin = null
  4056. // Used by the isClean() method
  4057. this.generation = this.maxGeneration = startGen || 1
  4058. }
  4059. // Create a history change event from an updateDoc-style change
  4060. // object.
  4061. function historyChangeFromChange(doc, change) {
  4062. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
  4063. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  4064. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
  4065. return histChange
  4066. }
  4067. // Pop all selection events off the end of a history array. Stop at
  4068. // a change event.
  4069. function clearSelectionEvents(array) {
  4070. while (array.length) {
  4071. var last = lst(array)
  4072. if (last.ranges) { array.pop() }
  4073. else { break }
  4074. }
  4075. }
  4076. // Find the top change event in the history. Pop off selection
  4077. // events that are in the way.
  4078. function lastChangeEvent(hist, force) {
  4079. if (force) {
  4080. clearSelectionEvents(hist.done)
  4081. return lst(hist.done)
  4082. } else if (hist.done.length && !lst(hist.done).ranges) {
  4083. return lst(hist.done)
  4084. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4085. hist.done.pop()
  4086. return lst(hist.done)
  4087. }
  4088. }
  4089. // Register a change in the history. Merges changes that are within
  4090. // a single operation, or are close together with an origin that
  4091. // allows merging (starting with "+") into a single event.
  4092. function addChangeToHistory(doc, change, selAfter, opId) {
  4093. var hist = doc.history
  4094. hist.undone.length = 0
  4095. var time = +new Date, cur
  4096. var last
  4097. if ((hist.lastOp == opId ||
  4098. hist.lastOrigin == change.origin && change.origin &&
  4099. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  4100. change.origin.charAt(0) == "*")) &&
  4101. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4102. // Merge this change into the last event
  4103. last = lst(cur.changes)
  4104. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4105. // Optimized case for simple insertion -- don't want to add
  4106. // new changesets for every character typed
  4107. last.to = changeEnd(change)
  4108. } else {
  4109. // Add new sub-event
  4110. cur.changes.push(historyChangeFromChange(doc, change))
  4111. }
  4112. } else {
  4113. // Can not be merged, start a new event.
  4114. var before = lst(hist.done)
  4115. if (!before || !before.ranges)
  4116. { pushSelectionToHistory(doc.sel, hist.done) }
  4117. cur = {changes: [historyChangeFromChange(doc, change)],
  4118. generation: hist.generation}
  4119. hist.done.push(cur)
  4120. while (hist.done.length > hist.undoDepth) {
  4121. hist.done.shift()
  4122. if (!hist.done[0].ranges) { hist.done.shift() }
  4123. }
  4124. }
  4125. hist.done.push(selAfter)
  4126. hist.generation = ++hist.maxGeneration
  4127. hist.lastModTime = hist.lastSelTime = time
  4128. hist.lastOp = hist.lastSelOp = opId
  4129. hist.lastOrigin = hist.lastSelOrigin = change.origin
  4130. if (!last) { signal(doc, "historyAdded") }
  4131. }
  4132. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4133. var ch = origin.charAt(0)
  4134. return ch == "*" ||
  4135. ch == "+" &&
  4136. prev.ranges.length == sel.ranges.length &&
  4137. prev.somethingSelected() == sel.somethingSelected() &&
  4138. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4139. }
  4140. // Called whenever the selection changes, sets the new selection as
  4141. // the pending selection in the history, and pushes the old pending
  4142. // selection into the 'done' array when it was significantly
  4143. // different (in number of selected ranges, emptiness, or time).
  4144. function addSelectionToHistory(doc, sel, opId, options) {
  4145. var hist = doc.history, origin = options && options.origin
  4146. // A new event is started when the previous origin does not match
  4147. // the current, or the origins don't allow matching. Origins
  4148. // starting with * are always merged, those starting with + are
  4149. // merged when similar and close together in time.
  4150. if (opId == hist.lastSelOp ||
  4151. (origin && hist.lastSelOrigin == origin &&
  4152. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4153. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4154. { hist.done[hist.done.length - 1] = sel }
  4155. else
  4156. { pushSelectionToHistory(sel, hist.done) }
  4157. hist.lastSelTime = +new Date
  4158. hist.lastSelOrigin = origin
  4159. hist.lastSelOp = opId
  4160. if (options && options.clearRedo !== false)
  4161. { clearSelectionEvents(hist.undone) }
  4162. }
  4163. function pushSelectionToHistory(sel, dest) {
  4164. var top = lst(dest)
  4165. if (!(top && top.ranges && top.equals(sel)))
  4166. { dest.push(sel) }
  4167. }
  4168. // Used to store marked span information in the history.
  4169. function attachLocalSpans(doc, change, from, to) {
  4170. var existing = change["spans_" + doc.id], n = 0
  4171. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4172. if (line.markedSpans)
  4173. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans }
  4174. ++n
  4175. })
  4176. }
  4177. // When un/re-doing restores text containing marked spans, those
  4178. // that have been explicitly cleared should not be restored.
  4179. function removeClearedSpans(spans) {
  4180. if (!spans) { return null }
  4181. var out
  4182. for (var i = 0; i < spans.length; ++i) {
  4183. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
  4184. else if (out) { out.push(spans[i]) }
  4185. }
  4186. return !out ? spans : out.length ? out : null
  4187. }
  4188. // Retrieve and filter the old marked spans stored in a change event.
  4189. function getOldSpans(doc, change) {
  4190. var found = change["spans_" + doc.id]
  4191. if (!found) { return null }
  4192. var nw = []
  4193. for (var i = 0; i < change.text.length; ++i)
  4194. { nw.push(removeClearedSpans(found[i])) }
  4195. return nw
  4196. }
  4197. // Used for un/re-doing changes from the history. Combines the
  4198. // result of computing the existing spans with the set of spans that
  4199. // existed in the history (so that deleting around a span and then
  4200. // undoing brings back the span).
  4201. function mergeOldSpans(doc, change) {
  4202. var old = getOldSpans(doc, change)
  4203. var stretched = stretchSpansOverChange(doc, change)
  4204. if (!old) { return stretched }
  4205. if (!stretched) { return old }
  4206. for (var i = 0; i < old.length; ++i) {
  4207. var oldCur = old[i], stretchCur = stretched[i]
  4208. if (oldCur && stretchCur) {
  4209. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4210. var span = stretchCur[j]
  4211. for (var k = 0; k < oldCur.length; ++k)
  4212. { if (oldCur[k].marker == span.marker) { continue spans } }
  4213. oldCur.push(span)
  4214. }
  4215. } else if (stretchCur) {
  4216. old[i] = stretchCur
  4217. }
  4218. }
  4219. return old
  4220. }
  4221. // Used both to provide a JSON-safe object in .getHistory, and, when
  4222. // detaching a document, to split the history in two
  4223. function copyHistoryArray(events, newGroup, instantiateSel) {
  4224. var copy = []
  4225. for (var i = 0; i < events.length; ++i) {
  4226. var event = events[i]
  4227. if (event.ranges) {
  4228. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  4229. continue
  4230. }
  4231. var changes = event.changes, newChanges = []
  4232. copy.push({changes: newChanges})
  4233. for (var j = 0; j < changes.length; ++j) {
  4234. var change = changes[j], m = (void 0)
  4235. newChanges.push({from: change.from, to: change.to, text: change.text})
  4236. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4237. if (indexOf(newGroup, Number(m[1])) > -1) {
  4238. lst(newChanges)[prop] = change[prop]
  4239. delete change[prop]
  4240. }
  4241. } } }
  4242. }
  4243. }
  4244. return copy
  4245. }
  4246. // The 'scroll' parameter given to many of these indicated whether
  4247. // the new cursor position should be scrolled into view after
  4248. // modifying the selection.
  4249. // If shift is held or the extend flag is set, extends a range to
  4250. // include a given position (and optionally a second position).
  4251. // Otherwise, simply returns the range between the given positions.
  4252. // Used for cursor motion and such.
  4253. function extendRange(doc, range, head, other) {
  4254. if (doc.cm && doc.cm.display.shift || doc.extend) {
  4255. var anchor = range.anchor
  4256. if (other) {
  4257. var posBefore = cmp(head, anchor) < 0
  4258. if (posBefore != (cmp(other, anchor) < 0)) {
  4259. anchor = head
  4260. head = other
  4261. } else if (posBefore != (cmp(head, other) < 0)) {
  4262. head = other
  4263. }
  4264. }
  4265. return new Range(anchor, head)
  4266. } else {
  4267. return new Range(other || head, head)
  4268. }
  4269. }
  4270. // Extend the primary selection range, discard the rest.
  4271. function extendSelection(doc, head, other, options) {
  4272. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options)
  4273. }
  4274. // Extend all selections (pos is an array of selections with length
  4275. // equal the number of selections)
  4276. function extendSelections(doc, heads, options) {
  4277. var out = []
  4278. for (var i = 0; i < doc.sel.ranges.length; i++)
  4279. { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null) }
  4280. var newSel = normalizeSelection(out, doc.sel.primIndex)
  4281. setSelection(doc, newSel, options)
  4282. }
  4283. // Updates a single range in the selection.
  4284. function replaceOneSelection(doc, i, range, options) {
  4285. var ranges = doc.sel.ranges.slice(0)
  4286. ranges[i] = range
  4287. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
  4288. }
  4289. // Reset the selection to a single range.
  4290. function setSimpleSelection(doc, anchor, head, options) {
  4291. setSelection(doc, simpleSelection(anchor, head), options)
  4292. }
  4293. // Give beforeSelectionChange handlers a change to influence a
  4294. // selection update.
  4295. function filterSelectionChange(doc, sel, options) {
  4296. var obj = {
  4297. ranges: sel.ranges,
  4298. update: function(ranges) {
  4299. var this$1 = this;
  4300. this.ranges = []
  4301. for (var i = 0; i < ranges.length; i++)
  4302. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4303. clipPos(doc, ranges[i].head)) }
  4304. },
  4305. origin: options && options.origin
  4306. }
  4307. signal(doc, "beforeSelectionChange", doc, obj)
  4308. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
  4309. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4310. else { return sel }
  4311. }
  4312. function setSelectionReplaceHistory(doc, sel, options) {
  4313. var done = doc.history.done, last = lst(done)
  4314. if (last && last.ranges) {
  4315. done[done.length - 1] = sel
  4316. setSelectionNoUndo(doc, sel, options)
  4317. } else {
  4318. setSelection(doc, sel, options)
  4319. }
  4320. }
  4321. // Set a new selection.
  4322. function setSelection(doc, sel, options) {
  4323. setSelectionNoUndo(doc, sel, options)
  4324. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  4325. }
  4326. function setSelectionNoUndo(doc, sel, options) {
  4327. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4328. { sel = filterSelectionChange(doc, sel, options) }
  4329. var bias = options && options.bias ||
  4330. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  4331. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  4332. if (!(options && options.scroll === false) && doc.cm)
  4333. { ensureCursorVisible(doc.cm) }
  4334. }
  4335. function setSelectionInner(doc, sel) {
  4336. if (sel.equals(doc.sel)) { return }
  4337. doc.sel = sel
  4338. if (doc.cm) {
  4339. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
  4340. signalCursorActivity(doc.cm)
  4341. }
  4342. signalLater(doc, "cursorActivity", doc)
  4343. }
  4344. // Verify that the selection does not partially select any atomic
  4345. // marked ranges.
  4346. function reCheckSelection(doc) {
  4347. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll)
  4348. }
  4349. // Return a selection that does not partially select any atomic
  4350. // ranges.
  4351. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4352. var out
  4353. for (var i = 0; i < sel.ranges.length; i++) {
  4354. var range = sel.ranges[i]
  4355. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  4356. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  4357. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  4358. if (out || newAnchor != range.anchor || newHead != range.head) {
  4359. if (!out) { out = sel.ranges.slice(0, i) }
  4360. out[i] = new Range(newAnchor, newHead)
  4361. }
  4362. }
  4363. return out ? normalizeSelection(out, sel.primIndex) : sel
  4364. }
  4365. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4366. var line = getLine(doc, pos.line)
  4367. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4368. var sp = line.markedSpans[i], m = sp.marker
  4369. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4370. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4371. if (mayClear) {
  4372. signal(m, "beforeCursorEnter")
  4373. if (m.explicitlyCleared) {
  4374. if (!line.markedSpans) { break }
  4375. else {--i; continue}
  4376. }
  4377. }
  4378. if (!m.atomic) { continue }
  4379. if (oldPos) {
  4380. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0)
  4381. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4382. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
  4383. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4384. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4385. }
  4386. var far = m.find(dir < 0 ? -1 : 1)
  4387. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4388. { far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
  4389. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4390. }
  4391. } }
  4392. return pos
  4393. }
  4394. // Ensure a given position is not inside an atomic range.
  4395. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4396. var dir = bias || 1
  4397. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4398. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4399. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4400. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  4401. if (!found) {
  4402. doc.cantEdit = true
  4403. return Pos(doc.first, 0)
  4404. }
  4405. return found
  4406. }
  4407. function movePos(doc, pos, dir, line) {
  4408. if (dir < 0 && pos.ch == 0) {
  4409. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4410. else { return null }
  4411. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4412. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4413. else { return null }
  4414. } else {
  4415. return new Pos(pos.line, pos.ch + dir)
  4416. }
  4417. }
  4418. function selectAll(cm) {
  4419. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  4420. }
  4421. // UPDATING
  4422. // Allow "beforeChange" event handlers to influence a change
  4423. function filterChange(doc, change, update) {
  4424. var obj = {
  4425. canceled: false,
  4426. from: change.from,
  4427. to: change.to,
  4428. text: change.text,
  4429. origin: change.origin,
  4430. cancel: function () { return obj.canceled = true; }
  4431. }
  4432. if (update) { obj.update = function (from, to, text, origin) {
  4433. if (from) { obj.from = clipPos(doc, from) }
  4434. if (to) { obj.to = clipPos(doc, to) }
  4435. if (text) { obj.text = text }
  4436. if (origin !== undefined) { obj.origin = origin }
  4437. } }
  4438. signal(doc, "beforeChange", doc, obj)
  4439. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
  4440. if (obj.canceled) { return null }
  4441. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4442. }
  4443. // Apply a change to a document, and add it to the document's
  4444. // history, and propagating it to all linked documents.
  4445. function makeChange(doc, change, ignoreReadOnly) {
  4446. if (doc.cm) {
  4447. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4448. if (doc.cm.state.suppressEdits) { return }
  4449. }
  4450. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4451. change = filterChange(doc, change, true)
  4452. if (!change) { return }
  4453. }
  4454. // Possibly split or suppress the update based on the presence
  4455. // of read-only spans in its range.
  4456. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  4457. if (split) {
  4458. for (var i = split.length - 1; i >= 0; --i)
  4459. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}) }
  4460. } else {
  4461. makeChangeInner(doc, change)
  4462. }
  4463. }
  4464. function makeChangeInner(doc, change) {
  4465. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4466. var selAfter = computeSelAfterChange(doc, change)
  4467. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  4468. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  4469. var rebased = []
  4470. linkedDocs(doc, function (doc, sharedHist) {
  4471. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4472. rebaseHist(doc.history, change)
  4473. rebased.push(doc.history)
  4474. }
  4475. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  4476. })
  4477. }
  4478. // Revert a change stored in a document's history.
  4479. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4480. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  4481. var hist = doc.history, event, selAfter = doc.sel
  4482. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
  4483. // Verify that there is a useable event (so that ctrl-z won't
  4484. // needlessly clear selection events)
  4485. var i = 0
  4486. for (; i < source.length; i++) {
  4487. event = source[i]
  4488. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4489. { break }
  4490. }
  4491. if (i == source.length) { return }
  4492. hist.lastOrigin = hist.lastSelOrigin = null
  4493. for (;;) {
  4494. event = source.pop()
  4495. if (event.ranges) {
  4496. pushSelectionToHistory(event, dest)
  4497. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4498. setSelection(doc, event, {clearRedo: false})
  4499. return
  4500. }
  4501. selAfter = event
  4502. }
  4503. else { break }
  4504. }
  4505. // Build up a reverse change object to add to the opposite history
  4506. // stack (redo when undoing, and vice versa).
  4507. var antiChanges = []
  4508. pushSelectionToHistory(selAfter, dest)
  4509. dest.push({changes: antiChanges, generation: hist.generation})
  4510. hist.generation = event.generation || ++hist.maxGeneration
  4511. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
  4512. var loop = function ( i ) {
  4513. var change = event.changes[i]
  4514. change.origin = type
  4515. if (filter && !filterChange(doc, change, false)) {
  4516. source.length = 0
  4517. return {}
  4518. }
  4519. antiChanges.push(historyChangeFromChange(doc, change))
  4520. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  4521. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  4522. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
  4523. var rebased = []
  4524. // Propagate to the linked documents
  4525. linkedDocs(doc, function (doc, sharedHist) {
  4526. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4527. rebaseHist(doc.history, change)
  4528. rebased.push(doc.history)
  4529. }
  4530. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  4531. })
  4532. };
  4533. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4534. var returned = loop( i$1 );
  4535. if ( returned ) return returned.v;
  4536. }
  4537. }
  4538. // Sub-views need their line numbers shifted when text is added
  4539. // above or below them in the parent document.
  4540. function shiftDoc(doc, distance) {
  4541. if (distance == 0) { return }
  4542. doc.first += distance
  4543. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4544. Pos(range.anchor.line + distance, range.anchor.ch),
  4545. Pos(range.head.line + distance, range.head.ch)
  4546. ); }), doc.sel.primIndex)
  4547. if (doc.cm) {
  4548. regChange(doc.cm, doc.first, doc.first - distance, distance)
  4549. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4550. { regLineChange(doc.cm, l, "gutter") }
  4551. }
  4552. }
  4553. // More lower-level change function, handling only a single document
  4554. // (not linked ones).
  4555. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4556. if (doc.cm && !doc.cm.curOp)
  4557. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4558. if (change.to.line < doc.first) {
  4559. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  4560. return
  4561. }
  4562. if (change.from.line > doc.lastLine()) { return }
  4563. // Clip the change to the size of this doc
  4564. if (change.from.line < doc.first) {
  4565. var shift = change.text.length - 1 - (doc.first - change.from.line)
  4566. shiftDoc(doc, shift)
  4567. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4568. text: [lst(change.text)], origin: change.origin}
  4569. }
  4570. var last = doc.lastLine()
  4571. if (change.to.line > last) {
  4572. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4573. text: [change.text[0]], origin: change.origin}
  4574. }
  4575. change.removed = getBetween(doc, change.from, change.to)
  4576. if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
  4577. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
  4578. else { updateDoc(doc, change, spans) }
  4579. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  4580. }
  4581. // Handle the interaction of a change to a document with the editor
  4582. // that this document is part of.
  4583. function makeChangeSingleDocInEditor(cm, change, spans) {
  4584. var doc = cm.doc, display = cm.display, from = change.from, to = change.to
  4585. var recomputeMaxLength = false, checkWidthStart = from.line
  4586. if (!cm.options.lineWrapping) {
  4587. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  4588. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4589. if (line == display.maxLine) {
  4590. recomputeMaxLength = true
  4591. return true
  4592. }
  4593. })
  4594. }
  4595. if (doc.sel.contains(change.from, change.to) > -1)
  4596. { signalCursorActivity(cm) }
  4597. updateDoc(doc, change, spans, estimateHeight(cm))
  4598. if (!cm.options.lineWrapping) {
  4599. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4600. var len = lineLength(line)
  4601. if (len > display.maxLineLength) {
  4602. display.maxLine = line
  4603. display.maxLineLength = len
  4604. display.maxLineChanged = true
  4605. recomputeMaxLength = false
  4606. }
  4607. })
  4608. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
  4609. }
  4610. // Adjust frontier, schedule worker
  4611. doc.frontier = Math.min(doc.frontier, from.line)
  4612. startWorker(cm, 400)
  4613. var lendiff = change.text.length - (to.line - from.line) - 1
  4614. // Remember that these lines changed, for updating the display
  4615. if (change.full)
  4616. { regChange(cm) }
  4617. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4618. { regLineChange(cm, from.line, "text") }
  4619. else
  4620. { regChange(cm, from.line, to.line + 1, lendiff) }
  4621. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
  4622. if (changeHandler || changesHandler) {
  4623. var obj = {
  4624. from: from, to: to,
  4625. text: change.text,
  4626. removed: change.removed,
  4627. origin: change.origin
  4628. }
  4629. if (changeHandler) { signalLater(cm, "change", cm, obj) }
  4630. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
  4631. }
  4632. cm.display.selForContextMenu = null
  4633. }
  4634. function replaceRange(doc, code, from, to, origin) {
  4635. if (!to) { to = from }
  4636. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp }
  4637. if (typeof code == "string") { code = doc.splitLines(code) }
  4638. makeChange(doc, {from: from, to: to, text: code, origin: origin})
  4639. }
  4640. // Rebasing/resetting history to deal with externally-sourced changes
  4641. function rebaseHistSelSingle(pos, from, to, diff) {
  4642. if (to < pos.line) {
  4643. pos.line += diff
  4644. } else if (from < pos.line) {
  4645. pos.line = from
  4646. pos.ch = 0
  4647. }
  4648. }
  4649. // Tries to rebase an array of history events given a change in the
  4650. // document. If the change touches the same lines as the event, the
  4651. // event, and everything 'behind' it, is discarded. If the change is
  4652. // before the event, the event's positions are updated. Uses a
  4653. // copy-on-write scheme for the positions, to avoid having to
  4654. // reallocate them all on every rebase, but also avoid problems with
  4655. // shared position objects being unsafely updated.
  4656. function rebaseHistArray(array, from, to, diff) {
  4657. for (var i = 0; i < array.length; ++i) {
  4658. var sub = array[i], ok = true
  4659. if (sub.ranges) {
  4660. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
  4661. for (var j = 0; j < sub.ranges.length; j++) {
  4662. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  4663. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  4664. }
  4665. continue
  4666. }
  4667. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4668. var cur = sub.changes[j$1]
  4669. if (to < cur.from.line) {
  4670. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  4671. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  4672. } else if (from <= cur.to.line) {
  4673. ok = false
  4674. break
  4675. }
  4676. }
  4677. if (!ok) {
  4678. array.splice(0, i + 1)
  4679. i = 0
  4680. }
  4681. }
  4682. }
  4683. function rebaseHist(hist, change) {
  4684. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
  4685. rebaseHistArray(hist.done, from, to, diff)
  4686. rebaseHistArray(hist.undone, from, to, diff)
  4687. }
  4688. // Utility for applying a change to a line by handle or number,
  4689. // returning the number and optionally registering the line as
  4690. // changed.
  4691. function changeLine(doc, handle, changeType, op) {
  4692. var no = handle, line = handle
  4693. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
  4694. else { no = lineNo(handle) }
  4695. if (no == null) { return null }
  4696. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
  4697. return line
  4698. }
  4699. // The document is represented as a BTree consisting of leaves, with
  4700. // chunk of lines in them, and branches, with up to ten leaves or
  4701. // other branch nodes below them. The top node is always a branch
  4702. // node, and is the document object itself (meaning it has
  4703. // additional methods and properties).
  4704. //
  4705. // All nodes have parent links. The tree is used both to go from
  4706. // line numbers to line objects, and to go from objects to numbers.
  4707. // It also indexes by height, and is used to convert between height
  4708. // and line object, and to find the total height of the document.
  4709. //
  4710. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4711. function LeafChunk(lines) {
  4712. var this$1 = this;
  4713. this.lines = lines
  4714. this.parent = null
  4715. var height = 0
  4716. for (var i = 0; i < lines.length; ++i) {
  4717. lines[i].parent = this$1
  4718. height += lines[i].height
  4719. }
  4720. this.height = height
  4721. }
  4722. LeafChunk.prototype = {
  4723. chunkSize: function() { return this.lines.length },
  4724. // Remove the n lines at offset 'at'.
  4725. removeInner: function(at, n) {
  4726. var this$1 = this;
  4727. for (var i = at, e = at + n; i < e; ++i) {
  4728. var line = this$1.lines[i]
  4729. this$1.height -= line.height
  4730. cleanUpLine(line)
  4731. signalLater(line, "delete")
  4732. }
  4733. this.lines.splice(at, n)
  4734. },
  4735. // Helper used to collapse a small branch into a single leaf.
  4736. collapse: function(lines) {
  4737. lines.push.apply(lines, this.lines)
  4738. },
  4739. // Insert the given array of lines at offset 'at', count them as
  4740. // having the given height.
  4741. insertInner: function(at, lines, height) {
  4742. var this$1 = this;
  4743. this.height += height
  4744. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  4745. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
  4746. },
  4747. // Used to iterate over a part of the tree.
  4748. iterN: function(at, n, op) {
  4749. var this$1 = this;
  4750. for (var e = at + n; at < e; ++at)
  4751. { if (op(this$1.lines[at])) { return true } }
  4752. }
  4753. }
  4754. function BranchChunk(children) {
  4755. var this$1 = this;
  4756. this.children = children
  4757. var size = 0, height = 0
  4758. for (var i = 0; i < children.length; ++i) {
  4759. var ch = children[i]
  4760. size += ch.chunkSize(); height += ch.height
  4761. ch.parent = this$1
  4762. }
  4763. this.size = size
  4764. this.height = height
  4765. this.parent = null
  4766. }
  4767. BranchChunk.prototype = {
  4768. chunkSize: function() { return this.size },
  4769. removeInner: function(at, n) {
  4770. var this$1 = this;
  4771. this.size -= n
  4772. for (var i = 0; i < this.children.length; ++i) {
  4773. var child = this$1.children[i], sz = child.chunkSize()
  4774. if (at < sz) {
  4775. var rm = Math.min(n, sz - at), oldHeight = child.height
  4776. child.removeInner(at, rm)
  4777. this$1.height -= oldHeight - child.height
  4778. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
  4779. if ((n -= rm) == 0) { break }
  4780. at = 0
  4781. } else { at -= sz }
  4782. }
  4783. // If the result is smaller than 25 lines, ensure that it is a
  4784. // single leaf node.
  4785. if (this.size - n < 25 &&
  4786. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  4787. var lines = []
  4788. this.collapse(lines)
  4789. this.children = [new LeafChunk(lines)]
  4790. this.children[0].parent = this
  4791. }
  4792. },
  4793. collapse: function(lines) {
  4794. var this$1 = this;
  4795. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
  4796. },
  4797. insertInner: function(at, lines, height) {
  4798. var this$1 = this;
  4799. this.size += lines.length
  4800. this.height += height
  4801. for (var i = 0; i < this.children.length; ++i) {
  4802. var child = this$1.children[i], sz = child.chunkSize()
  4803. if (at <= sz) {
  4804. child.insertInner(at, lines, height)
  4805. if (child.lines && child.lines.length > 50) {
  4806. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  4807. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  4808. var remaining = child.lines.length % 25 + 25
  4809. for (var pos = remaining; pos < child.lines.length;) {
  4810. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
  4811. child.height -= leaf.height
  4812. this$1.children.splice(++i, 0, leaf)
  4813. leaf.parent = this$1
  4814. }
  4815. child.lines = child.lines.slice(0, remaining)
  4816. this$1.maybeSpill()
  4817. }
  4818. break
  4819. }
  4820. at -= sz
  4821. }
  4822. },
  4823. // When a node has grown, check whether it should be split.
  4824. maybeSpill: function() {
  4825. if (this.children.length <= 10) { return }
  4826. var me = this
  4827. do {
  4828. var spilled = me.children.splice(me.children.length - 5, 5)
  4829. var sibling = new BranchChunk(spilled)
  4830. if (!me.parent) { // Become the parent node
  4831. var copy = new BranchChunk(me.children)
  4832. copy.parent = me
  4833. me.children = [copy, sibling]
  4834. me = copy
  4835. } else {
  4836. me.size -= sibling.size
  4837. me.height -= sibling.height
  4838. var myIndex = indexOf(me.parent.children, me)
  4839. me.parent.children.splice(myIndex + 1, 0, sibling)
  4840. }
  4841. sibling.parent = me.parent
  4842. } while (me.children.length > 10)
  4843. me.parent.maybeSpill()
  4844. },
  4845. iterN: function(at, n, op) {
  4846. var this$1 = this;
  4847. for (var i = 0; i < this.children.length; ++i) {
  4848. var child = this$1.children[i], sz = child.chunkSize()
  4849. if (at < sz) {
  4850. var used = Math.min(n, sz - at)
  4851. if (child.iterN(at, used, op)) { return true }
  4852. if ((n -= used) == 0) { break }
  4853. at = 0
  4854. } else { at -= sz }
  4855. }
  4856. }
  4857. }
  4858. // Line widgets are block elements displayed above or below a line.
  4859. function LineWidget(doc, node, options) {
  4860. var this$1 = this;
  4861. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  4862. { this$1[opt] = options[opt] } } }
  4863. this.doc = doc
  4864. this.node = node
  4865. }
  4866. eventMixin(LineWidget)
  4867. function adjustScrollWhenAboveVisible(cm, line, diff) {
  4868. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  4869. { addToScrollPos(cm, null, diff) }
  4870. }
  4871. LineWidget.prototype.clear = function() {
  4872. var this$1 = this;
  4873. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  4874. if (no == null || !ws) { return }
  4875. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
  4876. if (!ws.length) { line.widgets = null }
  4877. var height = widgetHeight(this)
  4878. updateLineHeight(line, Math.max(0, line.height - height))
  4879. if (cm) { runInOp(cm, function () {
  4880. adjustScrollWhenAboveVisible(cm, line, -height)
  4881. regLineChange(cm, no, "widget")
  4882. }) }
  4883. }
  4884. LineWidget.prototype.changed = function() {
  4885. var oldH = this.height, cm = this.doc.cm, line = this.line
  4886. this.height = null
  4887. var diff = widgetHeight(this) - oldH
  4888. if (!diff) { return }
  4889. updateLineHeight(line, line.height + diff)
  4890. if (cm) { runInOp(cm, function () {
  4891. cm.curOp.forceUpdate = true
  4892. adjustScrollWhenAboveVisible(cm, line, diff)
  4893. }) }
  4894. }
  4895. function addLineWidget(doc, handle, node, options) {
  4896. var widget = new LineWidget(doc, node, options)
  4897. var cm = doc.cm
  4898. if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
  4899. changeLine(doc, handle, "widget", function (line) {
  4900. var widgets = line.widgets || (line.widgets = [])
  4901. if (widget.insertAt == null) { widgets.push(widget) }
  4902. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
  4903. widget.line = line
  4904. if (cm && !lineIsHidden(doc, line)) {
  4905. var aboveVisible = heightAtLine(line) < doc.scrollTop
  4906. updateLineHeight(line, line.height + widgetHeight(widget))
  4907. if (aboveVisible) { addToScrollPos(cm, null, widget.height) }
  4908. cm.curOp.forceUpdate = true
  4909. }
  4910. return true
  4911. })
  4912. return widget
  4913. }
  4914. // TEXTMARKERS
  4915. // Created with markText and setBookmark methods. A TextMarker is a
  4916. // handle that can be used to clear or find a marked position in the
  4917. // document. Line objects hold arrays (markedSpans) containing
  4918. // {from, to, marker} object pointing to such marker objects, and
  4919. // indicating that such a marker is present on that line. Multiple
  4920. // lines may point to the same marker when it spans across lines.
  4921. // The spans will have null for their from/to properties when the
  4922. // marker continues beyond the start/end of the line. Markers have
  4923. // links back to the lines they currently touch.
  4924. // Collapsed markers have unique ids, in order to be able to order
  4925. // them, which is needed for uniquely determining an outer marker
  4926. // when they overlap (they may nest, but not partially overlap).
  4927. var nextMarkerId = 0
  4928. function TextMarker(doc, type) {
  4929. this.lines = []
  4930. this.type = type
  4931. this.doc = doc
  4932. this.id = ++nextMarkerId
  4933. }
  4934. eventMixin(TextMarker)
  4935. // Clear the marker.
  4936. TextMarker.prototype.clear = function() {
  4937. var this$1 = this;
  4938. if (this.explicitlyCleared) { return }
  4939. var cm = this.doc.cm, withOp = cm && !cm.curOp
  4940. if (withOp) { startOperation(cm) }
  4941. if (hasHandler(this, "clear")) {
  4942. var found = this.find()
  4943. if (found) { signalLater(this, "clear", found.from, found.to) }
  4944. }
  4945. var min = null, max = null
  4946. for (var i = 0; i < this.lines.length; ++i) {
  4947. var line = this$1.lines[i]
  4948. var span = getMarkedSpanFor(line.markedSpans, this$1)
  4949. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
  4950. else if (cm) {
  4951. if (span.to != null) { max = lineNo(line) }
  4952. if (span.from != null) { min = lineNo(line) }
  4953. }
  4954. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  4955. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  4956. { updateLineHeight(line, textHeight(cm.display)) }
  4957. }
  4958. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  4959. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
  4960. if (len > cm.display.maxLineLength) {
  4961. cm.display.maxLine = visual
  4962. cm.display.maxLineLength = len
  4963. cm.display.maxLineChanged = true
  4964. }
  4965. } }
  4966. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
  4967. this.lines.length = 0
  4968. this.explicitlyCleared = true
  4969. if (this.atomic && this.doc.cantEdit) {
  4970. this.doc.cantEdit = false
  4971. if (cm) { reCheckSelection(cm.doc) }
  4972. }
  4973. if (cm) { signalLater(cm, "markerCleared", cm, this) }
  4974. if (withOp) { endOperation(cm) }
  4975. if (this.parent) { this.parent.clear() }
  4976. }
  4977. // Find the position of the marker in the document. Returns a {from,
  4978. // to} object by default. Side can be passed to get a specific side
  4979. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  4980. // Pos objects returned contain a line object, rather than a line
  4981. // number (used to prevent looking up the same line twice).
  4982. TextMarker.prototype.find = function(side, lineObj) {
  4983. var this$1 = this;
  4984. if (side == null && this.type == "bookmark") { side = 1 }
  4985. var from, to
  4986. for (var i = 0; i < this.lines.length; ++i) {
  4987. var line = this$1.lines[i]
  4988. var span = getMarkedSpanFor(line.markedSpans, this$1)
  4989. if (span.from != null) {
  4990. from = Pos(lineObj ? line : lineNo(line), span.from)
  4991. if (side == -1) { return from }
  4992. }
  4993. if (span.to != null) {
  4994. to = Pos(lineObj ? line : lineNo(line), span.to)
  4995. if (side == 1) { return to }
  4996. }
  4997. }
  4998. return from && {from: from, to: to}
  4999. }
  5000. // Signals that the marker's widget changed, and surrounding layout
  5001. // should be recomputed.
  5002. TextMarker.prototype.changed = function() {
  5003. var pos = this.find(-1, true), widget = this, cm = this.doc.cm
  5004. if (!pos || !cm) { return }
  5005. runInOp(cm, function () {
  5006. var line = pos.line, lineN = lineNo(pos.line)
  5007. var view = findViewForLine(cm, lineN)
  5008. if (view) {
  5009. clearLineMeasurementCacheFor(view)
  5010. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  5011. }
  5012. cm.curOp.updateMaxLine = true
  5013. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5014. var oldHeight = widget.height
  5015. widget.height = null
  5016. var dHeight = widgetHeight(widget) - oldHeight
  5017. if (dHeight)
  5018. { updateLineHeight(line, line.height + dHeight) }
  5019. }
  5020. })
  5021. }
  5022. TextMarker.prototype.attachLine = function(line) {
  5023. if (!this.lines.length && this.doc.cm) {
  5024. var op = this.doc.cm.curOp
  5025. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5026. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
  5027. }
  5028. this.lines.push(line)
  5029. }
  5030. TextMarker.prototype.detachLine = function(line) {
  5031. this.lines.splice(indexOf(this.lines, line), 1)
  5032. if (!this.lines.length && this.doc.cm) {
  5033. var op = this.doc.cm.curOp
  5034. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  5035. }
  5036. }
  5037. // Create a marker, wire it up to the right lines, and
  5038. function markText(doc, from, to, options, type) {
  5039. // Shared markers (across linked documents) are handled separately
  5040. // (markTextShared will call out to this again, once per
  5041. // document).
  5042. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5043. // Ensure we are in an operation.
  5044. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5045. var marker = new TextMarker(doc, type), diff = cmp(from, to)
  5046. if (options) { copyObj(options, marker, false) }
  5047. // Don't connect empty markers unless clearWhenEmpty is false
  5048. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5049. { return marker }
  5050. if (marker.replacedWith) {
  5051. // Showing up as a widget implies collapsed (widget replaces text)
  5052. marker.collapsed = true
  5053. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget")
  5054. marker.widgetNode.setAttribute("role", "presentation") // hide from accessibility tree
  5055. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
  5056. if (options.insertLeft) { marker.widgetNode.insertLeft = true }
  5057. }
  5058. if (marker.collapsed) {
  5059. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5060. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5061. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5062. seeCollapsedSpans()
  5063. }
  5064. if (marker.addToHistory)
  5065. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
  5066. var curLine = from.line, cm = doc.cm, updateMaxLine
  5067. doc.iter(curLine, to.line + 1, function (line) {
  5068. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5069. { updateMaxLine = true }
  5070. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
  5071. addMarkedSpan(line, new MarkedSpan(marker,
  5072. curLine == from.line ? from.ch : null,
  5073. curLine == to.line ? to.ch : null))
  5074. ++curLine
  5075. })
  5076. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5077. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5078. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
  5079. }) }
  5080. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
  5081. if (marker.readOnly) {
  5082. seeReadOnlySpans()
  5083. if (doc.history.done.length || doc.history.undone.length)
  5084. { doc.clearHistory() }
  5085. }
  5086. if (marker.collapsed) {
  5087. marker.id = ++nextMarkerId
  5088. marker.atomic = true
  5089. }
  5090. if (cm) {
  5091. // Sync editor state
  5092. if (updateMaxLine) { cm.curOp.updateMaxLine = true }
  5093. if (marker.collapsed)
  5094. { regChange(cm, from.line, to.line + 1) }
  5095. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5096. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
  5097. if (marker.atomic) { reCheckSelection(cm.doc) }
  5098. signalLater(cm, "markerAdded", cm, marker)
  5099. }
  5100. return marker
  5101. }
  5102. // SHARED TEXTMARKERS
  5103. // A shared marker spans multiple linked documents. It is
  5104. // implemented as a meta-marker-object controlling multiple normal
  5105. // markers.
  5106. function SharedTextMarker(markers, primary) {
  5107. var this$1 = this;
  5108. this.markers = markers
  5109. this.primary = primary
  5110. for (var i = 0; i < markers.length; ++i)
  5111. { markers[i].parent = this$1 }
  5112. }
  5113. eventMixin(SharedTextMarker)
  5114. SharedTextMarker.prototype.clear = function() {
  5115. var this$1 = this;
  5116. if (this.explicitlyCleared) { return }
  5117. this.explicitlyCleared = true
  5118. for (var i = 0; i < this.markers.length; ++i)
  5119. { this$1.markers[i].clear() }
  5120. signalLater(this, "clear")
  5121. }
  5122. SharedTextMarker.prototype.find = function(side, lineObj) {
  5123. return this.primary.find(side, lineObj)
  5124. }
  5125. function markTextShared(doc, from, to, options, type) {
  5126. options = copyObj(options)
  5127. options.shared = false
  5128. var markers = [markText(doc, from, to, options, type)], primary = markers[0]
  5129. var widget = options.widgetNode
  5130. linkedDocs(doc, function (doc) {
  5131. if (widget) { options.widgetNode = widget.cloneNode(true) }
  5132. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  5133. for (var i = 0; i < doc.linked.length; ++i)
  5134. { if (doc.linked[i].isParent) { return } }
  5135. primary = lst(markers)
  5136. })
  5137. return new SharedTextMarker(markers, primary)
  5138. }
  5139. function findSharedMarkers(doc) {
  5140. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5141. }
  5142. function copySharedMarkers(doc, markers) {
  5143. for (var i = 0; i < markers.length; i++) {
  5144. var marker = markers[i], pos = marker.find()
  5145. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
  5146. if (cmp(mFrom, mTo)) {
  5147. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  5148. marker.markers.push(subMark)
  5149. subMark.parent = marker
  5150. }
  5151. }
  5152. }
  5153. function detachSharedMarkers(markers) {
  5154. var loop = function ( i ) {
  5155. var marker = markers[i], linked = [marker.primary.doc]
  5156. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
  5157. for (var j = 0; j < marker.markers.length; j++) {
  5158. var subMarker = marker.markers[j]
  5159. if (indexOf(linked, subMarker.doc) == -1) {
  5160. subMarker.parent = null
  5161. marker.markers.splice(j--, 1)
  5162. }
  5163. }
  5164. };
  5165. for (var i = 0; i < markers.length; i++) loop( i );
  5166. }
  5167. var nextDocId = 0
  5168. var Doc = function(text, mode, firstLine, lineSep) {
  5169. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep) }
  5170. if (firstLine == null) { firstLine = 0 }
  5171. BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  5172. this.first = firstLine
  5173. this.scrollTop = this.scrollLeft = 0
  5174. this.cantEdit = false
  5175. this.cleanGeneration = 1
  5176. this.frontier = firstLine
  5177. var start = Pos(firstLine, 0)
  5178. this.sel = simpleSelection(start)
  5179. this.history = new History(null)
  5180. this.id = ++nextDocId
  5181. this.modeOption = mode
  5182. this.lineSep = lineSep
  5183. this.extend = false
  5184. if (typeof text == "string") { text = this.splitLines(text) }
  5185. updateDoc(this, {from: start, to: start, text: text})
  5186. setSelection(this, simpleSelection(start), sel_dontScroll)
  5187. }
  5188. Doc.prototype = createObj(BranchChunk.prototype, {
  5189. constructor: Doc,
  5190. // Iterate over the document. Supports two forms -- with only one
  5191. // argument, it calls that for each line in the document. With
  5192. // three, it iterates over the range given by the first two (with
  5193. // the second being non-inclusive).
  5194. iter: function(from, to, op) {
  5195. if (op) { this.iterN(from - this.first, to - from, op) }
  5196. else { this.iterN(this.first, this.first + this.size, from) }
  5197. },
  5198. // Non-public interface for adding and removing lines.
  5199. insert: function(at, lines) {
  5200. var height = 0
  5201. for (var i = 0; i < lines.length; ++i) { height += lines[i].height }
  5202. this.insertInner(at - this.first, lines, height)
  5203. },
  5204. remove: function(at, n) { this.removeInner(at - this.first, n) },
  5205. // From here, the methods are part of the public interface. Most
  5206. // are also available from CodeMirror (editor) instances.
  5207. getValue: function(lineSep) {
  5208. var lines = getLines(this, this.first, this.first + this.size)
  5209. if (lineSep === false) { return lines }
  5210. return lines.join(lineSep || this.lineSeparator())
  5211. },
  5212. setValue: docMethodOp(function(code) {
  5213. var top = Pos(this.first, 0), last = this.first + this.size - 1
  5214. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5215. text: this.splitLines(code), origin: "setValue", full: true}, true)
  5216. setSelection(this, simpleSelection(top))
  5217. }),
  5218. replaceRange: function(code, from, to, origin) {
  5219. from = clipPos(this, from)
  5220. to = to ? clipPos(this, to) : from
  5221. replaceRange(this, code, from, to, origin)
  5222. },
  5223. getRange: function(from, to, lineSep) {
  5224. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  5225. if (lineSep === false) { return lines }
  5226. return lines.join(lineSep || this.lineSeparator())
  5227. },
  5228. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5229. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5230. getLineNumber: function(line) {return lineNo(line)},
  5231. getLineHandleVisualStart: function(line) {
  5232. if (typeof line == "number") { line = getLine(this, line) }
  5233. return visualLine(line)
  5234. },
  5235. lineCount: function() {return this.size},
  5236. firstLine: function() {return this.first},
  5237. lastLine: function() {return this.first + this.size - 1},
  5238. clipPos: function(pos) {return clipPos(this, pos)},
  5239. getCursor: function(start) {
  5240. var range = this.sel.primary(), pos
  5241. if (start == null || start == "head") { pos = range.head }
  5242. else if (start == "anchor") { pos = range.anchor }
  5243. else if (start == "end" || start == "to" || start === false) { pos = range.to() }
  5244. else { pos = range.from() }
  5245. return pos
  5246. },
  5247. listSelections: function() { return this.sel.ranges },
  5248. somethingSelected: function() {return this.sel.somethingSelected()},
  5249. setCursor: docMethodOp(function(line, ch, options) {
  5250. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options)
  5251. }),
  5252. setSelection: docMethodOp(function(anchor, head, options) {
  5253. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  5254. }),
  5255. extendSelection: docMethodOp(function(head, other, options) {
  5256. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  5257. }),
  5258. extendSelections: docMethodOp(function(heads, options) {
  5259. extendSelections(this, clipPosArray(this, heads), options)
  5260. }),
  5261. extendSelectionsBy: docMethodOp(function(f, options) {
  5262. var heads = map(this.sel.ranges, f)
  5263. extendSelections(this, clipPosArray(this, heads), options)
  5264. }),
  5265. setSelections: docMethodOp(function(ranges, primary, options) {
  5266. var this$1 = this;
  5267. if (!ranges.length) { return }
  5268. var out = []
  5269. for (var i = 0; i < ranges.length; i++)
  5270. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5271. clipPos(this$1, ranges[i].head)) }
  5272. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
  5273. setSelection(this, normalizeSelection(out, primary), options)
  5274. }),
  5275. addSelection: docMethodOp(function(anchor, head, options) {
  5276. var ranges = this.sel.ranges.slice(0)
  5277. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  5278. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
  5279. }),
  5280. getSelection: function(lineSep) {
  5281. var this$1 = this;
  5282. var ranges = this.sel.ranges, lines
  5283. for (var i = 0; i < ranges.length; i++) {
  5284. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5285. lines = lines ? lines.concat(sel) : sel
  5286. }
  5287. if (lineSep === false) { return lines }
  5288. else { return lines.join(lineSep || this.lineSeparator()) }
  5289. },
  5290. getSelections: function(lineSep) {
  5291. var this$1 = this;
  5292. var parts = [], ranges = this.sel.ranges
  5293. for (var i = 0; i < ranges.length; i++) {
  5294. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5295. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
  5296. parts[i] = sel
  5297. }
  5298. return parts
  5299. },
  5300. replaceSelection: function(code, collapse, origin) {
  5301. var dup = []
  5302. for (var i = 0; i < this.sel.ranges.length; i++)
  5303. { dup[i] = code }
  5304. this.replaceSelections(dup, collapse, origin || "+input")
  5305. },
  5306. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5307. var this$1 = this;
  5308. var changes = [], sel = this.sel
  5309. for (var i = 0; i < sel.ranges.length; i++) {
  5310. var range = sel.ranges[i]
  5311. changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
  5312. }
  5313. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
  5314. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5315. { makeChange(this$1, changes[i$1]) }
  5316. if (newSel) { setSelectionReplaceHistory(this, newSel) }
  5317. else if (this.cm) { ensureCursorVisible(this.cm) }
  5318. }),
  5319. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
  5320. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
  5321. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
  5322. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
  5323. setExtending: function(val) {this.extend = val},
  5324. getExtending: function() {return this.extend},
  5325. historySize: function() {
  5326. var hist = this.history, done = 0, undone = 0
  5327. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
  5328. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
  5329. return {undo: done, redo: undone}
  5330. },
  5331. clearHistory: function() {this.history = new History(this.history.maxGeneration)},
  5332. markClean: function() {
  5333. this.cleanGeneration = this.changeGeneration(true)
  5334. },
  5335. changeGeneration: function(forceSplit) {
  5336. if (forceSplit)
  5337. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
  5338. return this.history.generation
  5339. },
  5340. isClean: function (gen) {
  5341. return this.history.generation == (gen || this.cleanGeneration)
  5342. },
  5343. getHistory: function() {
  5344. return {done: copyHistoryArray(this.history.done),
  5345. undone: copyHistoryArray(this.history.undone)}
  5346. },
  5347. setHistory: function(histData) {
  5348. var hist = this.history = new History(this.history.maxGeneration)
  5349. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  5350. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  5351. },
  5352. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5353. return changeLine(this, line, "gutter", function (line) {
  5354. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  5355. markers[gutterID] = value
  5356. if (!value && isEmpty(markers)) { line.gutterMarkers = null }
  5357. return true
  5358. })
  5359. }),
  5360. clearGutter: docMethodOp(function(gutterID) {
  5361. var this$1 = this;
  5362. this.iter(function (line) {
  5363. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5364. changeLine(this$1, line, "gutter", function () {
  5365. line.gutterMarkers[gutterID] = null
  5366. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
  5367. return true
  5368. })
  5369. }
  5370. })
  5371. }),
  5372. lineInfo: function(line) {
  5373. var n
  5374. if (typeof line == "number") {
  5375. if (!isLine(this, line)) { return null }
  5376. n = line
  5377. line = getLine(this, line)
  5378. if (!line) { return null }
  5379. } else {
  5380. n = lineNo(line)
  5381. if (n == null) { return null }
  5382. }
  5383. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5384. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5385. widgets: line.widgets}
  5386. },
  5387. addLineClass: docMethodOp(function(handle, where, cls) {
  5388. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5389. var prop = where == "text" ? "textClass"
  5390. : where == "background" ? "bgClass"
  5391. : where == "gutter" ? "gutterClass" : "wrapClass"
  5392. if (!line[prop]) { line[prop] = cls }
  5393. else if (classTest(cls).test(line[prop])) { return false }
  5394. else { line[prop] += " " + cls }
  5395. return true
  5396. })
  5397. }),
  5398. removeLineClass: docMethodOp(function(handle, where, cls) {
  5399. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5400. var prop = where == "text" ? "textClass"
  5401. : where == "background" ? "bgClass"
  5402. : where == "gutter" ? "gutterClass" : "wrapClass"
  5403. var cur = line[prop]
  5404. if (!cur) { return false }
  5405. else if (cls == null) { line[prop] = null }
  5406. else {
  5407. var found = cur.match(classTest(cls))
  5408. if (!found) { return false }
  5409. var end = found.index + found[0].length
  5410. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
  5411. }
  5412. return true
  5413. })
  5414. }),
  5415. addLineWidget: docMethodOp(function(handle, node, options) {
  5416. return addLineWidget(this, handle, node, options)
  5417. }),
  5418. removeLineWidget: function(widget) { widget.clear() },
  5419. markText: function(from, to, options) {
  5420. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5421. },
  5422. setBookmark: function(pos, options) {
  5423. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5424. insertLeft: options && options.insertLeft,
  5425. clearWhenEmpty: false, shared: options && options.shared,
  5426. handleMouseEvents: options && options.handleMouseEvents}
  5427. pos = clipPos(this, pos)
  5428. return markText(this, pos, pos, realOpts, "bookmark")
  5429. },
  5430. findMarksAt: function(pos) {
  5431. pos = clipPos(this, pos)
  5432. var markers = [], spans = getLine(this, pos.line).markedSpans
  5433. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5434. var span = spans[i]
  5435. if ((span.from == null || span.from <= pos.ch) &&
  5436. (span.to == null || span.to >= pos.ch))
  5437. { markers.push(span.marker.parent || span.marker) }
  5438. } }
  5439. return markers
  5440. },
  5441. findMarks: function(from, to, filter) {
  5442. from = clipPos(this, from); to = clipPos(this, to)
  5443. var found = [], lineNo = from.line
  5444. this.iter(from.line, to.line + 1, function (line) {
  5445. var spans = line.markedSpans
  5446. if (spans) { for (var i = 0; i < spans.length; i++) {
  5447. var span = spans[i]
  5448. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5449. span.from == null && lineNo != from.line ||
  5450. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5451. (!filter || filter(span.marker)))
  5452. { found.push(span.marker.parent || span.marker) }
  5453. } }
  5454. ++lineNo
  5455. })
  5456. return found
  5457. },
  5458. getAllMarks: function() {
  5459. var markers = []
  5460. this.iter(function (line) {
  5461. var sps = line.markedSpans
  5462. if (sps) { for (var i = 0; i < sps.length; ++i)
  5463. { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
  5464. })
  5465. return markers
  5466. },
  5467. posFromIndex: function(off) {
  5468. var ch, lineNo = this.first, sepSize = this.lineSeparator().length
  5469. this.iter(function (line) {
  5470. var sz = line.text.length + sepSize
  5471. if (sz > off) { ch = off; return true }
  5472. off -= sz
  5473. ++lineNo
  5474. })
  5475. return clipPos(this, Pos(lineNo, ch))
  5476. },
  5477. indexFromPos: function (coords) {
  5478. coords = clipPos(this, coords)
  5479. var index = coords.ch
  5480. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5481. var sepSize = this.lineSeparator().length
  5482. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5483. index += line.text.length + sepSize
  5484. })
  5485. return index
  5486. },
  5487. copy: function(copyHistory) {
  5488. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5489. this.modeOption, this.first, this.lineSep)
  5490. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
  5491. doc.sel = this.sel
  5492. doc.extend = false
  5493. if (copyHistory) {
  5494. doc.history.undoDepth = this.history.undoDepth
  5495. doc.setHistory(this.getHistory())
  5496. }
  5497. return doc
  5498. },
  5499. linkedDoc: function(options) {
  5500. if (!options) { options = {} }
  5501. var from = this.first, to = this.first + this.size
  5502. if (options.from != null && options.from > from) { from = options.from }
  5503. if (options.to != null && options.to < to) { to = options.to }
  5504. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep)
  5505. if (options.sharedHist) { copy.history = this.history
  5506. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
  5507. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
  5508. copySharedMarkers(copy, findSharedMarkers(this))
  5509. return copy
  5510. },
  5511. unlinkDoc: function(other) {
  5512. var this$1 = this;
  5513. if (other instanceof CodeMirror) { other = other.doc }
  5514. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5515. var link = this$1.linked[i]
  5516. if (link.doc != other) { continue }
  5517. this$1.linked.splice(i, 1)
  5518. other.unlinkDoc(this$1)
  5519. detachSharedMarkers(findSharedMarkers(this$1))
  5520. break
  5521. } }
  5522. // If the histories were shared, split them again
  5523. if (other.history == this.history) {
  5524. var splitIds = [other.id]
  5525. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
  5526. other.history = new History(null)
  5527. other.history.done = copyHistoryArray(this.history.done, splitIds)
  5528. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  5529. }
  5530. },
  5531. iterLinkedDocs: function(f) {linkedDocs(this, f)},
  5532. getMode: function() {return this.mode},
  5533. getEditor: function() {return this.cm},
  5534. splitLines: function(str) {
  5535. if (this.lineSep) { return str.split(this.lineSep) }
  5536. return splitLinesAuto(str)
  5537. },
  5538. lineSeparator: function() { return this.lineSep || "\n" }
  5539. })
  5540. // Public alias.
  5541. Doc.prototype.eachLine = Doc.prototype.iter
  5542. // Kludge to work around strange IE behavior where it'll sometimes
  5543. // re-fire a series of drag-related events right after the drop (#1551)
  5544. var lastDrop = 0
  5545. function onDrop(e) {
  5546. var cm = this
  5547. clearDragCursor(cm)
  5548. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5549. { return }
  5550. e_preventDefault(e)
  5551. if (ie) { lastDrop = +new Date }
  5552. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
  5553. if (!pos || cm.isReadOnly()) { return }
  5554. // Might be a file drop, in which case we simply extract the text
  5555. // and insert it.
  5556. if (files && files.length && window.FileReader && window.File) {
  5557. var n = files.length, text = Array(n), read = 0
  5558. var loadFile = function (file, i) {
  5559. if (cm.options.allowDropFileTypes &&
  5560. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5561. { return }
  5562. var reader = new FileReader
  5563. reader.onload = operation(cm, function () {
  5564. var content = reader.result
  5565. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
  5566. text[i] = content
  5567. if (++read == n) {
  5568. pos = clipPos(cm.doc, pos)
  5569. var change = {from: pos, to: pos,
  5570. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5571. origin: "paste"}
  5572. makeChange(cm.doc, change)
  5573. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
  5574. }
  5575. })
  5576. reader.readAsText(file)
  5577. }
  5578. for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
  5579. } else { // Normal drop
  5580. // Don't do a replace if the drop happened inside of the selected text.
  5581. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5582. cm.state.draggingText(e)
  5583. // Ensure the editor is re-focused
  5584. setTimeout(function () { return cm.display.input.focus(); }, 20)
  5585. return
  5586. }
  5587. try {
  5588. var text$1 = e.dataTransfer.getData("Text")
  5589. if (text$1) {
  5590. var selected
  5591. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5592. { selected = cm.listSelections() }
  5593. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  5594. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5595. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
  5596. cm.replaceSelection(text$1, "around", "paste")
  5597. cm.display.input.focus()
  5598. }
  5599. }
  5600. catch(e){}
  5601. }
  5602. }
  5603. function onDragStart(cm, e) {
  5604. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5605. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5606. e.dataTransfer.setData("Text", cm.getSelection())
  5607. e.dataTransfer.effectAllowed = "copyMove"
  5608. // Use dummy image instead of default browsers image.
  5609. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5610. if (e.dataTransfer.setDragImage && !safari) {
  5611. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
  5612. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  5613. if (presto) {
  5614. img.width = img.height = 1
  5615. cm.display.wrapper.appendChild(img)
  5616. // Force a relayout, or Opera won't use our image for some obscure reason
  5617. img._top = img.offsetTop
  5618. }
  5619. e.dataTransfer.setDragImage(img, 0, 0)
  5620. if (presto) { img.parentNode.removeChild(img) }
  5621. }
  5622. }
  5623. function onDragOver(cm, e) {
  5624. var pos = posFromMouse(cm, e)
  5625. if (!pos) { return }
  5626. var frag = document.createDocumentFragment()
  5627. drawSelectionCursor(cm, pos, frag)
  5628. if (!cm.display.dragCursor) {
  5629. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
  5630. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  5631. }
  5632. removeChildrenAndAdd(cm.display.dragCursor, frag)
  5633. }
  5634. function clearDragCursor(cm) {
  5635. if (cm.display.dragCursor) {
  5636. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  5637. cm.display.dragCursor = null
  5638. }
  5639. }
  5640. // These must be handled carefully, because naively registering a
  5641. // handler for each editor will cause the editors to never be
  5642. // garbage collected.
  5643. function forEachCodeMirror(f) {
  5644. if (!document.body.getElementsByClassName) { return }
  5645. var byClass = document.body.getElementsByClassName("CodeMirror")
  5646. for (var i = 0; i < byClass.length; i++) {
  5647. var cm = byClass[i].CodeMirror
  5648. if (cm) { f(cm) }
  5649. }
  5650. }
  5651. var globalsRegistered = false
  5652. function ensureGlobalHandlers() {
  5653. if (globalsRegistered) { return }
  5654. registerGlobalHandlers()
  5655. globalsRegistered = true
  5656. }
  5657. function registerGlobalHandlers() {
  5658. // When the window resizes, we need to refresh active editors.
  5659. var resizeTimer
  5660. on(window, "resize", function () {
  5661. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5662. resizeTimer = null
  5663. forEachCodeMirror(onResize)
  5664. }, 100) }
  5665. })
  5666. // When the window loses focus, we want to show the editor as blurred
  5667. on(window, "blur", function () { return forEachCodeMirror(onBlur); })
  5668. }
  5669. // Called when the window resizes
  5670. function onResize(cm) {
  5671. var d = cm.display
  5672. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5673. { return }
  5674. // Might be a text scaling operation, clear size caches.
  5675. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5676. d.scrollbarsClipped = false
  5677. cm.setSize()
  5678. }
  5679. var keyNames = {
  5680. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5681. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5682. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5683. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5684. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  5685. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5686. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5687. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5688. }
  5689. // Number keys
  5690. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
  5691. // Alphabetic keys
  5692. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
  5693. // Function keys
  5694. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
  5695. var keyMap = {}
  5696. keyMap.basic = {
  5697. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5698. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5699. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5700. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5701. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5702. "Esc": "singleSelection"
  5703. }
  5704. // Note that the save and find-related commands aren't defined by
  5705. // default. User code or addons can define them. Unknown commands
  5706. // are simply ignored.
  5707. keyMap.pcDefault = {
  5708. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5709. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5710. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5711. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5712. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5713. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5714. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5715. fallthrough: "basic"
  5716. }
  5717. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5718. keyMap.emacsy = {
  5719. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5720. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5721. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5722. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5723. "Ctrl-O": "openLine"
  5724. }
  5725. keyMap.macDefault = {
  5726. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5727. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5728. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5729. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5730. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5731. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5732. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5733. fallthrough: ["basic", "emacsy"]
  5734. }
  5735. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
  5736. // KEYMAP DISPATCH
  5737. function normalizeKeyName(name) {
  5738. var parts = name.split(/-(?!$)/)
  5739. name = parts[parts.length - 1]
  5740. var alt, ctrl, shift, cmd
  5741. for (var i = 0; i < parts.length - 1; i++) {
  5742. var mod = parts[i]
  5743. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
  5744. else if (/^a(lt)?$/i.test(mod)) { alt = true }
  5745. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
  5746. else if (/^s(hift)?$/i.test(mod)) { shift = true }
  5747. else { throw new Error("Unrecognized modifier name: " + mod) }
  5748. }
  5749. if (alt) { name = "Alt-" + name }
  5750. if (ctrl) { name = "Ctrl-" + name }
  5751. if (cmd) { name = "Cmd-" + name }
  5752. if (shift) { name = "Shift-" + name }
  5753. return name
  5754. }
  5755. // This is a kludge to keep keymaps mostly working as raw objects
  5756. // (backwards compatibility) while at the same time support features
  5757. // like normalization and multi-stroke key bindings. It compiles a
  5758. // new normalized keymap, and then updates the old object to reflect
  5759. // this.
  5760. function normalizeKeyMap(keymap) {
  5761. var copy = {}
  5762. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  5763. var value = keymap[keyname]
  5764. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  5765. if (value == "...") { delete keymap[keyname]; continue }
  5766. var keys = map(keyname.split(" "), normalizeKeyName)
  5767. for (var i = 0; i < keys.length; i++) {
  5768. var val = (void 0), name = (void 0)
  5769. if (i == keys.length - 1) {
  5770. name = keys.join(" ")
  5771. val = value
  5772. } else {
  5773. name = keys.slice(0, i + 1).join(" ")
  5774. val = "..."
  5775. }
  5776. var prev = copy[name]
  5777. if (!prev) { copy[name] = val }
  5778. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  5779. }
  5780. delete keymap[keyname]
  5781. } }
  5782. for (var prop in copy) { keymap[prop] = copy[prop] }
  5783. return keymap
  5784. }
  5785. function lookupKey(key, map, handle, context) {
  5786. map = getKeyMap(map)
  5787. var found = map.call ? map.call(key, context) : map[key]
  5788. if (found === false) { return "nothing" }
  5789. if (found === "...") { return "multi" }
  5790. if (found != null && handle(found)) { return "handled" }
  5791. if (map.fallthrough) {
  5792. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5793. { return lookupKey(key, map.fallthrough, handle, context) }
  5794. for (var i = 0; i < map.fallthrough.length; i++) {
  5795. var result = lookupKey(key, map.fallthrough[i], handle, context)
  5796. if (result) { return result }
  5797. }
  5798. }
  5799. }
  5800. // Modifier key presses don't count as 'real' key presses for the
  5801. // purpose of keymap fallthrough.
  5802. function isModifierKey(value) {
  5803. var name = typeof value == "string" ? value : keyNames[value.keyCode]
  5804. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  5805. }
  5806. // Look up the name of a key as indicated by an event object.
  5807. function keyName(event, noShift) {
  5808. if (presto && event.keyCode == 34 && event["char"]) { return false }
  5809. var base = keyNames[event.keyCode], name = base
  5810. if (name == null || event.altGraphKey) { return false }
  5811. if (event.altKey && base != "Alt") { name = "Alt-" + name }
  5812. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
  5813. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
  5814. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
  5815. return name
  5816. }
  5817. function getKeyMap(val) {
  5818. return typeof val == "string" ? keyMap[val] : val
  5819. }
  5820. // Helper for deleting text near the selection(s), used to implement
  5821. // backspace, delete, and similar functionality.
  5822. function deleteNearSelection(cm, compute) {
  5823. var ranges = cm.doc.sel.ranges, kill = []
  5824. // Build up a set of ranges to kill first, merging overlapping
  5825. // ranges.
  5826. for (var i = 0; i < ranges.length; i++) {
  5827. var toKill = compute(ranges[i])
  5828. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  5829. var replaced = kill.pop()
  5830. if (cmp(replaced.from, toKill.from) < 0) {
  5831. toKill.from = replaced.from
  5832. break
  5833. }
  5834. }
  5835. kill.push(toKill)
  5836. }
  5837. // Next, remove those actual ranges.
  5838. runInOp(cm, function () {
  5839. for (var i = kill.length - 1; i >= 0; i--)
  5840. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") }
  5841. ensureCursorVisible(cm)
  5842. })
  5843. }
  5844. // Commands are parameter-less actions that can be performed on an
  5845. // editor, mostly used for keybindings.
  5846. var commands = {
  5847. selectAll: selectAll,
  5848. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  5849. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  5850. if (range.empty()) {
  5851. var len = getLine(cm.doc, range.head.line).text.length
  5852. if (range.head.ch == len && range.head.line < cm.lastLine())
  5853. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  5854. else
  5855. { return {from: range.head, to: Pos(range.head.line, len)} }
  5856. } else {
  5857. return {from: range.from(), to: range.to()}
  5858. }
  5859. }); },
  5860. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5861. from: Pos(range.from().line, 0),
  5862. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  5863. }); }); },
  5864. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5865. from: Pos(range.from().line, 0), to: range.from()
  5866. }); }); },
  5867. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  5868. var top = cm.charCoords(range.head, "div").top + 5
  5869. var leftPos = cm.coordsChar({left: 0, top: top}, "div")
  5870. return {from: leftPos, to: range.from()}
  5871. }); },
  5872. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  5873. var top = cm.charCoords(range.head, "div").top + 5
  5874. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  5875. return {from: range.from(), to: rightPos }
  5876. }); },
  5877. undo: function (cm) { return cm.undo(); },
  5878. redo: function (cm) { return cm.redo(); },
  5879. undoSelection: function (cm) { return cm.undoSelection(); },
  5880. redoSelection: function (cm) { return cm.redoSelection(); },
  5881. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  5882. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  5883. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  5884. {origin: "+move", bias: 1}
  5885. ); },
  5886. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  5887. {origin: "+move", bias: 1}
  5888. ); },
  5889. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  5890. {origin: "+move", bias: -1}
  5891. ); },
  5892. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  5893. var top = cm.charCoords(range.head, "div").top + 5
  5894. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  5895. }, sel_move); },
  5896. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  5897. var top = cm.charCoords(range.head, "div").top + 5
  5898. return cm.coordsChar({left: 0, top: top}, "div")
  5899. }, sel_move); },
  5900. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  5901. var top = cm.charCoords(range.head, "div").top + 5
  5902. var pos = cm.coordsChar({left: 0, top: top}, "div")
  5903. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  5904. return pos
  5905. }, sel_move); },
  5906. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  5907. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  5908. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  5909. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  5910. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  5911. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  5912. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  5913. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  5914. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  5915. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  5916. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  5917. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  5918. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  5919. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  5920. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  5921. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  5922. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  5923. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  5924. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  5925. indentMore: function (cm) { return cm.indentSelection("add"); },
  5926. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  5927. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  5928. insertSoftTab: function (cm) {
  5929. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
  5930. for (var i = 0; i < ranges.length; i++) {
  5931. var pos = ranges[i].from()
  5932. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  5933. spaces.push(spaceStr(tabSize - col % tabSize))
  5934. }
  5935. cm.replaceSelections(spaces)
  5936. },
  5937. defaultTab: function (cm) {
  5938. if (cm.somethingSelected()) { cm.indentSelection("add") }
  5939. else { cm.execCommand("insertTab") }
  5940. },
  5941. // Swap the two chars left and right of each selection's head.
  5942. // Move cursor behind the two swapped characters afterwards.
  5943. //
  5944. // Doesn't consider line feeds a character.
  5945. // Doesn't scan more than one line above to find a character.
  5946. // Doesn't do anything on an empty line.
  5947. // Doesn't do anything with non-empty selections.
  5948. transposeChars: function (cm) { return runInOp(cm, function () {
  5949. var ranges = cm.listSelections(), newSel = []
  5950. for (var i = 0; i < ranges.length; i++) {
  5951. if (!ranges[i].empty()) { continue }
  5952. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
  5953. if (line) {
  5954. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
  5955. if (cur.ch > 0) {
  5956. cur = new Pos(cur.line, cur.ch + 1)
  5957. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5958. Pos(cur.line, cur.ch - 2), cur, "+transpose")
  5959. } else if (cur.line > cm.doc.first) {
  5960. var prev = getLine(cm.doc, cur.line - 1).text
  5961. if (prev) {
  5962. cur = new Pos(cur.line, 1)
  5963. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  5964. prev.charAt(prev.length - 1),
  5965. Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
  5966. }
  5967. }
  5968. }
  5969. newSel.push(new Range(cur, cur))
  5970. }
  5971. cm.setSelections(newSel)
  5972. }); },
  5973. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  5974. var sels = cm.listSelections()
  5975. for (var i = sels.length - 1; i >= 0; i--)
  5976. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") }
  5977. sels = cm.listSelections()
  5978. for (var i$1 = 0; i$1 < sels.length; i$1++)
  5979. { cm.indentLine(sels[i$1].from().line, null, true) }
  5980. ensureCursorVisible(cm)
  5981. }); },
  5982. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  5983. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  5984. }
  5985. function lineStart(cm, lineN) {
  5986. var line = getLine(cm.doc, lineN)
  5987. var visual = visualLine(line)
  5988. if (visual != line) { lineN = lineNo(visual) }
  5989. var order = getOrder(visual)
  5990. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual)
  5991. return Pos(lineN, ch)
  5992. }
  5993. function lineEnd(cm, lineN) {
  5994. var merged, line = getLine(cm.doc, lineN)
  5995. while (merged = collapsedSpanAtEnd(line)) {
  5996. line = merged.find(1, true).line
  5997. lineN = null
  5998. }
  5999. var order = getOrder(line)
  6000. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line)
  6001. return Pos(lineN == null ? lineNo(line) : lineN, ch)
  6002. }
  6003. function lineStartSmart(cm, pos) {
  6004. var start = lineStart(cm, pos.line)
  6005. var line = getLine(cm.doc, start.line)
  6006. var order = getOrder(line)
  6007. if (!order || order[0].level == 0) {
  6008. var firstNonWS = Math.max(0, line.text.search(/\S/))
  6009. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  6010. return Pos(start.line, inWS ? 0 : firstNonWS)
  6011. }
  6012. return start
  6013. }
  6014. // Run a handler that was bound to a key.
  6015. function doHandleBinding(cm, bound, dropShift) {
  6016. if (typeof bound == "string") {
  6017. bound = commands[bound]
  6018. if (!bound) { return false }
  6019. }
  6020. // Ensure previous input has been read, so that the handler sees a
  6021. // consistent view of the document
  6022. cm.display.input.ensurePolled()
  6023. var prevShift = cm.display.shift, done = false
  6024. try {
  6025. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6026. if (dropShift) { cm.display.shift = false }
  6027. done = bound(cm) != Pass
  6028. } finally {
  6029. cm.display.shift = prevShift
  6030. cm.state.suppressEdits = false
  6031. }
  6032. return done
  6033. }
  6034. function lookupKeyForEditor(cm, name, handle) {
  6035. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6036. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  6037. if (result) { return result }
  6038. }
  6039. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6040. || lookupKey(name, cm.options.keyMap, handle, cm)
  6041. }
  6042. var stopSeq = new Delayed
  6043. function dispatchKey(cm, name, e, handle) {
  6044. var seq = cm.state.keySeq
  6045. if (seq) {
  6046. if (isModifierKey(name)) { return "handled" }
  6047. stopSeq.set(50, function () {
  6048. if (cm.state.keySeq == seq) {
  6049. cm.state.keySeq = null
  6050. cm.display.input.reset()
  6051. }
  6052. })
  6053. name = seq + " " + name
  6054. }
  6055. var result = lookupKeyForEditor(cm, name, handle)
  6056. if (result == "multi")
  6057. { cm.state.keySeq = name }
  6058. if (result == "handled")
  6059. { signalLater(cm, "keyHandled", cm, name, e) }
  6060. if (result == "handled" || result == "multi") {
  6061. e_preventDefault(e)
  6062. restartBlink(cm)
  6063. }
  6064. if (seq && !result && /\'$/.test(name)) {
  6065. e_preventDefault(e)
  6066. return true
  6067. }
  6068. return !!result
  6069. }
  6070. // Handle a key from the keydown event.
  6071. function handleKeyBinding(cm, e) {
  6072. var name = keyName(e, true)
  6073. if (!name) { return false }
  6074. if (e.shiftKey && !cm.state.keySeq) {
  6075. // First try to resolve full name (including 'Shift-'). Failing
  6076. // that, see if there is a cursor-motion command (starting with
  6077. // 'go') bound to the keyname without 'Shift-'.
  6078. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6079. || dispatchKey(cm, name, e, function (b) {
  6080. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6081. { return doHandleBinding(cm, b) }
  6082. })
  6083. } else {
  6084. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6085. }
  6086. }
  6087. // Handle a key from the keypress event
  6088. function handleCharBinding(cm, e, ch) {
  6089. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6090. }
  6091. var lastStoppedKey = null
  6092. function onKeyDown(e) {
  6093. var cm = this
  6094. cm.curOp.focus = activeElt()
  6095. if (signalDOMEvent(cm, e)) { return }
  6096. // IE does strange things with escape.
  6097. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
  6098. var code = e.keyCode
  6099. cm.display.shift = code == 16 || e.shiftKey
  6100. var handled = handleKeyBinding(cm, e)
  6101. if (presto) {
  6102. lastStoppedKey = handled ? code : null
  6103. // Opera has no cut event... we try to at least catch the key combo
  6104. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6105. { cm.replaceSelection("", null, "cut") }
  6106. }
  6107. // Turn mouse into crosshair when Alt is held on Mac.
  6108. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6109. { showCrossHair(cm) }
  6110. }
  6111. function showCrossHair(cm) {
  6112. var lineDiv = cm.display.lineDiv
  6113. addClass(lineDiv, "CodeMirror-crosshair")
  6114. function up(e) {
  6115. if (e.keyCode == 18 || !e.altKey) {
  6116. rmClass(lineDiv, "CodeMirror-crosshair")
  6117. off(document, "keyup", up)
  6118. off(document, "mouseover", up)
  6119. }
  6120. }
  6121. on(document, "keyup", up)
  6122. on(document, "mouseover", up)
  6123. }
  6124. function onKeyUp(e) {
  6125. if (e.keyCode == 16) { this.doc.sel.shift = false }
  6126. signalDOMEvent(this, e)
  6127. }
  6128. function onKeyPress(e) {
  6129. var cm = this
  6130. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6131. var keyCode = e.keyCode, charCode = e.charCode
  6132. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6133. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6134. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  6135. // Some browsers fire keypress events for backspace
  6136. if (ch == "\x08") { return }
  6137. if (handleCharBinding(cm, e, ch)) { return }
  6138. cm.display.input.onKeyPress(e)
  6139. }
  6140. // A mouse down can be a single click, double click, triple click,
  6141. // start of selection drag, start of text drag, new cursor
  6142. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6143. // middle-click-paste. Or it might be a click on something we should
  6144. // not interfere with, such as a scrollbar or widget.
  6145. function onMouseDown(e) {
  6146. var cm = this, display = cm.display
  6147. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6148. display.input.ensurePolled()
  6149. display.shift = e.shiftKey
  6150. if (eventInWidget(display, e)) {
  6151. if (!webkit) {
  6152. // Briefly turn off draggability, to allow widgets to do
  6153. // normal dragging things.
  6154. display.scroller.draggable = false
  6155. setTimeout(function () { return display.scroller.draggable = true; }, 100)
  6156. }
  6157. return
  6158. }
  6159. if (clickInGutter(cm, e)) { return }
  6160. var start = posFromMouse(cm, e)
  6161. window.focus()
  6162. switch (e_button(e)) {
  6163. case 1:
  6164. // #3261: make sure, that we're not starting a second selection
  6165. if (cm.state.selectingText)
  6166. { cm.state.selectingText(e) }
  6167. else if (start)
  6168. { leftButtonDown(cm, e, start) }
  6169. else if (e_target(e) == display.scroller)
  6170. { e_preventDefault(e) }
  6171. break
  6172. case 2:
  6173. if (webkit) { cm.state.lastMiddleDown = +new Date }
  6174. if (start) { extendSelection(cm.doc, start) }
  6175. setTimeout(function () { return display.input.focus(); }, 20)
  6176. e_preventDefault(e)
  6177. break
  6178. case 3:
  6179. if (captureRightClick) { onContextMenu(cm, e) }
  6180. else { delayBlurEvent(cm) }
  6181. break
  6182. }
  6183. }
  6184. var lastClick;
  6185. var lastDoubleClick;
  6186. function leftButtonDown(cm, e, start) {
  6187. if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
  6188. else { cm.curOp.focus = activeElt() }
  6189. var now = +new Date, type
  6190. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  6191. type = "triple"
  6192. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  6193. type = "double"
  6194. lastDoubleClick = {time: now, pos: start}
  6195. } else {
  6196. type = "single"
  6197. lastClick = {time: now, pos: start}
  6198. }
  6199. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained
  6200. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6201. type == "single" && (contained = sel.contains(start)) > -1 &&
  6202. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  6203. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  6204. { leftButtonStartDrag(cm, e, start, modifier) }
  6205. else
  6206. { leftButtonSelect(cm, e, start, type, modifier) }
  6207. }
  6208. // Start a text drag. When it ends, see if any dragging actually
  6209. // happen, and treat as a click if it didn't.
  6210. function leftButtonStartDrag(cm, e, start, modifier) {
  6211. var display = cm.display, startTime = +new Date
  6212. var dragEnd = operation(cm, function (e2) {
  6213. if (webkit) { display.scroller.draggable = false }
  6214. cm.state.draggingText = false
  6215. off(document, "mouseup", dragEnd)
  6216. off(display.scroller, "drop", dragEnd)
  6217. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  6218. e_preventDefault(e2)
  6219. if (!modifier && +new Date - 200 < startTime)
  6220. { extendSelection(cm.doc, start) }
  6221. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6222. if (webkit || ie && ie_version == 9)
  6223. { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) }
  6224. else
  6225. { display.input.focus() }
  6226. }
  6227. })
  6228. // Let the drag handler handle this.
  6229. if (webkit) { display.scroller.draggable = true }
  6230. cm.state.draggingText = dragEnd
  6231. dragEnd.copy = mac ? e.altKey : e.ctrlKey
  6232. // IE's approach to draggable
  6233. if (display.scroller.dragDrop) { display.scroller.dragDrop() }
  6234. on(document, "mouseup", dragEnd)
  6235. on(display.scroller, "drop", dragEnd)
  6236. }
  6237. // Normal selection, as opposed to text dragging.
  6238. function leftButtonSelect(cm, e, start, type, addNew) {
  6239. var display = cm.display, doc = cm.doc
  6240. e_preventDefault(e)
  6241. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  6242. if (addNew && !e.shiftKey) {
  6243. ourIndex = doc.sel.contains(start)
  6244. if (ourIndex > -1)
  6245. { ourRange = ranges[ourIndex] }
  6246. else
  6247. { ourRange = new Range(start, start) }
  6248. } else {
  6249. ourRange = doc.sel.primary()
  6250. ourIndex = doc.sel.primIndex
  6251. }
  6252. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  6253. type = "rect"
  6254. if (!addNew) { ourRange = new Range(start, start) }
  6255. start = posFromMouse(cm, e, true, true)
  6256. ourIndex = -1
  6257. } else if (type == "double") {
  6258. var word = cm.findWordAt(start)
  6259. if (cm.display.shift || doc.extend)
  6260. { ourRange = extendRange(doc, ourRange, word.anchor, word.head) }
  6261. else
  6262. { ourRange = word }
  6263. } else if (type == "triple") {
  6264. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)))
  6265. if (cm.display.shift || doc.extend)
  6266. { ourRange = extendRange(doc, ourRange, line.anchor, line.head) }
  6267. else
  6268. { ourRange = line }
  6269. } else {
  6270. ourRange = extendRange(doc, ourRange, start)
  6271. }
  6272. if (!addNew) {
  6273. ourIndex = 0
  6274. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  6275. startSel = doc.sel
  6276. } else if (ourIndex == -1) {
  6277. ourIndex = ranges.length
  6278. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6279. {scroll: false, origin: "*mouse"})
  6280. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  6281. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6282. {scroll: false, origin: "*mouse"})
  6283. startSel = doc.sel
  6284. } else {
  6285. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  6286. }
  6287. var lastPos = start
  6288. function extendTo(pos) {
  6289. if (cmp(lastPos, pos) == 0) { return }
  6290. lastPos = pos
  6291. if (type == "rect") {
  6292. var ranges = [], tabSize = cm.options.tabSize
  6293. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  6294. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  6295. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  6296. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6297. line <= end; line++) {
  6298. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  6299. if (left == right)
  6300. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
  6301. else if (text.length > leftPos)
  6302. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
  6303. }
  6304. if (!ranges.length) { ranges.push(new Range(start, start)) }
  6305. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6306. {origin: "*mouse", scroll: false})
  6307. cm.scrollIntoView(pos)
  6308. } else {
  6309. var oldRange = ourRange
  6310. var anchor = oldRange.anchor, head = pos
  6311. if (type != "single") {
  6312. var range
  6313. if (type == "double")
  6314. { range = cm.findWordAt(pos) }
  6315. else
  6316. { range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) }
  6317. if (cmp(range.anchor, anchor) > 0) {
  6318. head = range.head
  6319. anchor = minPos(oldRange.from(), range.anchor)
  6320. } else {
  6321. head = range.anchor
  6322. anchor = maxPos(oldRange.to(), range.head)
  6323. }
  6324. }
  6325. var ranges$1 = startSel.ranges.slice(0)
  6326. ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head)
  6327. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
  6328. }
  6329. }
  6330. var editorSize = display.wrapper.getBoundingClientRect()
  6331. // Used to ensure timeout re-tries don't fire when another extend
  6332. // happened in the meantime (clearTimeout isn't reliable -- at
  6333. // least on Chrome, the timeouts still happen even when cleared,
  6334. // if the clear happens after their scheduled firing time).
  6335. var counter = 0
  6336. function extend(e) {
  6337. var curCount = ++counter
  6338. var cur = posFromMouse(cm, e, true, type == "rect")
  6339. if (!cur) { return }
  6340. if (cmp(cur, lastPos) != 0) {
  6341. cm.curOp.focus = activeElt()
  6342. extendTo(cur)
  6343. var visible = visibleLines(display, doc)
  6344. if (cur.line >= visible.to || cur.line < visible.from)
  6345. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
  6346. } else {
  6347. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  6348. if (outside) { setTimeout(operation(cm, function () {
  6349. if (counter != curCount) { return }
  6350. display.scroller.scrollTop += outside
  6351. extend(e)
  6352. }), 50) }
  6353. }
  6354. }
  6355. function done(e) {
  6356. cm.state.selectingText = false
  6357. counter = Infinity
  6358. e_preventDefault(e)
  6359. display.input.focus()
  6360. off(document, "mousemove", move)
  6361. off(document, "mouseup", up)
  6362. doc.history.lastSelOrigin = null
  6363. }
  6364. var move = operation(cm, function (e) {
  6365. if (!e_button(e)) { done(e) }
  6366. else { extend(e) }
  6367. })
  6368. var up = operation(cm, done)
  6369. cm.state.selectingText = up
  6370. on(document, "mousemove", move)
  6371. on(document, "mouseup", up)
  6372. }
  6373. // Determines whether an event happened in the gutter, and fires the
  6374. // handlers for the corresponding event.
  6375. function gutterEvent(cm, e, type, prevent) {
  6376. var mX, mY
  6377. try { mX = e.clientX; mY = e.clientY }
  6378. catch(e) { return false }
  6379. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6380. if (prevent) { e_preventDefault(e) }
  6381. var display = cm.display
  6382. var lineBox = display.lineDiv.getBoundingClientRect()
  6383. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6384. mY -= lineBox.top - display.viewOffset
  6385. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6386. var g = display.gutters.childNodes[i]
  6387. if (g && g.getBoundingClientRect().right >= mX) {
  6388. var line = lineAtHeight(cm.doc, mY)
  6389. var gutter = cm.options.gutters[i]
  6390. signal(cm, type, cm, line, gutter, e)
  6391. return e_defaultPrevented(e)
  6392. }
  6393. }
  6394. }
  6395. function clickInGutter(cm, e) {
  6396. return gutterEvent(cm, e, "gutterClick", true)
  6397. }
  6398. // CONTEXT MENU HANDLING
  6399. // To make the context menu work, we need to briefly unhide the
  6400. // textarea (making it as unobtrusive as possible) to let the
  6401. // right-click take effect on it.
  6402. function onContextMenu(cm, e) {
  6403. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6404. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6405. cm.display.input.onContextMenu(e)
  6406. }
  6407. function contextMenuInGutter(cm, e) {
  6408. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6409. return gutterEvent(cm, e, "gutterContextMenu", false)
  6410. }
  6411. function themeChanged(cm) {
  6412. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6413. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
  6414. clearCaches(cm)
  6415. }
  6416. var Init = {toString: function(){return "CodeMirror.Init"}}
  6417. var defaults = {}
  6418. var optionHandlers = {}
  6419. function defineOptions(CodeMirror) {
  6420. var optionHandlers = CodeMirror.optionHandlers
  6421. function option(name, deflt, handle, notOnInit) {
  6422. CodeMirror.defaults[name] = deflt
  6423. if (handle) { optionHandlers[name] =
  6424. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
  6425. }
  6426. CodeMirror.defineOption = option
  6427. // Passed to option handlers when there is no old value.
  6428. CodeMirror.Init = Init
  6429. // These two are, on init, called from the constructor because they
  6430. // have to be initialized before the editor can start at all.
  6431. option("value", "", function (cm, val) { return cm.setValue(val); }, true)
  6432. option("mode", null, function (cm, val) {
  6433. cm.doc.modeOption = val
  6434. loadMode(cm)
  6435. }, true)
  6436. option("indentUnit", 2, loadMode, true)
  6437. option("indentWithTabs", false)
  6438. option("smartIndent", true)
  6439. option("tabSize", 4, function (cm) {
  6440. resetModeState(cm)
  6441. clearCaches(cm)
  6442. regChange(cm)
  6443. }, true)
  6444. option("lineSeparator", null, function (cm, val) {
  6445. cm.doc.lineSep = val
  6446. if (!val) { return }
  6447. var newBreaks = [], lineNo = cm.doc.first
  6448. cm.doc.iter(function (line) {
  6449. for (var pos = 0;;) {
  6450. var found = line.text.indexOf(val, pos)
  6451. if (found == -1) { break }
  6452. pos = found + val.length
  6453. newBreaks.push(Pos(lineNo, found))
  6454. }
  6455. lineNo++
  6456. })
  6457. for (var i = newBreaks.length - 1; i >= 0; i--)
  6458. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
  6459. })
  6460. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6461. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
  6462. if (old != Init) { cm.refresh() }
  6463. })
  6464. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
  6465. option("electricChars", true)
  6466. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6467. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6468. }, true)
  6469. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
  6470. option("rtlMoveVisually", !windows)
  6471. option("wholeLineUpdateBefore", true)
  6472. option("theme", "default", function (cm) {
  6473. themeChanged(cm)
  6474. guttersChanged(cm)
  6475. }, true)
  6476. option("keyMap", "default", function (cm, val, old) {
  6477. var next = getKeyMap(val)
  6478. var prev = old != Init && getKeyMap(old)
  6479. if (prev && prev.detach) { prev.detach(cm, next) }
  6480. if (next.attach) { next.attach(cm, prev || null) }
  6481. })
  6482. option("extraKeys", null)
  6483. option("lineWrapping", false, wrappingChanged, true)
  6484. option("gutters", [], function (cm) {
  6485. setGuttersForLineNumbers(cm.options)
  6486. guttersChanged(cm)
  6487. }, true)
  6488. option("fixedGutter", true, function (cm, val) {
  6489. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
  6490. cm.refresh()
  6491. }, true)
  6492. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
  6493. option("scrollbarStyle", "native", function (cm) {
  6494. initScrollbars(cm)
  6495. updateScrollbars(cm)
  6496. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  6497. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  6498. }, true)
  6499. option("lineNumbers", false, function (cm) {
  6500. setGuttersForLineNumbers(cm.options)
  6501. guttersChanged(cm)
  6502. }, true)
  6503. option("firstLineNumber", 1, guttersChanged, true)
  6504. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
  6505. option("showCursorWhenSelecting", false, updateSelection, true)
  6506. option("resetSelectionOnContextMenu", true)
  6507. option("lineWiseCopyCut", true)
  6508. option("readOnly", false, function (cm, val) {
  6509. if (val == "nocursor") {
  6510. onBlur(cm)
  6511. cm.display.input.blur()
  6512. cm.display.disabled = true
  6513. } else {
  6514. cm.display.disabled = false
  6515. }
  6516. cm.display.input.readOnlyChanged(val)
  6517. })
  6518. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
  6519. option("dragDrop", true, dragDropChanged)
  6520. option("allowDropFileTypes", null)
  6521. option("cursorBlinkRate", 530)
  6522. option("cursorScrollMargin", 0)
  6523. option("cursorHeight", 1, updateSelection, true)
  6524. option("singleCursorHeightPerLine", true, updateSelection, true)
  6525. option("workTime", 100)
  6526. option("workDelay", 100)
  6527. option("flattenSpans", true, resetModeState, true)
  6528. option("addModeClass", false, resetModeState, true)
  6529. option("pollInterval", 100)
  6530. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
  6531. option("historyEventDelay", 1250)
  6532. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true)
  6533. option("maxHighlightLength", 10000, resetModeState, true)
  6534. option("moveInputWithCursor", true, function (cm, val) {
  6535. if (!val) { cm.display.input.resetPosition() }
  6536. })
  6537. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; })
  6538. option("autofocus", null)
  6539. }
  6540. function guttersChanged(cm) {
  6541. updateGutters(cm)
  6542. regChange(cm)
  6543. alignHorizontally(cm)
  6544. }
  6545. function dragDropChanged(cm, value, old) {
  6546. var wasOn = old && old != Init
  6547. if (!value != !wasOn) {
  6548. var funcs = cm.display.dragFunctions
  6549. var toggle = value ? on : off
  6550. toggle(cm.display.scroller, "dragstart", funcs.start)
  6551. toggle(cm.display.scroller, "dragenter", funcs.enter)
  6552. toggle(cm.display.scroller, "dragover", funcs.over)
  6553. toggle(cm.display.scroller, "dragleave", funcs.leave)
  6554. toggle(cm.display.scroller, "drop", funcs.drop)
  6555. }
  6556. }
  6557. function wrappingChanged(cm) {
  6558. if (cm.options.lineWrapping) {
  6559. addClass(cm.display.wrapper, "CodeMirror-wrap")
  6560. cm.display.sizer.style.minWidth = ""
  6561. cm.display.sizerWidth = null
  6562. } else {
  6563. rmClass(cm.display.wrapper, "CodeMirror-wrap")
  6564. findMaxLine(cm)
  6565. }
  6566. estimateLineHeights(cm)
  6567. regChange(cm)
  6568. clearCaches(cm)
  6569. setTimeout(function () { return updateScrollbars(cm); }, 100)
  6570. }
  6571. // A CodeMirror instance represents an editor. This is the object
  6572. // that user code is usually dealing with.
  6573. function CodeMirror(place, options) {
  6574. var this$1 = this;
  6575. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  6576. this.options = options = options ? copyObj(options) : {}
  6577. // Determine effective options based on given values and defaults.
  6578. copyObj(defaults, options, false)
  6579. setGuttersForLineNumbers(options)
  6580. var doc = options.value
  6581. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator) }
  6582. this.doc = doc
  6583. var input = new CodeMirror.inputStyles[options.inputStyle](this)
  6584. var display = this.display = new Display(place, doc, input)
  6585. display.wrapper.CodeMirror = this
  6586. updateGutters(this)
  6587. themeChanged(this)
  6588. if (options.lineWrapping)
  6589. { this.display.wrapper.className += " CodeMirror-wrap" }
  6590. initScrollbars(this)
  6591. this.state = {
  6592. keyMaps: [], // stores maps added by addKeyMap
  6593. overlays: [], // highlighting overlays, as added by addOverlay
  6594. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  6595. overwrite: false,
  6596. delayingBlurEvent: false,
  6597. focused: false,
  6598. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  6599. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  6600. selectingText: false,
  6601. draggingText: false,
  6602. highlight: new Delayed(), // stores highlight worker timeout
  6603. keySeq: null, // Unfinished key sequence
  6604. specialChars: null
  6605. }
  6606. if (options.autofocus && !mobile) { display.input.focus() }
  6607. // Override magic textarea content restore that IE sometimes does
  6608. // on our hidden textarea on reload
  6609. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
  6610. registerEventHandlers(this)
  6611. ensureGlobalHandlers()
  6612. startOperation(this)
  6613. this.curOp.forceUpdate = true
  6614. attachDoc(this, doc)
  6615. if ((options.autofocus && !mobile) || this.hasFocus())
  6616. { setTimeout(bind(onFocus, this), 20) }
  6617. else
  6618. { onBlur(this) }
  6619. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  6620. { optionHandlers[opt](this$1, options[opt], Init) } }
  6621. maybeUpdateLineNumberWidth(this)
  6622. if (options.finishInit) { options.finishInit(this) }
  6623. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
  6624. endOperation(this)
  6625. // Suppress optimizelegibility in Webkit, since it breaks text
  6626. // measuring on line wrapping boundaries.
  6627. if (webkit && options.lineWrapping &&
  6628. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  6629. { display.lineDiv.style.textRendering = "auto" }
  6630. }
  6631. // The default configuration options.
  6632. CodeMirror.defaults = defaults
  6633. // Functions to run when options are changed.
  6634. CodeMirror.optionHandlers = optionHandlers
  6635. // Attach the necessary event handlers when initializing the editor
  6636. function registerEventHandlers(cm) {
  6637. var d = cm.display
  6638. on(d.scroller, "mousedown", operation(cm, onMouseDown))
  6639. // Older IE's will not fire a second mousedown for a double click
  6640. if (ie && ie_version < 11)
  6641. { on(d.scroller, "dblclick", operation(cm, function (e) {
  6642. if (signalDOMEvent(cm, e)) { return }
  6643. var pos = posFromMouse(cm, e)
  6644. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  6645. e_preventDefault(e)
  6646. var word = cm.findWordAt(pos)
  6647. extendSelection(cm.doc, word.anchor, word.head)
  6648. })) }
  6649. else
  6650. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
  6651. // Some browsers fire contextmenu *after* opening the menu, at
  6652. // which point we can't mess with it anymore. Context menu is
  6653. // handled in onMouseDown for these browsers.
  6654. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
  6655. // Used to suppress mouse event handling when a touch happens
  6656. var touchFinished, prevTouch = {end: 0}
  6657. function finishTouch() {
  6658. if (d.activeTouch) {
  6659. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
  6660. prevTouch = d.activeTouch
  6661. prevTouch.end = +new Date
  6662. }
  6663. }
  6664. function isMouseLikeTouchEvent(e) {
  6665. if (e.touches.length != 1) { return false }
  6666. var touch = e.touches[0]
  6667. return touch.radiusX <= 1 && touch.radiusY <= 1
  6668. }
  6669. function farAway(touch, other) {
  6670. if (other.left == null) { return true }
  6671. var dx = other.left - touch.left, dy = other.top - touch.top
  6672. return dx * dx + dy * dy > 20 * 20
  6673. }
  6674. on(d.scroller, "touchstart", function (e) {
  6675. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  6676. d.input.ensurePolled()
  6677. clearTimeout(touchFinished)
  6678. var now = +new Date
  6679. d.activeTouch = {start: now, moved: false,
  6680. prev: now - prevTouch.end <= 300 ? prevTouch : null}
  6681. if (e.touches.length == 1) {
  6682. d.activeTouch.left = e.touches[0].pageX
  6683. d.activeTouch.top = e.touches[0].pageY
  6684. }
  6685. }
  6686. })
  6687. on(d.scroller, "touchmove", function () {
  6688. if (d.activeTouch) { d.activeTouch.moved = true }
  6689. })
  6690. on(d.scroller, "touchend", function (e) {
  6691. var touch = d.activeTouch
  6692. if (touch && !eventInWidget(d, e) && touch.left != null &&
  6693. !touch.moved && new Date - touch.start < 300) {
  6694. var pos = cm.coordsChar(d.activeTouch, "page"), range
  6695. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  6696. { range = new Range(pos, pos) }
  6697. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  6698. { range = cm.findWordAt(pos) }
  6699. else // Triple tap
  6700. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6701. cm.setSelection(range.anchor, range.head)
  6702. cm.focus()
  6703. e_preventDefault(e)
  6704. }
  6705. finishTouch()
  6706. })
  6707. on(d.scroller, "touchcancel", finishTouch)
  6708. // Sync scrolling between fake scrollbars and real scrollable
  6709. // area, ensure viewport is updated when scrolling.
  6710. on(d.scroller, "scroll", function () {
  6711. if (d.scroller.clientHeight) {
  6712. setScrollTop(cm, d.scroller.scrollTop)
  6713. setScrollLeft(cm, d.scroller.scrollLeft, true)
  6714. signal(cm, "scroll", cm)
  6715. }
  6716. })
  6717. // Listen to wheel events in order to try and update the viewport on time.
  6718. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); })
  6719. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); })
  6720. // Prevent wrapper from ever scrolling
  6721. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
  6722. d.dragFunctions = {
  6723. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
  6724. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
  6725. start: function (e) { return onDragStart(cm, e); },
  6726. drop: operation(cm, onDrop),
  6727. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
  6728. }
  6729. var inp = d.input.getField()
  6730. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); })
  6731. on(inp, "keydown", operation(cm, onKeyDown))
  6732. on(inp, "keypress", operation(cm, onKeyPress))
  6733. on(inp, "focus", function (e) { return onFocus(cm, e); })
  6734. on(inp, "blur", function (e) { return onBlur(cm, e); })
  6735. }
  6736. var initHooks = []
  6737. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }
  6738. // Indent the given line. The how parameter can be "smart",
  6739. // "add"/null, "subtract", or "prev". When aggressive is false
  6740. // (typically set to true for forced single-line indents), empty
  6741. // lines are not indented, and places where the mode returns Pass
  6742. // are left alone.
  6743. function indentLine(cm, n, how, aggressive) {
  6744. var doc = cm.doc, state
  6745. if (how == null) { how = "add" }
  6746. if (how == "smart") {
  6747. // Fall back to "prev" when the mode doesn't have an indentation
  6748. // method.
  6749. if (!doc.mode.indent) { how = "prev" }
  6750. else { state = getStateBefore(cm, n) }
  6751. }
  6752. var tabSize = cm.options.tabSize
  6753. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
  6754. if (line.stateAfter) { line.stateAfter = null }
  6755. var curSpaceString = line.text.match(/^\s*/)[0], indentation
  6756. if (!aggressive && !/\S/.test(line.text)) {
  6757. indentation = 0
  6758. how = "not"
  6759. } else if (how == "smart") {
  6760. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  6761. if (indentation == Pass || indentation > 150) {
  6762. if (!aggressive) { return }
  6763. how = "prev"
  6764. }
  6765. }
  6766. if (how == "prev") {
  6767. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
  6768. else { indentation = 0 }
  6769. } else if (how == "add") {
  6770. indentation = curSpace + cm.options.indentUnit
  6771. } else if (how == "subtract") {
  6772. indentation = curSpace - cm.options.indentUnit
  6773. } else if (typeof how == "number") {
  6774. indentation = curSpace + how
  6775. }
  6776. indentation = Math.max(0, indentation)
  6777. var indentString = "", pos = 0
  6778. if (cm.options.indentWithTabs)
  6779. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
  6780. if (pos < indentation) { indentString += spaceStr(indentation - pos) }
  6781. if (indentString != curSpaceString) {
  6782. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
  6783. line.stateAfter = null
  6784. return true
  6785. } else {
  6786. // Ensure that, if the cursor was in the whitespace at the start
  6787. // of the line, it is moved to the end of that space.
  6788. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  6789. var range = doc.sel.ranges[i$1]
  6790. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  6791. var pos$1 = Pos(n, curSpaceString.length)
  6792. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  6793. break
  6794. }
  6795. }
  6796. }
  6797. }
  6798. // This will be set to a {lineWise: bool, text: [string]} object, so
  6799. // that, when pasting, we know what kind of selections the copied
  6800. // text was made out of.
  6801. var lastCopied = null
  6802. function setLastCopied(newLastCopied) {
  6803. lastCopied = newLastCopied
  6804. }
  6805. function applyTextInput(cm, inserted, deleted, sel, origin) {
  6806. var doc = cm.doc
  6807. cm.display.shift = false
  6808. if (!sel) { sel = doc.sel }
  6809. var paste = cm.state.pasteIncoming || origin == "paste"
  6810. var textLines = splitLinesAuto(inserted), multiPaste = null
  6811. // When pasing N lines into N selections, insert one line per selection
  6812. if (paste && sel.ranges.length > 1) {
  6813. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  6814. if (sel.ranges.length % lastCopied.text.length == 0) {
  6815. multiPaste = []
  6816. for (var i = 0; i < lastCopied.text.length; i++)
  6817. { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
  6818. }
  6819. } else if (textLines.length == sel.ranges.length) {
  6820. multiPaste = map(textLines, function (l) { return [l]; })
  6821. }
  6822. }
  6823. var updateInput
  6824. // Normal behavior is to insert the new text into every selection
  6825. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  6826. var range = sel.ranges[i$1]
  6827. var from = range.from(), to = range.to()
  6828. if (range.empty()) {
  6829. if (deleted && deleted > 0) // Handle deletion
  6830. { from = Pos(from.line, from.ch - deleted) }
  6831. else if (cm.state.overwrite && !paste) // Handle overwrite
  6832. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
  6833. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  6834. { from = to = Pos(from.line, 0) }
  6835. }
  6836. updateInput = cm.curOp.updateInput
  6837. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  6838. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
  6839. makeChange(cm.doc, changeEvent)
  6840. signalLater(cm, "inputRead", cm, changeEvent)
  6841. }
  6842. if (inserted && !paste)
  6843. { triggerElectric(cm, inserted) }
  6844. ensureCursorVisible(cm)
  6845. cm.curOp.updateInput = updateInput
  6846. cm.curOp.typing = true
  6847. cm.state.pasteIncoming = cm.state.cutIncoming = false
  6848. }
  6849. function handlePaste(e, cm) {
  6850. var pasted = e.clipboardData && e.clipboardData.getData("Text")
  6851. if (pasted) {
  6852. e.preventDefault()
  6853. if (!cm.isReadOnly() && !cm.options.disableInput)
  6854. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
  6855. return true
  6856. }
  6857. }
  6858. function triggerElectric(cm, inserted) {
  6859. // When an 'electric' character is inserted, immediately trigger a reindent
  6860. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  6861. var sel = cm.doc.sel
  6862. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  6863. var range = sel.ranges[i]
  6864. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  6865. var mode = cm.getModeAt(range.head)
  6866. var indented = false
  6867. if (mode.electricChars) {
  6868. for (var j = 0; j < mode.electricChars.length; j++)
  6869. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  6870. indented = indentLine(cm, range.head.line, "smart")
  6871. break
  6872. } }
  6873. } else if (mode.electricInput) {
  6874. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  6875. { indented = indentLine(cm, range.head.line, "smart") }
  6876. }
  6877. if (indented) { signalLater(cm, "electricInput", cm, range.head.line) }
  6878. }
  6879. }
  6880. function copyableRanges(cm) {
  6881. var text = [], ranges = []
  6882. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  6883. var line = cm.doc.sel.ranges[i].head.line
  6884. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}
  6885. ranges.push(lineRange)
  6886. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  6887. }
  6888. return {text: text, ranges: ranges}
  6889. }
  6890. function disableBrowserMagic(field, spellcheck) {
  6891. field.setAttribute("autocorrect", "off")
  6892. field.setAttribute("autocapitalize", "off")
  6893. field.setAttribute("spellcheck", !!spellcheck)
  6894. }
  6895. function hiddenTextarea() {
  6896. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
  6897. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
  6898. // The textarea is kept positioned near the cursor to prevent the
  6899. // fact that it'll be scrolled into view on input from scrolling
  6900. // our fake cursor out of view. On webkit, when wrap=off, paste is
  6901. // very slow. So make the area wide instead.
  6902. if (webkit) { te.style.width = "1000px" }
  6903. else { te.setAttribute("wrap", "off") }
  6904. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  6905. if (ios) { te.style.border = "1px solid black" }
  6906. disableBrowserMagic(te)
  6907. return div
  6908. }
  6909. // The publicly visible API. Note that methodOp(f) means
  6910. // 'wrap f in an operation, performed on its `this` parameter'.
  6911. // This is not the complete set of editor methods. Most of the
  6912. // methods defined on the Doc type are also injected into
  6913. // CodeMirror.prototype, for backwards compatibility and
  6914. // convenience.
  6915. function addEditorMethods(CodeMirror) {
  6916. var optionHandlers = CodeMirror.optionHandlers
  6917. var helpers = CodeMirror.helpers = {}
  6918. CodeMirror.prototype = {
  6919. constructor: CodeMirror,
  6920. focus: function(){window.focus(); this.display.input.focus()},
  6921. setOption: function(option, value) {
  6922. var options = this.options, old = options[option]
  6923. if (options[option] == value && option != "mode") { return }
  6924. options[option] = value
  6925. if (optionHandlers.hasOwnProperty(option))
  6926. { operation(this, optionHandlers[option])(this, value, old) }
  6927. signal(this, "optionChange", this, option)
  6928. },
  6929. getOption: function(option) {return this.options[option]},
  6930. getDoc: function() {return this.doc},
  6931. addKeyMap: function(map, bottom) {
  6932. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map))
  6933. },
  6934. removeKeyMap: function(map) {
  6935. var maps = this.state.keyMaps
  6936. for (var i = 0; i < maps.length; ++i)
  6937. { if (maps[i] == map || maps[i].name == map) {
  6938. maps.splice(i, 1)
  6939. return true
  6940. } }
  6941. },
  6942. addOverlay: methodOp(function(spec, options) {
  6943. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  6944. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  6945. insertSorted(this.state.overlays,
  6946. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  6947. priority: (options && options.priority) || 0},
  6948. function (overlay) { return overlay.priority; })
  6949. this.state.modeGen++
  6950. regChange(this)
  6951. }),
  6952. removeOverlay: methodOp(function(spec) {
  6953. var this$1 = this;
  6954. var overlays = this.state.overlays
  6955. for (var i = 0; i < overlays.length; ++i) {
  6956. var cur = overlays[i].modeSpec
  6957. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  6958. overlays.splice(i, 1)
  6959. this$1.state.modeGen++
  6960. regChange(this$1)
  6961. return
  6962. }
  6963. }
  6964. }),
  6965. indentLine: methodOp(function(n, dir, aggressive) {
  6966. if (typeof dir != "string" && typeof dir != "number") {
  6967. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
  6968. else { dir = dir ? "add" : "subtract" }
  6969. }
  6970. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
  6971. }),
  6972. indentSelection: methodOp(function(how) {
  6973. var this$1 = this;
  6974. var ranges = this.doc.sel.ranges, end = -1
  6975. for (var i = 0; i < ranges.length; i++) {
  6976. var range = ranges[i]
  6977. if (!range.empty()) {
  6978. var from = range.from(), to = range.to()
  6979. var start = Math.max(end, from.line)
  6980. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  6981. for (var j = start; j < end; ++j)
  6982. { indentLine(this$1, j, how) }
  6983. var newRanges = this$1.doc.sel.ranges
  6984. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  6985. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
  6986. } else if (range.head.line > end) {
  6987. indentLine(this$1, range.head.line, how, true)
  6988. end = range.head.line
  6989. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
  6990. }
  6991. }
  6992. }),
  6993. // Fetch the parser token for a given character. Useful for hacks
  6994. // that want to inspect the mode state (say, for completion).
  6995. getTokenAt: function(pos, precise) {
  6996. return takeToken(this, pos, precise)
  6997. },
  6998. getLineTokens: function(line, precise) {
  6999. return takeToken(this, Pos(line), precise, true)
  7000. },
  7001. getTokenTypeAt: function(pos) {
  7002. pos = clipPos(this.doc, pos)
  7003. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  7004. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
  7005. var type
  7006. if (ch == 0) { type = styles[2] }
  7007. else { for (;;) {
  7008. var mid = (before + after) >> 1
  7009. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
  7010. else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
  7011. else { type = styles[mid * 2 + 2]; break }
  7012. } }
  7013. var cut = type ? type.indexOf("overlay ") : -1
  7014. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7015. },
  7016. getModeAt: function(pos) {
  7017. var mode = this.doc.mode
  7018. if (!mode.innerMode) { return mode }
  7019. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7020. },
  7021. getHelper: function(pos, type) {
  7022. return this.getHelpers(pos, type)[0]
  7023. },
  7024. getHelpers: function(pos, type) {
  7025. var this$1 = this;
  7026. var found = []
  7027. if (!helpers.hasOwnProperty(type)) { return found }
  7028. var help = helpers[type], mode = this.getModeAt(pos)
  7029. if (typeof mode[type] == "string") {
  7030. if (help[mode[type]]) { found.push(help[mode[type]]) }
  7031. } else if (mode[type]) {
  7032. for (var i = 0; i < mode[type].length; i++) {
  7033. var val = help[mode[type][i]]
  7034. if (val) { found.push(val) }
  7035. }
  7036. } else if (mode.helperType && help[mode.helperType]) {
  7037. found.push(help[mode.helperType])
  7038. } else if (help[mode.name]) {
  7039. found.push(help[mode.name])
  7040. }
  7041. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7042. var cur = help._global[i$1]
  7043. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7044. { found.push(cur.val) }
  7045. }
  7046. return found
  7047. },
  7048. getStateAfter: function(line, precise) {
  7049. var doc = this.doc
  7050. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
  7051. return getStateBefore(this, line + 1, precise)
  7052. },
  7053. cursorCoords: function(start, mode) {
  7054. var pos, range = this.doc.sel.primary()
  7055. if (start == null) { pos = range.head }
  7056. else if (typeof start == "object") { pos = clipPos(this.doc, start) }
  7057. else { pos = start ? range.from() : range.to() }
  7058. return cursorCoords(this, pos, mode || "page")
  7059. },
  7060. charCoords: function(pos, mode) {
  7061. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7062. },
  7063. coordsChar: function(coords, mode) {
  7064. coords = fromCoordSystem(this, coords, mode || "page")
  7065. return coordsChar(this, coords.left, coords.top)
  7066. },
  7067. lineAtHeight: function(height, mode) {
  7068. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
  7069. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7070. },
  7071. heightAtLine: function(line, mode, includeWidgets) {
  7072. var end = false, lineObj
  7073. if (typeof line == "number") {
  7074. var last = this.doc.first + this.doc.size - 1
  7075. if (line < this.doc.first) { line = this.doc.first }
  7076. else if (line > last) { line = last; end = true }
  7077. lineObj = getLine(this.doc, line)
  7078. } else {
  7079. lineObj = line
  7080. }
  7081. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets).top +
  7082. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7083. },
  7084. defaultTextHeight: function() { return textHeight(this.display) },
  7085. defaultCharWidth: function() { return charWidth(this.display) },
  7086. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7087. addWidget: function(pos, node, scroll, vert, horiz) {
  7088. var display = this.display
  7089. pos = cursorCoords(this, clipPos(this.doc, pos))
  7090. var top = pos.bottom, left = pos.left
  7091. node.style.position = "absolute"
  7092. node.setAttribute("cm-ignore-events", "true")
  7093. this.display.input.setUneditable(node)
  7094. display.sizer.appendChild(node)
  7095. if (vert == "over") {
  7096. top = pos.top
  7097. } else if (vert == "above" || vert == "near") {
  7098. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7099. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  7100. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7101. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7102. { top = pos.top - node.offsetHeight }
  7103. else if (pos.bottom + node.offsetHeight <= vspace)
  7104. { top = pos.bottom }
  7105. if (left + node.offsetWidth > hspace)
  7106. { left = hspace - node.offsetWidth }
  7107. }
  7108. node.style.top = top + "px"
  7109. node.style.left = node.style.right = ""
  7110. if (horiz == "right") {
  7111. left = display.sizer.clientWidth - node.offsetWidth
  7112. node.style.right = "0px"
  7113. } else {
  7114. if (horiz == "left") { left = 0 }
  7115. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
  7116. node.style.left = left + "px"
  7117. }
  7118. if (scroll)
  7119. { scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight) }
  7120. },
  7121. triggerOnKeyDown: methodOp(onKeyDown),
  7122. triggerOnKeyPress: methodOp(onKeyPress),
  7123. triggerOnKeyUp: onKeyUp,
  7124. execCommand: function(cmd) {
  7125. if (commands.hasOwnProperty(cmd))
  7126. { return commands[cmd].call(null, this) }
  7127. },
  7128. triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
  7129. findPosH: function(from, amount, unit, visually) {
  7130. var this$1 = this;
  7131. var dir = 1
  7132. if (amount < 0) { dir = -1; amount = -amount }
  7133. var cur = clipPos(this.doc, from)
  7134. for (var i = 0; i < amount; ++i) {
  7135. cur = findPosH(this$1.doc, cur, dir, unit, visually)
  7136. if (cur.hitSide) { break }
  7137. }
  7138. return cur
  7139. },
  7140. moveH: methodOp(function(dir, unit) {
  7141. var this$1 = this;
  7142. this.extendSelectionsBy(function (range) {
  7143. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7144. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7145. else
  7146. { return dir < 0 ? range.from() : range.to() }
  7147. }, sel_move)
  7148. }),
  7149. deleteH: methodOp(function(dir, unit) {
  7150. var sel = this.doc.sel, doc = this.doc
  7151. if (sel.somethingSelected())
  7152. { doc.replaceSelection("", null, "+delete") }
  7153. else
  7154. { deleteNearSelection(this, function (range) {
  7155. var other = findPosH(doc, range.head, dir, unit, false)
  7156. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7157. }) }
  7158. }),
  7159. findPosV: function(from, amount, unit, goalColumn) {
  7160. var this$1 = this;
  7161. var dir = 1, x = goalColumn
  7162. if (amount < 0) { dir = -1; amount = -amount }
  7163. var cur = clipPos(this.doc, from)
  7164. for (var i = 0; i < amount; ++i) {
  7165. var coords = cursorCoords(this$1, cur, "div")
  7166. if (x == null) { x = coords.left }
  7167. else { coords.left = x }
  7168. cur = findPosV(this$1, coords, dir, unit)
  7169. if (cur.hitSide) { break }
  7170. }
  7171. return cur
  7172. },
  7173. moveV: methodOp(function(dir, unit) {
  7174. var this$1 = this;
  7175. var doc = this.doc, goals = []
  7176. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  7177. doc.extendSelectionsBy(function (range) {
  7178. if (collapse)
  7179. { return dir < 0 ? range.from() : range.to() }
  7180. var headPos = cursorCoords(this$1, range.head, "div")
  7181. if (range.goalColumn != null) { headPos.left = range.goalColumn }
  7182. goals.push(headPos.left)
  7183. var pos = findPosV(this$1, headPos, dir, unit)
  7184. if (unit == "page" && range == doc.sel.primary())
  7185. { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top) }
  7186. return pos
  7187. }, sel_move)
  7188. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7189. { doc.sel.ranges[i].goalColumn = goals[i] } }
  7190. }),
  7191. // Find the word at the given position (as returned by coordsChar).
  7192. findWordAt: function(pos) {
  7193. var doc = this.doc, line = getLine(doc, pos.line).text
  7194. var start = pos.ch, end = pos.ch
  7195. if (line) {
  7196. var helper = this.getHelper(pos, "wordChars")
  7197. if ((pos.xRel < 0 || end == line.length) && start) { --start; } else { ++end }
  7198. var startChar = line.charAt(start)
  7199. var check = isWordChar(startChar, helper)
  7200. ? function (ch) { return isWordChar(ch, helper); }
  7201. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7202. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
  7203. while (start > 0 && check(line.charAt(start - 1))) { --start }
  7204. while (end < line.length && check(line.charAt(end))) { ++end }
  7205. }
  7206. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7207. },
  7208. toggleOverwrite: function(value) {
  7209. if (value != null && value == this.state.overwrite) { return }
  7210. if (this.state.overwrite = !this.state.overwrite)
  7211. { addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7212. else
  7213. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7214. signal(this, "overwriteToggle", this, this.state.overwrite)
  7215. },
  7216. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7217. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7218. scrollTo: methodOp(function(x, y) {
  7219. if (x != null || y != null) { resolveScrollToPos(this) }
  7220. if (x != null) { this.curOp.scrollLeft = x }
  7221. if (y != null) { this.curOp.scrollTop = y }
  7222. }),
  7223. getScrollInfo: function() {
  7224. var scroller = this.display.scroller
  7225. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7226. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7227. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7228. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7229. },
  7230. scrollIntoView: methodOp(function(range, margin) {
  7231. if (range == null) {
  7232. range = {from: this.doc.sel.primary().head, to: null}
  7233. if (margin == null) { margin = this.options.cursorScrollMargin }
  7234. } else if (typeof range == "number") {
  7235. range = {from: Pos(range, 0), to: null}
  7236. } else if (range.from == null) {
  7237. range = {from: range, to: null}
  7238. }
  7239. if (!range.to) { range.to = range.from }
  7240. range.margin = margin || 0
  7241. if (range.from.line != null) {
  7242. resolveScrollToPos(this)
  7243. this.curOp.scrollToPos = range
  7244. } else {
  7245. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  7246. Math.min(range.from.top, range.to.top) - range.margin,
  7247. Math.max(range.from.right, range.to.right),
  7248. Math.max(range.from.bottom, range.to.bottom) + range.margin)
  7249. this.scrollTo(sPos.scrollLeft, sPos.scrollTop)
  7250. }
  7251. }),
  7252. setSize: methodOp(function(width, height) {
  7253. var this$1 = this;
  7254. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }
  7255. if (width != null) { this.display.wrapper.style.width = interpret(width) }
  7256. if (height != null) { this.display.wrapper.style.height = interpret(height) }
  7257. if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
  7258. var lineNo = this.display.viewFrom
  7259. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7260. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7261. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7262. ++lineNo
  7263. })
  7264. this.curOp.forceUpdate = true
  7265. signal(this, "refresh", this)
  7266. }),
  7267. operation: function(f){return runInOp(this, f)},
  7268. refresh: methodOp(function() {
  7269. var oldHeight = this.display.cachedTextHeight
  7270. regChange(this)
  7271. this.curOp.forceUpdate = true
  7272. clearCaches(this)
  7273. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop)
  7274. updateGutterSpace(this)
  7275. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7276. { estimateLineHeights(this) }
  7277. signal(this, "refresh", this)
  7278. }),
  7279. swapDoc: methodOp(function(doc) {
  7280. var old = this.doc
  7281. old.cm = null
  7282. attachDoc(this, doc)
  7283. clearCaches(this)
  7284. this.display.input.reset()
  7285. this.scrollTo(doc.scrollLeft, doc.scrollTop)
  7286. this.curOp.forceScroll = true
  7287. signalLater(this, "swapDoc", this, old)
  7288. return old
  7289. }),
  7290. getInputField: function(){return this.display.input.getField()},
  7291. getWrapperElement: function(){return this.display.wrapper},
  7292. getScrollerElement: function(){return this.display.scroller},
  7293. getGutterElement: function(){return this.display.gutters}
  7294. }
  7295. eventMixin(CodeMirror)
  7296. CodeMirror.registerHelper = function(type, name, value) {
  7297. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
  7298. helpers[type][name] = value
  7299. }
  7300. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7301. CodeMirror.registerHelper(type, name, value)
  7302. helpers[type]._global.push({pred: predicate, val: value})
  7303. }
  7304. }
  7305. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7306. // right), unit can be "char", "column" (like char, but doesn't
  7307. // cross line boundaries), "word" (across next word), or "group" (to
  7308. // the start of next group of word or non-word-non-whitespace
  7309. // chars). The visually param controls whether, in right-to-left
  7310. // text, direction 1 means to move towards the next index in the
  7311. // string, or towards the character to the right of the current
  7312. // position. The resulting position will have a hitSide=true
  7313. // property if it reached the end of the document.
  7314. function findPosH(doc, pos, dir, unit, visually) {
  7315. var line = pos.line, ch = pos.ch, origDir = dir
  7316. var lineObj = getLine(doc, line)
  7317. function findNextLine() {
  7318. var l = line + dir
  7319. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7320. line = l
  7321. return lineObj = getLine(doc, l)
  7322. }
  7323. function moveOnce(boundToLine) {
  7324. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true)
  7325. if (next == null) {
  7326. if (!boundToLine && findNextLine()) {
  7327. if (visually) { ch = (dir < 0 ? lineRight : lineLeft)(lineObj) }
  7328. else { ch = dir < 0 ? lineObj.text.length : 0 }
  7329. } else { return false }
  7330. } else { ch = next }
  7331. return true
  7332. }
  7333. if (unit == "char") {
  7334. moveOnce()
  7335. } else if (unit == "column") {
  7336. moveOnce(true)
  7337. } else if (unit == "word" || unit == "group") {
  7338. var sawType = null, group = unit == "group"
  7339. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
  7340. for (var first = true;; first = false) {
  7341. if (dir < 0 && !moveOnce(!first)) { break }
  7342. var cur = lineObj.text.charAt(ch) || "\n"
  7343. var type = isWordChar(cur, helper) ? "w"
  7344. : group && cur == "\n" ? "n"
  7345. : !group || /\s/.test(cur) ? null
  7346. : "p"
  7347. if (group && !first && !type) { type = "s" }
  7348. if (sawType && sawType != type) {
  7349. if (dir < 0) {dir = 1; moveOnce()}
  7350. break
  7351. }
  7352. if (type) { sawType = type }
  7353. if (dir > 0 && !moveOnce(!first)) { break }
  7354. }
  7355. }
  7356. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true)
  7357. if (!cmp(pos, result)) { result.hitSide = true }
  7358. return result
  7359. }
  7360. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7361. // "page" or "line". The resulting position will have a hitSide=true
  7362. // property if it reached the end of the document.
  7363. function findPosV(cm, pos, dir, unit) {
  7364. var doc = cm.doc, x = pos.left, y
  7365. if (unit == "page") {
  7366. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  7367. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
  7368. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  7369. } else if (unit == "line") {
  7370. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  7371. }
  7372. var target
  7373. for (;;) {
  7374. target = coordsChar(cm, x, y)
  7375. if (!target.outside) { break }
  7376. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7377. y += dir * 5
  7378. }
  7379. return target
  7380. }
  7381. // CONTENTEDITABLE INPUT STYLE
  7382. var ContentEditableInput = function(cm) {
  7383. this.cm = cm
  7384. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  7385. this.polling = new Delayed()
  7386. this.composing = null
  7387. this.gracePeriod = false
  7388. this.readDOMTimeout = null
  7389. };
  7390. ContentEditableInput.prototype.init = function (display) {
  7391. var this$1 = this;
  7392. var input = this, cm = input.cm
  7393. var div = input.div = display.lineDiv
  7394. disableBrowserMagic(div, cm.options.spellcheck)
  7395. on(div, "paste", function (e) {
  7396. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7397. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7398. if (ie_version <= 11) { setTimeout(operation(cm, function () {
  7399. if (!input.pollContent()) { regChange(cm) }
  7400. }), 20) }
  7401. })
  7402. on(div, "compositionstart", function (e) {
  7403. this$1.composing = {data: e.data, done: false}
  7404. })
  7405. on(div, "compositionupdate", function (e) {
  7406. if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
  7407. })
  7408. on(div, "compositionend", function (e) {
  7409. if (this$1.composing) {
  7410. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
  7411. this$1.composing.done = true
  7412. }
  7413. })
  7414. on(div, "touchstart", function () { return input.forceCompositionEnd(); })
  7415. on(div, "input", function () {
  7416. if (!this$1.composing) { this$1.readFromDOMSoon() }
  7417. })
  7418. function onCopyCut(e) {
  7419. if (signalDOMEvent(cm, e)) { return }
  7420. if (cm.somethingSelected()) {
  7421. setLastCopied({lineWise: false, text: cm.getSelections()})
  7422. if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
  7423. } else if (!cm.options.lineWiseCopyCut) {
  7424. return
  7425. } else {
  7426. var ranges = copyableRanges(cm)
  7427. setLastCopied({lineWise: true, text: ranges.text})
  7428. if (e.type == "cut") {
  7429. cm.operation(function () {
  7430. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  7431. cm.replaceSelection("", null, "cut")
  7432. })
  7433. }
  7434. }
  7435. if (e.clipboardData) {
  7436. e.clipboardData.clearData()
  7437. var content = lastCopied.text.join("\n")
  7438. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7439. e.clipboardData.setData("Text", content)
  7440. if (e.clipboardData.getData("Text") == content) {
  7441. e.preventDefault()
  7442. return
  7443. }
  7444. }
  7445. // Old-fashioned briefly-focus-a-textarea hack
  7446. var kludge = hiddenTextarea(), te = kludge.firstChild
  7447. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  7448. te.value = lastCopied.text.join("\n")
  7449. var hadFocus = document.activeElement
  7450. selectInput(te)
  7451. setTimeout(function () {
  7452. cm.display.lineSpace.removeChild(kludge)
  7453. hadFocus.focus()
  7454. if (hadFocus == div) { input.showPrimarySelection() }
  7455. }, 50)
  7456. }
  7457. on(div, "copy", onCopyCut)
  7458. on(div, "cut", onCopyCut)
  7459. };
  7460. ContentEditableInput.prototype.prepareSelection = function () {
  7461. var result = prepareSelection(this.cm, false)
  7462. result.focus = this.cm.state.focused
  7463. return result
  7464. };
  7465. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7466. if (!info || !this.cm.display.view.length) { return }
  7467. if (info.focus || takeFocus) { this.showPrimarySelection() }
  7468. this.showMultipleSelections(info)
  7469. };
  7470. ContentEditableInput.prototype.showPrimarySelection = function () {
  7471. var sel = window.getSelection(), prim = this.cm.doc.sel.primary()
  7472. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset)
  7473. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset)
  7474. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7475. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  7476. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  7477. { return }
  7478. var start = posToDOM(this.cm, prim.from())
  7479. var end = posToDOM(this.cm, prim.to())
  7480. if (!start && !end) { return }
  7481. var view = this.cm.display.view
  7482. var old = sel.rangeCount && sel.getRangeAt(0)
  7483. if (!start) {
  7484. start = {node: view[0].measure.map[2], offset: 0}
  7485. } else if (!end) { // FIXME dangerously hacky
  7486. var measure = view[view.length - 1].measure
  7487. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  7488. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}
  7489. }
  7490. var rng
  7491. try { rng = range(start.node, start.offset, end.offset, end.node) }
  7492. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7493. if (rng) {
  7494. if (!gecko && this.cm.state.focused) {
  7495. sel.collapse(start.node, start.offset)
  7496. if (!rng.collapsed) {
  7497. sel.removeAllRanges()
  7498. sel.addRange(rng)
  7499. }
  7500. } else {
  7501. sel.removeAllRanges()
  7502. sel.addRange(rng)
  7503. }
  7504. if (old && sel.anchorNode == null) { sel.addRange(old) }
  7505. else if (gecko) { this.startGracePeriod() }
  7506. }
  7507. this.rememberSelection()
  7508. };
  7509. ContentEditableInput.prototype.startGracePeriod = function () {
  7510. var this$1 = this;
  7511. clearTimeout(this.gracePeriod)
  7512. this.gracePeriod = setTimeout(function () {
  7513. this$1.gracePeriod = false
  7514. if (this$1.selectionChanged())
  7515. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
  7516. }, 20)
  7517. };
  7518. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7519. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  7520. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  7521. };
  7522. ContentEditableInput.prototype.rememberSelection = function () {
  7523. var sel = window.getSelection()
  7524. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  7525. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  7526. };
  7527. ContentEditableInput.prototype.selectionInEditor = function () {
  7528. var sel = window.getSelection()
  7529. if (!sel.rangeCount) { return false }
  7530. var node = sel.getRangeAt(0).commonAncestorContainer
  7531. return contains(this.div, node)
  7532. };
  7533. ContentEditableInput.prototype.focus = function () {
  7534. if (this.cm.options.readOnly != "nocursor") {
  7535. if (!this.selectionInEditor())
  7536. { this.showSelection(this.prepareSelection(), true) }
  7537. this.div.focus()
  7538. }
  7539. };
  7540. ContentEditableInput.prototype.blur = function () { this.div.blur() };
  7541. ContentEditableInput.prototype.getField = function () { return this.div };
  7542. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7543. ContentEditableInput.prototype.receivedFocus = function () {
  7544. var input = this
  7545. if (this.selectionInEditor())
  7546. { this.pollSelection() }
  7547. else
  7548. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
  7549. function poll() {
  7550. if (input.cm.state.focused) {
  7551. input.pollSelection()
  7552. input.polling.set(input.cm.options.pollInterval, poll)
  7553. }
  7554. }
  7555. this.polling.set(this.cm.options.pollInterval, poll)
  7556. };
  7557. ContentEditableInput.prototype.selectionChanged = function () {
  7558. var sel = window.getSelection()
  7559. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7560. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  7561. };
  7562. ContentEditableInput.prototype.pollSelection = function () {
  7563. if (!this.composing && this.readDOMTimeout == null && !this.gracePeriod && this.selectionChanged()) {
  7564. var sel = window.getSelection(), cm = this.cm
  7565. this.rememberSelection()
  7566. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7567. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  7568. if (anchor && head) { runInOp(cm, function () {
  7569. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  7570. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
  7571. }) }
  7572. }
  7573. };
  7574. ContentEditableInput.prototype.pollContent = function () {
  7575. if (this.readDOMTimeout != null) {
  7576. clearTimeout(this.readDOMTimeout)
  7577. this.readDOMTimeout = null
  7578. }
  7579. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  7580. var from = sel.from(), to = sel.to()
  7581. if (from.ch == 0 && from.line > cm.firstLine())
  7582. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
  7583. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  7584. { to = Pos(to.line + 1, 0) }
  7585. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  7586. var fromIndex, fromLine, fromNode
  7587. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  7588. fromLine = lineNo(display.view[0].line)
  7589. fromNode = display.view[0].node
  7590. } else {
  7591. fromLine = lineNo(display.view[fromIndex].line)
  7592. fromNode = display.view[fromIndex - 1].node.nextSibling
  7593. }
  7594. var toIndex = findViewIndex(cm, to.line)
  7595. var toLine, toNode
  7596. if (toIndex == display.view.length - 1) {
  7597. toLine = display.viewTo - 1
  7598. toNode = display.lineDiv.lastChild
  7599. } else {
  7600. toLine = lineNo(display.view[toIndex + 1].line) - 1
  7601. toNode = display.view[toIndex + 1].node.previousSibling
  7602. }
  7603. if (!fromNode) { return false }
  7604. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  7605. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  7606. while (newText.length > 1 && oldText.length > 1) {
  7607. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  7608. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  7609. else { break }
  7610. }
  7611. var cutFront = 0, cutEnd = 0
  7612. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  7613. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  7614. { ++cutFront }
  7615. var newBot = lst(newText), oldBot = lst(oldText)
  7616. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  7617. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  7618. while (cutEnd < maxCutEnd &&
  7619. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  7620. { ++cutEnd }
  7621. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  7622. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  7623. var chFrom = Pos(fromLine, cutFront)
  7624. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  7625. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  7626. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  7627. return true
  7628. }
  7629. };
  7630. ContentEditableInput.prototype.ensurePolled = function () {
  7631. this.forceCompositionEnd()
  7632. };
  7633. ContentEditableInput.prototype.reset = function () {
  7634. this.forceCompositionEnd()
  7635. };
  7636. ContentEditableInput.prototype.forceCompositionEnd = function () {
  7637. if (!this.composing) { return }
  7638. clearTimeout(this.readDOMTimeout)
  7639. this.composing = null
  7640. if (!this.pollContent()) { regChange(this.cm) }
  7641. this.div.blur()
  7642. this.div.focus()
  7643. };
  7644. ContentEditableInput.prototype.readFromDOMSoon = function () {
  7645. var this$1 = this;
  7646. if (this.readDOMTimeout != null) { return }
  7647. this.readDOMTimeout = setTimeout(function () {
  7648. this$1.readDOMTimeout = null
  7649. if (this$1.composing) {
  7650. if (this$1.composing.done) { this$1.composing = null }
  7651. else { return }
  7652. }
  7653. if (this$1.cm.isReadOnly() || !this$1.pollContent())
  7654. { runInOp(this$1.cm, function () { return regChange(this$1.cm); }) }
  7655. }, 80)
  7656. };
  7657. ContentEditableInput.prototype.setUneditable = function (node) {
  7658. node.contentEditable = "false"
  7659. };
  7660. ContentEditableInput.prototype.onKeyPress = function (e) {
  7661. e.preventDefault()
  7662. if (!this.cm.isReadOnly())
  7663. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) }
  7664. };
  7665. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  7666. this.div.contentEditable = String(val != "nocursor")
  7667. };
  7668. ContentEditableInput.prototype.onContextMenu = function () {};
  7669. ContentEditableInput.prototype.resetPosition = function () {};
  7670. ContentEditableInput.prototype.needsContentAttribute = true
  7671. function posToDOM(cm, pos) {
  7672. var view = findViewForLine(cm, pos.line)
  7673. if (!view || view.hidden) { return null }
  7674. var line = getLine(cm.doc, pos.line)
  7675. var info = mapFromLineView(view, line, pos.line)
  7676. var order = getOrder(line), side = "left"
  7677. if (order) {
  7678. var partPos = getBidiPartAt(order, pos.ch)
  7679. side = partPos % 2 ? "right" : "left"
  7680. }
  7681. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  7682. result.offset = result.collapse == "right" ? result.end : result.start
  7683. return result
  7684. }
  7685. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  7686. function domTextBetween(cm, from, to, fromLine, toLine) {
  7687. var text = "", closing = false, lineSep = cm.doc.lineSeparator()
  7688. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  7689. function walk(node) {
  7690. if (node.nodeType == 1) {
  7691. var cmText = node.getAttribute("cm-text")
  7692. if (cmText != null) {
  7693. if (cmText == "") { text += node.textContent.replace(/\u200b/g, "") }
  7694. else { text += cmText }
  7695. return
  7696. }
  7697. var markerID = node.getAttribute("cm-marker"), range
  7698. if (markerID) {
  7699. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  7700. if (found.length && (range = found[0].find()))
  7701. { text += getBetween(cm.doc, range.from, range.to).join(lineSep) }
  7702. return
  7703. }
  7704. if (node.getAttribute("contenteditable") == "false") { return }
  7705. for (var i = 0; i < node.childNodes.length; i++)
  7706. { walk(node.childNodes[i]) }
  7707. if (/^(pre|div|p)$/i.test(node.nodeName))
  7708. { closing = true }
  7709. } else if (node.nodeType == 3) {
  7710. var val = node.nodeValue
  7711. if (!val) { return }
  7712. if (closing) {
  7713. text += lineSep
  7714. closing = false
  7715. }
  7716. text += val
  7717. }
  7718. }
  7719. for (;;) {
  7720. walk(from)
  7721. if (from == to) { break }
  7722. from = from.nextSibling
  7723. }
  7724. return text
  7725. }
  7726. function domToPos(cm, node, offset) {
  7727. var lineNode
  7728. if (node == cm.display.lineDiv) {
  7729. lineNode = cm.display.lineDiv.childNodes[offset]
  7730. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  7731. node = null; offset = 0
  7732. } else {
  7733. for (lineNode = node;; lineNode = lineNode.parentNode) {
  7734. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  7735. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  7736. }
  7737. }
  7738. for (var i = 0; i < cm.display.view.length; i++) {
  7739. var lineView = cm.display.view[i]
  7740. if (lineView.node == lineNode)
  7741. { return locateNodeInLineView(lineView, node, offset) }
  7742. }
  7743. }
  7744. function locateNodeInLineView(lineView, node, offset) {
  7745. var wrapper = lineView.text.firstChild, bad = false
  7746. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  7747. if (node == wrapper) {
  7748. bad = true
  7749. node = wrapper.childNodes[offset]
  7750. offset = 0
  7751. if (!node) {
  7752. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  7753. return badPos(Pos(lineNo(line), line.text.length), bad)
  7754. }
  7755. }
  7756. var textNode = node.nodeType == 3 ? node : null, topNode = node
  7757. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  7758. textNode = node.firstChild
  7759. if (offset) { offset = textNode.nodeValue.length }
  7760. }
  7761. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
  7762. var measure = lineView.measure, maps = measure.maps
  7763. function find(textNode, topNode, offset) {
  7764. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  7765. var map = i < 0 ? measure.map : maps[i]
  7766. for (var j = 0; j < map.length; j += 3) {
  7767. var curNode = map[j + 2]
  7768. if (curNode == textNode || curNode == topNode) {
  7769. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  7770. var ch = map[j] + offset
  7771. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] }
  7772. return Pos(line, ch)
  7773. }
  7774. }
  7775. }
  7776. }
  7777. var found = find(textNode, topNode, offset)
  7778. if (found) { return badPos(found, bad) }
  7779. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  7780. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  7781. found = find(after, after.firstChild, 0)
  7782. if (found)
  7783. { return badPos(Pos(found.line, found.ch - dist), bad) }
  7784. else
  7785. { dist += after.textContent.length }
  7786. }
  7787. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  7788. found = find(before, before.firstChild, -1)
  7789. if (found)
  7790. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  7791. else
  7792. { dist$1 += before.textContent.length }
  7793. }
  7794. }
  7795. // TEXTAREA INPUT STYLE
  7796. var TextareaInput = function(cm) {
  7797. this.cm = cm
  7798. // See input.poll and input.reset
  7799. this.prevInput = ""
  7800. // Flag that indicates whether we expect input to appear real soon
  7801. // now (after some event like 'keypress' or 'input') and are
  7802. // polling intensively.
  7803. this.pollingFast = false
  7804. // Self-resetting timeout for the poller
  7805. this.polling = new Delayed()
  7806. // Tracks when input.reset has punted to just putting a short
  7807. // string into the textarea instead of the full selection.
  7808. this.inaccurateSelection = false
  7809. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  7810. this.hasSelection = false
  7811. this.composing = null
  7812. };
  7813. TextareaInput.prototype.init = function (display) {
  7814. var this$1 = this;
  7815. var input = this, cm = this.cm
  7816. // Wraps and hides input textarea
  7817. var div = this.wrapper = hiddenTextarea()
  7818. // The semihidden textarea that is focused when the editor is
  7819. // focused, and receives input.
  7820. var te = this.textarea = div.firstChild
  7821. display.wrapper.insertBefore(div, display.wrapper.firstChild)
  7822. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  7823. if (ios) { te.style.width = "0px" }
  7824. on(te, "input", function () {
  7825. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
  7826. input.poll()
  7827. })
  7828. on(te, "paste", function (e) {
  7829. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7830. cm.state.pasteIncoming = true
  7831. input.fastPoll()
  7832. })
  7833. function prepareCopyCut(e) {
  7834. if (signalDOMEvent(cm, e)) { return }
  7835. if (cm.somethingSelected()) {
  7836. setLastCopied({lineWise: false, text: cm.getSelections()})
  7837. if (input.inaccurateSelection) {
  7838. input.prevInput = ""
  7839. input.inaccurateSelection = false
  7840. te.value = lastCopied.text.join("\n")
  7841. selectInput(te)
  7842. }
  7843. } else if (!cm.options.lineWiseCopyCut) {
  7844. return
  7845. } else {
  7846. var ranges = copyableRanges(cm)
  7847. setLastCopied({lineWise: true, text: ranges.text})
  7848. if (e.type == "cut") {
  7849. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  7850. } else {
  7851. input.prevInput = ""
  7852. te.value = ranges.text.join("\n")
  7853. selectInput(te)
  7854. }
  7855. }
  7856. if (e.type == "cut") { cm.state.cutIncoming = true }
  7857. }
  7858. on(te, "cut", prepareCopyCut)
  7859. on(te, "copy", prepareCopyCut)
  7860. on(display.scroller, "paste", function (e) {
  7861. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  7862. cm.state.pasteIncoming = true
  7863. input.focus()
  7864. })
  7865. // Prevent normal selection in the editor (we handle our own)
  7866. on(display.lineSpace, "selectstart", function (e) {
  7867. if (!eventInWidget(display, e)) { e_preventDefault(e) }
  7868. })
  7869. on(te, "compositionstart", function () {
  7870. var start = cm.getCursor("from")
  7871. if (input.composing) { input.composing.range.clear() }
  7872. input.composing = {
  7873. start: start,
  7874. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  7875. }
  7876. })
  7877. on(te, "compositionend", function () {
  7878. if (input.composing) {
  7879. input.poll()
  7880. input.composing.range.clear()
  7881. input.composing = null
  7882. }
  7883. })
  7884. };
  7885. TextareaInput.prototype.prepareSelection = function () {
  7886. // Redraw the selection and/or cursor
  7887. var cm = this.cm, display = cm.display, doc = cm.doc
  7888. var result = prepareSelection(cm)
  7889. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  7890. if (cm.options.moveInputWithCursor) {
  7891. var headPos = cursorCoords(cm, doc.sel.primary().head, "div")
  7892. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()
  7893. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  7894. headPos.top + lineOff.top - wrapOff.top))
  7895. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  7896. headPos.left + lineOff.left - wrapOff.left))
  7897. }
  7898. return result
  7899. };
  7900. TextareaInput.prototype.showSelection = function (drawn) {
  7901. var cm = this.cm, display = cm.display
  7902. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  7903. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  7904. if (drawn.teTop != null) {
  7905. this.wrapper.style.top = drawn.teTop + "px"
  7906. this.wrapper.style.left = drawn.teLeft + "px"
  7907. }
  7908. };
  7909. // Reset the input to correspond to the selection (or to be empty,
  7910. // when not typing and nothing is selected)
  7911. TextareaInput.prototype.reset = function (typing) {
  7912. if (this.contextMenuPending) { return }
  7913. var minimal, selected, cm = this.cm, doc = cm.doc
  7914. if (cm.somethingSelected()) {
  7915. this.prevInput = ""
  7916. var range = doc.sel.primary()
  7917. minimal = hasCopyEvent &&
  7918. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000)
  7919. var content = minimal ? "-" : selected || cm.getSelection()
  7920. this.textarea.value = content
  7921. if (cm.state.focused) { selectInput(this.textarea) }
  7922. if (ie && ie_version >= 9) { this.hasSelection = content }
  7923. } else if (!typing) {
  7924. this.prevInput = this.textarea.value = ""
  7925. if (ie && ie_version >= 9) { this.hasSelection = null }
  7926. }
  7927. this.inaccurateSelection = minimal
  7928. };
  7929. TextareaInput.prototype.getField = function () { return this.textarea };
  7930. TextareaInput.prototype.supportsTouch = function () { return false };
  7931. TextareaInput.prototype.focus = function () {
  7932. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  7933. try { this.textarea.focus() }
  7934. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  7935. }
  7936. };
  7937. TextareaInput.prototype.blur = function () { this.textarea.blur() };
  7938. TextareaInput.prototype.resetPosition = function () {
  7939. this.wrapper.style.top = this.wrapper.style.left = 0
  7940. };
  7941. TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
  7942. // Poll for input changes, using the normal rate of polling. This
  7943. // runs as long as the editor is focused.
  7944. TextareaInput.prototype.slowPoll = function () {
  7945. var this$1 = this;
  7946. if (this.pollingFast) { return }
  7947. this.polling.set(this.cm.options.pollInterval, function () {
  7948. this$1.poll()
  7949. if (this$1.cm.state.focused) { this$1.slowPoll() }
  7950. })
  7951. };
  7952. // When an event has just come in that is likely to add or change
  7953. // something in the input textarea, we poll faster, to ensure that
  7954. // the change appears on the screen quickly.
  7955. TextareaInput.prototype.fastPoll = function () {
  7956. var missed = false, input = this
  7957. input.pollingFast = true
  7958. function p() {
  7959. var changed = input.poll()
  7960. if (!changed && !missed) {missed = true; input.polling.set(60, p)}
  7961. else {input.pollingFast = false; input.slowPoll()}
  7962. }
  7963. input.polling.set(20, p)
  7964. };
  7965. // Read input from the textarea, and update the document to match.
  7966. // When something is selected, it is present in the textarea, and
  7967. // selected (unless it is huge, in which case a placeholder is
  7968. // used). When nothing is selected, the cursor sits after previously
  7969. // seen text (can be empty), which is stored in prevInput (we must
  7970. // not reset the textarea when typing, because that breaks IME).
  7971. TextareaInput.prototype.poll = function () {
  7972. var this$1 = this;
  7973. var cm = this.cm, input = this.textarea, prevInput = this.prevInput
  7974. // Since this is called a *lot*, try to bail out as cheaply as
  7975. // possible when it is clear that nothing happened. hasSelection
  7976. // will be the case when there is a lot of text in the textarea,
  7977. // in which case reading its value would be expensive.
  7978. if (this.contextMenuPending || !cm.state.focused ||
  7979. (hasSelection(input) && !prevInput && !this.composing) ||
  7980. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  7981. { return false }
  7982. var text = input.value
  7983. // If nothing changed, bail.
  7984. if (text == prevInput && !cm.somethingSelected()) { return false }
  7985. // Work around nonsensical selection resetting in IE9/10, and
  7986. // inexplicable appearance of private area unicode characters on
  7987. // some key combos in Mac (#2689).
  7988. if (ie && ie_version >= 9 && this.hasSelection === text ||
  7989. mac && /[\uf700-\uf7ff]/.test(text)) {
  7990. cm.display.input.reset()
  7991. return false
  7992. }
  7993. if (cm.doc.sel == cm.display.selForContextMenu) {
  7994. var first = text.charCodeAt(0)
  7995. if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
  7996. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  7997. }
  7998. // Find the part of the input that is actually new
  7999. var same = 0, l = Math.min(prevInput.length, text.length)
  8000. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
  8001. runInOp(cm, function () {
  8002. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8003. null, this$1.composing ? "*compose" : null)
  8004. // Don't leave long text in the textarea, since it makes further polling slow
  8005. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
  8006. else { this$1.prevInput = text }
  8007. if (this$1.composing) {
  8008. this$1.composing.range.clear()
  8009. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8010. {className: "CodeMirror-composing"})
  8011. }
  8012. })
  8013. return true
  8014. };
  8015. TextareaInput.prototype.ensurePolled = function () {
  8016. if (this.pollingFast && this.poll()) { this.pollingFast = false }
  8017. };
  8018. TextareaInput.prototype.onKeyPress = function () {
  8019. if (ie && ie_version >= 9) { this.hasSelection = null }
  8020. this.fastPoll()
  8021. };
  8022. TextareaInput.prototype.onContextMenu = function (e) {
  8023. var input = this, cm = input.cm, display = cm.display, te = input.textarea
  8024. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
  8025. if (!pos || presto) { return } // Opera is difficult.
  8026. // Reset the current text selection only if the click is done outside of the selection
  8027. // and 'resetSelectionOnContextMenu' option is true.
  8028. var reset = cm.options.resetSelectionOnContextMenu
  8029. if (reset && cm.doc.sel.contains(pos) == -1)
  8030. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
  8031. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
  8032. input.wrapper.style.cssText = "position: absolute"
  8033. var wrapperBox = input.wrapper.getBoundingClientRect()
  8034. te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"
  8035. var oldScrollY
  8036. if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
  8037. display.input.focus()
  8038. if (webkit) { window.scrollTo(null, oldScrollY) }
  8039. display.input.reset()
  8040. // Adds "Select all" to context menu in FF
  8041. if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
  8042. input.contextMenuPending = true
  8043. display.selForContextMenu = cm.doc.sel
  8044. clearTimeout(display.detectingSelectAll)
  8045. // Select-all will be greyed out if there's nothing to select, so
  8046. // this adds a zero-width space so that we can later check whether
  8047. // it got selected.
  8048. function prepareSelectAllHack() {
  8049. if (te.selectionStart != null) {
  8050. var selected = cm.somethingSelected()
  8051. var extval = "\u200b" + (selected ? te.value : "")
  8052. te.value = "\u21da" // Used to catch context-menu undo
  8053. te.value = extval
  8054. input.prevInput = selected ? "" : "\u200b"
  8055. te.selectionStart = 1; te.selectionEnd = extval.length
  8056. // Re-set this, in case some other handler touched the
  8057. // selection in the meantime.
  8058. display.selForContextMenu = cm.doc.sel
  8059. }
  8060. }
  8061. function rehide() {
  8062. input.contextMenuPending = false
  8063. input.wrapper.style.cssText = oldWrapperCSS
  8064. te.style.cssText = oldCSS
  8065. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
  8066. // Try to detect the user choosing select-all
  8067. if (te.selectionStart != null) {
  8068. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
  8069. var i = 0, poll = function () {
  8070. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8071. te.selectionEnd > 0 && input.prevInput == "\u200b")
  8072. { operation(cm, selectAll)(cm) }
  8073. else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500) }
  8074. else { display.input.reset() }
  8075. }
  8076. display.detectingSelectAll = setTimeout(poll, 200)
  8077. }
  8078. }
  8079. if (ie && ie_version >= 9) { prepareSelectAllHack() }
  8080. if (captureRightClick) {
  8081. e_stop(e)
  8082. var mouseup = function () {
  8083. off(window, "mouseup", mouseup)
  8084. setTimeout(rehide, 20)
  8085. }
  8086. on(window, "mouseup", mouseup)
  8087. } else {
  8088. setTimeout(rehide, 50)
  8089. }
  8090. };
  8091. TextareaInput.prototype.readOnlyChanged = function (val) {
  8092. if (!val) { this.reset() }
  8093. };
  8094. TextareaInput.prototype.setUneditable = function () {};
  8095. TextareaInput.prototype.needsContentAttribute = false
  8096. function fromTextArea(textarea, options) {
  8097. options = options ? copyObj(options) : {}
  8098. options.value = textarea.value
  8099. if (!options.tabindex && textarea.tabIndex)
  8100. { options.tabindex = textarea.tabIndex }
  8101. if (!options.placeholder && textarea.placeholder)
  8102. { options.placeholder = textarea.placeholder }
  8103. // Set autofocus to true if this textarea is focused, or if it has
  8104. // autofocus and no other element is focused.
  8105. if (options.autofocus == null) {
  8106. var hasFocus = activeElt()
  8107. options.autofocus = hasFocus == textarea ||
  8108. textarea.getAttribute("autofocus") != null && hasFocus == document.body
  8109. }
  8110. function save() {textarea.value = cm.getValue()}
  8111. var realSubmit
  8112. if (textarea.form) {
  8113. on(textarea.form, "submit", save)
  8114. // Deplorable hack to make the submit method do the right thing.
  8115. if (!options.leaveSubmitMethodAlone) {
  8116. var form = textarea.form
  8117. realSubmit = form.submit
  8118. try {
  8119. var wrappedSubmit = form.submit = function () {
  8120. save()
  8121. form.submit = realSubmit
  8122. form.submit()
  8123. form.submit = wrappedSubmit
  8124. }
  8125. } catch(e) {}
  8126. }
  8127. }
  8128. options.finishInit = function (cm) {
  8129. cm.save = save
  8130. cm.getTextArea = function () { return textarea; }
  8131. cm.toTextArea = function () {
  8132. cm.toTextArea = isNaN // Prevent this from being ran twice
  8133. save()
  8134. textarea.parentNode.removeChild(cm.getWrapperElement())
  8135. textarea.style.display = ""
  8136. if (textarea.form) {
  8137. off(textarea.form, "submit", save)
  8138. if (typeof textarea.form.submit == "function")
  8139. { textarea.form.submit = realSubmit }
  8140. }
  8141. }
  8142. }
  8143. textarea.style.display = "none"
  8144. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8145. options)
  8146. return cm
  8147. }
  8148. function addLegacyProps(CodeMirror) {
  8149. CodeMirror.off = off
  8150. CodeMirror.on = on
  8151. CodeMirror.wheelEventPixels = wheelEventPixels
  8152. CodeMirror.Doc = Doc
  8153. CodeMirror.splitLines = splitLinesAuto
  8154. CodeMirror.countColumn = countColumn
  8155. CodeMirror.findColumn = findColumn
  8156. CodeMirror.isWordChar = isWordCharBasic
  8157. CodeMirror.Pass = Pass
  8158. CodeMirror.signal = signal
  8159. CodeMirror.Line = Line
  8160. CodeMirror.changeEnd = changeEnd
  8161. CodeMirror.scrollbarModel = scrollbarModel
  8162. CodeMirror.Pos = Pos
  8163. CodeMirror.cmpPos = cmp
  8164. CodeMirror.modes = modes
  8165. CodeMirror.mimeModes = mimeModes
  8166. CodeMirror.resolveMode = resolveMode
  8167. CodeMirror.getMode = getMode
  8168. CodeMirror.modeExtensions = modeExtensions
  8169. CodeMirror.extendMode = extendMode
  8170. CodeMirror.copyState = copyState
  8171. CodeMirror.startState = startState
  8172. CodeMirror.innerMode = innerMode
  8173. CodeMirror.commands = commands
  8174. CodeMirror.keyMap = keyMap
  8175. CodeMirror.keyName = keyName
  8176. CodeMirror.isModifierKey = isModifierKey
  8177. CodeMirror.lookupKey = lookupKey
  8178. CodeMirror.normalizeKeyMap = normalizeKeyMap
  8179. CodeMirror.StringStream = StringStream
  8180. CodeMirror.SharedTextMarker = SharedTextMarker
  8181. CodeMirror.TextMarker = TextMarker
  8182. CodeMirror.LineWidget = LineWidget
  8183. CodeMirror.e_preventDefault = e_preventDefault
  8184. CodeMirror.e_stopPropagation = e_stopPropagation
  8185. CodeMirror.e_stop = e_stop
  8186. CodeMirror.addClass = addClass
  8187. CodeMirror.contains = contains
  8188. CodeMirror.rmClass = rmClass
  8189. CodeMirror.keyNames = keyNames
  8190. }
  8191. // EDITOR CONSTRUCTOR
  8192. defineOptions(CodeMirror)
  8193. addEditorMethods(CodeMirror)
  8194. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8195. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ")
  8196. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8197. { CodeMirror.prototype[prop] = (function(method) {
  8198. return function() {return method.apply(this.doc, arguments)}
  8199. })(Doc.prototype[prop]) } }
  8200. eventMixin(Doc)
  8201. // INPUT HANDLING
  8202. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
  8203. // MODE DEFINITION AND QUERYING
  8204. // Extra arguments are stored as the mode's dependencies, which is
  8205. // used by (legacy) mechanisms like loadmode.js to automatically
  8206. // load a mode. (Preferred mechanism is the require/define calls.)
  8207. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8208. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name }
  8209. defineMode.apply(this, arguments)
  8210. }
  8211. CodeMirror.defineMIME = defineMIME
  8212. // Minimal default mode.
  8213. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
  8214. CodeMirror.defineMIME("text/plain", "null")
  8215. // EXTENSIONS
  8216. CodeMirror.defineExtension = function (name, func) {
  8217. CodeMirror.prototype[name] = func
  8218. }
  8219. CodeMirror.defineDocExtension = function (name, func) {
  8220. Doc.prototype[name] = func
  8221. }
  8222. CodeMirror.fromTextArea = fromTextArea
  8223. addLegacyProps(CodeMirror)
  8224. CodeMirror.version = "5.23.0"
  8225. return CodeMirror;
  8226. })));