codemirror.js 386 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // This is CodeMirror (https://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 edge = /Edge\/(\d+)/.exec(userAgent);
  21. var ie = ie_upto10 || ie_11up || edge;
  22. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  23. var webkit = !edge && /WebKit\//.test(userAgent);
  24. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  25. var chrome = !edge && /Chrome\//.test(userAgent);
  26. var presto = /Opera\//.test(userAgent);
  27. var safari = /Apple Computer/.test(navigator.vendor);
  28. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  29. var phantom = /PhantomJS/.test(userAgent);
  30. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  31. var android = /Android/.test(userAgent);
  32. // This is woefully incomplete. Suggestions for alternative methods welcome.
  33. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  34. var mac = ios || /Mac/.test(platform);
  35. var chromeOS = /\bCrOS\b/.test(userAgent);
  36. var windows = /win/i.test(platform);
  37. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  38. if (presto_version) { presto_version = Number(presto_version[1]); }
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  42. var captureRightClick = gecko || (ie && ie_version >= 9);
  43. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  44. var rmClass = function(node, cls) {
  45. var current = node.className;
  46. var match = classTest(cls).exec(current);
  47. if (match) {
  48. var after = current.slice(match.index + match[0].length);
  49. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  50. }
  51. };
  52. function removeChildren(e) {
  53. for (var count = e.childNodes.length; count > 0; --count)
  54. { e.removeChild(e.firstChild); }
  55. return e
  56. }
  57. function removeChildrenAndAdd(parent, e) {
  58. return removeChildren(parent).appendChild(e)
  59. }
  60. function elt(tag, content, className, style) {
  61. var e = document.createElement(tag);
  62. if (className) { e.className = className; }
  63. if (style) { e.style.cssText = style; }
  64. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  65. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  66. return e
  67. }
  68. // wrapper for elt, which removes the elt from the accessibility tree
  69. function eltP(tag, content, className, style) {
  70. var e = elt(tag, content, className, style);
  71. e.setAttribute("role", "presentation");
  72. return e
  73. }
  74. var range;
  75. if (document.createRange) { range = function(node, start, end, endNode) {
  76. var r = document.createRange();
  77. r.setEnd(endNode || node, end);
  78. r.setStart(node, start);
  79. return r
  80. }; }
  81. else { range = function(node, start, end) {
  82. var r = document.body.createTextRange();
  83. try { r.moveToElementText(node.parentNode); }
  84. catch(e) { return r }
  85. r.collapse(true);
  86. r.moveEnd("character", end);
  87. r.moveStart("character", start);
  88. return r
  89. }; }
  90. function contains(parent, child) {
  91. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  92. { child = child.parentNode; }
  93. if (parent.contains)
  94. { return parent.contains(child) }
  95. do {
  96. if (child.nodeType == 11) { child = child.host; }
  97. if (child == parent) { return true }
  98. } while (child = child.parentNode)
  99. }
  100. function activeElt() {
  101. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  102. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  103. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  104. var activeElement;
  105. try {
  106. activeElement = document.activeElement;
  107. } catch(e) {
  108. activeElement = document.body || null;
  109. }
  110. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  111. { activeElement = activeElement.shadowRoot.activeElement; }
  112. return activeElement
  113. }
  114. function addClass(node, cls) {
  115. var current = node.className;
  116. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  117. }
  118. function joinClasses(a, b) {
  119. var as = a.split(" ");
  120. for (var i = 0; i < as.length; i++)
  121. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  122. return b
  123. }
  124. var selectInput = function(node) { node.select(); };
  125. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  126. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  127. else if (ie) // Suppress mysterious IE10 errors
  128. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  129. function bind(f) {
  130. var args = Array.prototype.slice.call(arguments, 1);
  131. return function(){return f.apply(null, args)}
  132. }
  133. function copyObj(obj, target, overwrite) {
  134. if (!target) { target = {}; }
  135. for (var prop in obj)
  136. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  137. { target[prop] = obj[prop]; } }
  138. return target
  139. }
  140. // Counts the column offset in a string, taking tabs into account.
  141. // Used mostly to find indentation.
  142. function countColumn(string, end, tabSize, startIndex, startValue) {
  143. if (end == null) {
  144. end = string.search(/[^\s\u00a0]/);
  145. if (end == -1) { end = string.length; }
  146. }
  147. for (var i = startIndex || 0, n = startValue || 0;;) {
  148. var nextTab = string.indexOf("\t", i);
  149. if (nextTab < 0 || nextTab >= end)
  150. { return n + (end - i) }
  151. n += nextTab - i;
  152. n += tabSize - (n % tabSize);
  153. i = nextTab + 1;
  154. }
  155. }
  156. var Delayed = function() {this.id = null;};
  157. Delayed.prototype.set = function (ms, f) {
  158. clearTimeout(this.id);
  159. this.id = setTimeout(f, ms);
  160. };
  161. function indexOf(array, elt) {
  162. for (var i = 0; i < array.length; ++i)
  163. { if (array[i] == elt) { return i } }
  164. return -1
  165. }
  166. // Number of pixels added to scroller and sizer to hide scrollbar
  167. var scrollerGap = 30;
  168. // Returned or thrown by various protocols to signal 'I'm not
  169. // handling this'.
  170. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  171. // Reused option objects for setSelection & friends
  172. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  173. // The inverse of countColumn -- find the offset that corresponds to
  174. // a particular column.
  175. function findColumn(string, goal, tabSize) {
  176. for (var pos = 0, col = 0;;) {
  177. var nextTab = string.indexOf("\t", pos);
  178. if (nextTab == -1) { nextTab = string.length; }
  179. var skipped = nextTab - pos;
  180. if (nextTab == string.length || col + skipped >= goal)
  181. { return pos + Math.min(skipped, goal - col) }
  182. col += nextTab - pos;
  183. col += tabSize - (col % tabSize);
  184. pos = nextTab + 1;
  185. if (col >= goal) { return pos }
  186. }
  187. }
  188. var spaceStrs = [""];
  189. function spaceStr(n) {
  190. while (spaceStrs.length <= n)
  191. { spaceStrs.push(lst(spaceStrs) + " "); }
  192. return spaceStrs[n]
  193. }
  194. function lst(arr) { return arr[arr.length-1] }
  195. function map(array, f) {
  196. var out = [];
  197. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  198. return out
  199. }
  200. function insertSorted(array, value, score) {
  201. var pos = 0, priority = score(value);
  202. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  203. array.splice(pos, 0, value);
  204. }
  205. function nothing() {}
  206. function createObj(base, props) {
  207. var inst;
  208. if (Object.create) {
  209. inst = Object.create(base);
  210. } else {
  211. nothing.prototype = base;
  212. inst = new nothing();
  213. }
  214. if (props) { copyObj(props, inst); }
  215. return inst
  216. }
  217. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  218. function isWordCharBasic(ch) {
  219. return /\w/.test(ch) || ch > "\x80" &&
  220. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  221. }
  222. function isWordChar(ch, helper) {
  223. if (!helper) { return isWordCharBasic(ch) }
  224. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  225. return helper.test(ch)
  226. }
  227. function isEmpty(obj) {
  228. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  229. return true
  230. }
  231. // Extending unicode characters. A series of a non-extending char +
  232. // any number of extending chars is treated as a single unit as far
  233. // as editing and measuring is concerned. This is not fully correct,
  234. // since some scripts/fonts/browsers also treat other configurations
  235. // of code points as a group.
  236. 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]/;
  237. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  238. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  239. function skipExtendingChars(str, pos, dir) {
  240. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  241. return pos
  242. }
  243. // Returns the value from the range [`from`; `to`] that satisfies
  244. // `pred` and is closest to `from`. Assumes that at least `to`
  245. // satisfies `pred`. Supports `from` being greater than `to`.
  246. function findFirst(pred, from, to) {
  247. // At any point we are certain `to` satisfies `pred`, don't know
  248. // whether `from` does.
  249. var dir = from > to ? -1 : 1;
  250. for (;;) {
  251. if (from == to) { return from }
  252. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  253. if (mid == from) { return pred(mid) ? from : to }
  254. if (pred(mid)) { to = mid; }
  255. else { from = mid + dir; }
  256. }
  257. }
  258. // BIDI HELPERS
  259. function iterateBidiSections(order, from, to, f) {
  260. if (!order) { return f(from, to, "ltr", 0) }
  261. var found = false;
  262. for (var i = 0; i < order.length; ++i) {
  263. var part = order[i];
  264. if (part.from < to && part.to > from || from == to && part.to == from) {
  265. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  266. found = true;
  267. }
  268. }
  269. if (!found) { f(from, to, "ltr"); }
  270. }
  271. var bidiOther = null;
  272. function getBidiPartAt(order, ch, sticky) {
  273. var found;
  274. bidiOther = null;
  275. for (var i = 0; i < order.length; ++i) {
  276. var cur = order[i];
  277. if (cur.from < ch && cur.to > ch) { return i }
  278. if (cur.to == ch) {
  279. if (cur.from != cur.to && sticky == "before") { found = i; }
  280. else { bidiOther = i; }
  281. }
  282. if (cur.from == ch) {
  283. if (cur.from != cur.to && sticky != "before") { found = i; }
  284. else { bidiOther = i; }
  285. }
  286. }
  287. return found != null ? found : bidiOther
  288. }
  289. // Bidirectional ordering algorithm
  290. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  291. // that this (partially) implements.
  292. // One-char codes used for character types:
  293. // L (L): Left-to-Right
  294. // R (R): Right-to-Left
  295. // r (AL): Right-to-Left Arabic
  296. // 1 (EN): European Number
  297. // + (ES): European Number Separator
  298. // % (ET): European Number Terminator
  299. // n (AN): Arabic Number
  300. // , (CS): Common Number Separator
  301. // m (NSM): Non-Spacing Mark
  302. // b (BN): Boundary Neutral
  303. // s (B): Paragraph Separator
  304. // t (S): Segment Separator
  305. // w (WS): Whitespace
  306. // N (ON): Other Neutrals
  307. // Returns null if characters are ordered as they appear
  308. // (left-to-right), or an array of sections ({from, to, level}
  309. // objects) in the order in which they occur visually.
  310. var bidiOrdering = (function() {
  311. // Character types for codepoints 0 to 0xff
  312. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  313. // Character types for codepoints 0x600 to 0x6f9
  314. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  315. function charType(code) {
  316. if (code <= 0xf7) { return lowTypes.charAt(code) }
  317. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  318. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  319. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  320. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  321. else if (code == 0x200c) { return "b" }
  322. else { return "L" }
  323. }
  324. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  325. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  326. function BidiSpan(level, from, to) {
  327. this.level = level;
  328. this.from = from; this.to = to;
  329. }
  330. return function(str, direction) {
  331. var outerType = direction == "ltr" ? "L" : "R";
  332. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  333. var len = str.length, types = [];
  334. for (var i = 0; i < len; ++i)
  335. { types.push(charType(str.charCodeAt(i))); }
  336. // W1. Examine each non-spacing mark (NSM) in the level run, and
  337. // change the type of the NSM to the type of the previous
  338. // character. If the NSM is at the start of the level run, it will
  339. // get the type of sor.
  340. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  341. var type = types[i$1];
  342. if (type == "m") { types[i$1] = prev; }
  343. else { prev = type; }
  344. }
  345. // W2. Search backwards from each instance of a European number
  346. // until the first strong type (R, L, AL, or sor) is found. If an
  347. // AL is found, change the type of the European number to Arabic
  348. // number.
  349. // W3. Change all ALs to R.
  350. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  351. var type$1 = types[i$2];
  352. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  353. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  354. }
  355. // W4. A single European separator between two European numbers
  356. // changes to a European number. A single common separator between
  357. // two numbers of the same type changes to that type.
  358. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  359. var type$2 = types[i$3];
  360. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  361. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  362. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  363. prev$1 = type$2;
  364. }
  365. // W5. A sequence of European terminators adjacent to European
  366. // numbers changes to all European numbers.
  367. // W6. Otherwise, separators and terminators change to Other
  368. // Neutral.
  369. for (var i$4 = 0; i$4 < len; ++i$4) {
  370. var type$3 = types[i$4];
  371. if (type$3 == ",") { types[i$4] = "N"; }
  372. else if (type$3 == "%") {
  373. var end = (void 0);
  374. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  375. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  376. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  377. i$4 = end - 1;
  378. }
  379. }
  380. // W7. Search backwards from each instance of a European number
  381. // until the first strong type (R, L, or sor) is found. If an L is
  382. // found, then change the type of the European number to L.
  383. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  384. var type$4 = types[i$5];
  385. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  386. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  387. }
  388. // N1. A sequence of neutrals takes the direction of the
  389. // surrounding strong text if the text on both sides has the same
  390. // direction. European and Arabic numbers act as if they were R in
  391. // terms of their influence on neutrals. Start-of-level-run (sor)
  392. // and end-of-level-run (eor) are used at level run boundaries.
  393. // N2. Any remaining neutrals take the embedding direction.
  394. for (var i$6 = 0; i$6 < len; ++i$6) {
  395. if (isNeutral.test(types[i$6])) {
  396. var end$1 = (void 0);
  397. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  398. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  399. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  400. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  401. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  402. i$6 = end$1 - 1;
  403. }
  404. }
  405. // Here we depart from the documented algorithm, in order to avoid
  406. // building up an actual levels array. Since there are only three
  407. // levels (0, 1, 2) in an implementation that doesn't take
  408. // explicit embedding into account, we can build up the order on
  409. // the fly, without following the level-based algorithm.
  410. var order = [], m;
  411. for (var i$7 = 0; i$7 < len;) {
  412. if (countsAsLeft.test(types[i$7])) {
  413. var start = i$7;
  414. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  415. order.push(new BidiSpan(0, start, i$7));
  416. } else {
  417. var pos = i$7, at = order.length;
  418. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  419. for (var j$2 = pos; j$2 < i$7;) {
  420. if (countsAsNum.test(types[j$2])) {
  421. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  422. var nstart = j$2;
  423. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  424. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  425. pos = j$2;
  426. } else { ++j$2; }
  427. }
  428. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  429. }
  430. }
  431. if (direction == "ltr") {
  432. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  433. order[0].from = m[0].length;
  434. order.unshift(new BidiSpan(0, 0, m[0].length));
  435. }
  436. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  437. lst(order).to -= m[0].length;
  438. order.push(new BidiSpan(0, len - m[0].length, len));
  439. }
  440. }
  441. return direction == "rtl" ? order.reverse() : order
  442. }
  443. })();
  444. // Get the bidi ordering for the given line (and cache it). Returns
  445. // false for lines that are fully left-to-right, and an array of
  446. // BidiSpan objects otherwise.
  447. function getOrder(line, direction) {
  448. var order = line.order;
  449. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  450. return order
  451. }
  452. // EVENT HANDLING
  453. // Lightweight event framework. on/off also work on DOM nodes,
  454. // registering native DOM handlers.
  455. var noHandlers = [];
  456. var on = function(emitter, type, f) {
  457. if (emitter.addEventListener) {
  458. emitter.addEventListener(type, f, false);
  459. } else if (emitter.attachEvent) {
  460. emitter.attachEvent("on" + type, f);
  461. } else {
  462. var map$$1 = emitter._handlers || (emitter._handlers = {});
  463. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  464. }
  465. };
  466. function getHandlers(emitter, type) {
  467. return emitter._handlers && emitter._handlers[type] || noHandlers
  468. }
  469. function off(emitter, type, f) {
  470. if (emitter.removeEventListener) {
  471. emitter.removeEventListener(type, f, false);
  472. } else if (emitter.detachEvent) {
  473. emitter.detachEvent("on" + type, f);
  474. } else {
  475. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  476. if (arr) {
  477. var index = indexOf(arr, f);
  478. if (index > -1)
  479. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  480. }
  481. }
  482. }
  483. function signal(emitter, type /*, values...*/) {
  484. var handlers = getHandlers(emitter, type);
  485. if (!handlers.length) { return }
  486. var args = Array.prototype.slice.call(arguments, 2);
  487. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  488. }
  489. // The DOM events that CodeMirror handles can be overridden by
  490. // registering a (non-DOM) handler on the editor for the event name,
  491. // and preventDefault-ing the event in that handler.
  492. function signalDOMEvent(cm, e, override) {
  493. if (typeof e == "string")
  494. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  495. signal(cm, override || e.type, cm, e);
  496. return e_defaultPrevented(e) || e.codemirrorIgnore
  497. }
  498. function signalCursorActivity(cm) {
  499. var arr = cm._handlers && cm._handlers.cursorActivity;
  500. if (!arr) { return }
  501. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  502. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  503. { set.push(arr[i]); } }
  504. }
  505. function hasHandler(emitter, type) {
  506. return getHandlers(emitter, type).length > 0
  507. }
  508. // Add on and off methods to a constructor's prototype, to make
  509. // registering events on such objects more convenient.
  510. function eventMixin(ctor) {
  511. ctor.prototype.on = function(type, f) {on(this, type, f);};
  512. ctor.prototype.off = function(type, f) {off(this, type, f);};
  513. }
  514. // Due to the fact that we still support jurassic IE versions, some
  515. // compatibility wrappers are needed.
  516. function e_preventDefault(e) {
  517. if (e.preventDefault) { e.preventDefault(); }
  518. else { e.returnValue = false; }
  519. }
  520. function e_stopPropagation(e) {
  521. if (e.stopPropagation) { e.stopPropagation(); }
  522. else { e.cancelBubble = true; }
  523. }
  524. function e_defaultPrevented(e) {
  525. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  526. }
  527. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  528. function e_target(e) {return e.target || e.srcElement}
  529. function e_button(e) {
  530. var b = e.which;
  531. if (b == null) {
  532. if (e.button & 1) { b = 1; }
  533. else if (e.button & 2) { b = 3; }
  534. else if (e.button & 4) { b = 2; }
  535. }
  536. if (mac && e.ctrlKey && b == 1) { b = 3; }
  537. return b
  538. }
  539. // Detect drag-and-drop
  540. var dragAndDrop = function() {
  541. // There is *some* kind of drag-and-drop support in IE6-8, but I
  542. // couldn't get it to work yet.
  543. if (ie && ie_version < 9) { return false }
  544. var div = elt('div');
  545. return "draggable" in div || "dragDrop" in div
  546. }();
  547. var zwspSupported;
  548. function zeroWidthElement(measure) {
  549. if (zwspSupported == null) {
  550. var test = elt("span", "\u200b");
  551. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  552. if (measure.firstChild.offsetHeight != 0)
  553. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  554. }
  555. var node = zwspSupported ? elt("span", "\u200b") :
  556. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  557. node.setAttribute("cm-text", "");
  558. return node
  559. }
  560. // Feature-detect IE's crummy client rect reporting for bidi text
  561. var badBidiRects;
  562. function hasBadBidiRects(measure) {
  563. if (badBidiRects != null) { return badBidiRects }
  564. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  565. var r0 = range(txt, 0, 1).getBoundingClientRect();
  566. var r1 = range(txt, 1, 2).getBoundingClientRect();
  567. removeChildren(measure);
  568. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  569. return badBidiRects = (r1.right - r0.right < 3)
  570. }
  571. // See if "".split is the broken IE version, if so, provide an
  572. // alternative way to split lines.
  573. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  574. var pos = 0, result = [], l = string.length;
  575. while (pos <= l) {
  576. var nl = string.indexOf("\n", pos);
  577. if (nl == -1) { nl = string.length; }
  578. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  579. var rt = line.indexOf("\r");
  580. if (rt != -1) {
  581. result.push(line.slice(0, rt));
  582. pos += rt + 1;
  583. } else {
  584. result.push(line);
  585. pos = nl + 1;
  586. }
  587. }
  588. return result
  589. } : function (string) { return string.split(/\r\n?|\n/); };
  590. var hasSelection = window.getSelection ? function (te) {
  591. try { return te.selectionStart != te.selectionEnd }
  592. catch(e) { return false }
  593. } : function (te) {
  594. var range$$1;
  595. try {range$$1 = te.ownerDocument.selection.createRange();}
  596. catch(e) {}
  597. if (!range$$1 || range$$1.parentElement() != te) { return false }
  598. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  599. };
  600. var hasCopyEvent = (function () {
  601. var e = elt("div");
  602. if ("oncopy" in e) { return true }
  603. e.setAttribute("oncopy", "return;");
  604. return typeof e.oncopy == "function"
  605. })();
  606. var badZoomedRects = null;
  607. function hasBadZoomedRects(measure) {
  608. if (badZoomedRects != null) { return badZoomedRects }
  609. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  610. var normal = node.getBoundingClientRect();
  611. var fromRange = range(node, 0, 1).getBoundingClientRect();
  612. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  613. }
  614. // Known modes, by name and by MIME
  615. var modes = {}, mimeModes = {};
  616. // Extra arguments are stored as the mode's dependencies, which is
  617. // used by (legacy) mechanisms like loadmode.js to automatically
  618. // load a mode. (Preferred mechanism is the require/define calls.)
  619. function defineMode(name, mode) {
  620. if (arguments.length > 2)
  621. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  622. modes[name] = mode;
  623. }
  624. function defineMIME(mime, spec) {
  625. mimeModes[mime] = spec;
  626. }
  627. // Given a MIME type, a {name, ...options} config object, or a name
  628. // string, return a mode config object.
  629. function resolveMode(spec) {
  630. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  631. spec = mimeModes[spec];
  632. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  633. var found = mimeModes[spec.name];
  634. if (typeof found == "string") { found = {name: found}; }
  635. spec = createObj(found, spec);
  636. spec.name = found.name;
  637. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  638. return resolveMode("application/xml")
  639. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  640. return resolveMode("application/json")
  641. }
  642. if (typeof spec == "string") { return {name: spec} }
  643. else { return spec || {name: "null"} }
  644. }
  645. // Given a mode spec (anything that resolveMode accepts), find and
  646. // initialize an actual mode object.
  647. function getMode(options, spec) {
  648. spec = resolveMode(spec);
  649. var mfactory = modes[spec.name];
  650. if (!mfactory) { return getMode(options, "text/plain") }
  651. var modeObj = mfactory(options, spec);
  652. if (modeExtensions.hasOwnProperty(spec.name)) {
  653. var exts = modeExtensions[spec.name];
  654. for (var prop in exts) {
  655. if (!exts.hasOwnProperty(prop)) { continue }
  656. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  657. modeObj[prop] = exts[prop];
  658. }
  659. }
  660. modeObj.name = spec.name;
  661. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  662. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  663. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  664. return modeObj
  665. }
  666. // This can be used to attach properties to mode objects from
  667. // outside the actual mode definition.
  668. var modeExtensions = {};
  669. function extendMode(mode, properties) {
  670. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  671. copyObj(properties, exts);
  672. }
  673. function copyState(mode, state) {
  674. if (state === true) { return state }
  675. if (mode.copyState) { return mode.copyState(state) }
  676. var nstate = {};
  677. for (var n in state) {
  678. var val = state[n];
  679. if (val instanceof Array) { val = val.concat([]); }
  680. nstate[n] = val;
  681. }
  682. return nstate
  683. }
  684. // Given a mode and a state (for that mode), find the inner mode and
  685. // state at the position that the state refers to.
  686. function innerMode(mode, state) {
  687. var info;
  688. while (mode.innerMode) {
  689. info = mode.innerMode(state);
  690. if (!info || info.mode == mode) { break }
  691. state = info.state;
  692. mode = info.mode;
  693. }
  694. return info || {mode: mode, state: state}
  695. }
  696. function startState(mode, a1, a2) {
  697. return mode.startState ? mode.startState(a1, a2) : true
  698. }
  699. // STRING STREAM
  700. // Fed to the mode parsers, provides helper functions to make
  701. // parsers more succinct.
  702. var StringStream = function(string, tabSize, lineOracle) {
  703. this.pos = this.start = 0;
  704. this.string = string;
  705. this.tabSize = tabSize || 8;
  706. this.lastColumnPos = this.lastColumnValue = 0;
  707. this.lineStart = 0;
  708. this.lineOracle = lineOracle;
  709. };
  710. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  711. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  712. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  713. StringStream.prototype.next = function () {
  714. if (this.pos < this.string.length)
  715. { return this.string.charAt(this.pos++) }
  716. };
  717. StringStream.prototype.eat = function (match) {
  718. var ch = this.string.charAt(this.pos);
  719. var ok;
  720. if (typeof match == "string") { ok = ch == match; }
  721. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  722. if (ok) {++this.pos; return ch}
  723. };
  724. StringStream.prototype.eatWhile = function (match) {
  725. var start = this.pos;
  726. while (this.eat(match)){}
  727. return this.pos > start
  728. };
  729. StringStream.prototype.eatSpace = function () {
  730. var this$1 = this;
  731. var start = this.pos;
  732. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  733. return this.pos > start
  734. };
  735. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  736. StringStream.prototype.skipTo = function (ch) {
  737. var found = this.string.indexOf(ch, this.pos);
  738. if (found > -1) {this.pos = found; return true}
  739. };
  740. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  741. StringStream.prototype.column = function () {
  742. if (this.lastColumnPos < this.start) {
  743. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  744. this.lastColumnPos = this.start;
  745. }
  746. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  747. };
  748. StringStream.prototype.indentation = function () {
  749. return countColumn(this.string, null, this.tabSize) -
  750. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  751. };
  752. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  753. if (typeof pattern == "string") {
  754. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  755. var substr = this.string.substr(this.pos, pattern.length);
  756. if (cased(substr) == cased(pattern)) {
  757. if (consume !== false) { this.pos += pattern.length; }
  758. return true
  759. }
  760. } else {
  761. var match = this.string.slice(this.pos).match(pattern);
  762. if (match && match.index > 0) { return null }
  763. if (match && consume !== false) { this.pos += match[0].length; }
  764. return match
  765. }
  766. };
  767. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  768. StringStream.prototype.hideFirstChars = function (n, inner) {
  769. this.lineStart += n;
  770. try { return inner() }
  771. finally { this.lineStart -= n; }
  772. };
  773. StringStream.prototype.lookAhead = function (n) {
  774. var oracle = this.lineOracle;
  775. return oracle && oracle.lookAhead(n)
  776. };
  777. StringStream.prototype.baseToken = function () {
  778. var oracle = this.lineOracle;
  779. return oracle && oracle.baseToken(this.pos)
  780. };
  781. // Find the line object corresponding to the given line number.
  782. function getLine(doc, n) {
  783. n -= doc.first;
  784. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  785. var chunk = doc;
  786. while (!chunk.lines) {
  787. for (var i = 0;; ++i) {
  788. var child = chunk.children[i], sz = child.chunkSize();
  789. if (n < sz) { chunk = child; break }
  790. n -= sz;
  791. }
  792. }
  793. return chunk.lines[n]
  794. }
  795. // Get the part of a document between two positions, as an array of
  796. // strings.
  797. function getBetween(doc, start, end) {
  798. var out = [], n = start.line;
  799. doc.iter(start.line, end.line + 1, function (line) {
  800. var text = line.text;
  801. if (n == end.line) { text = text.slice(0, end.ch); }
  802. if (n == start.line) { text = text.slice(start.ch); }
  803. out.push(text);
  804. ++n;
  805. });
  806. return out
  807. }
  808. // Get the lines between from and to, as array of strings.
  809. function getLines(doc, from, to) {
  810. var out = [];
  811. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  812. return out
  813. }
  814. // Update the height of a line, propagating the height change
  815. // upwards to parent nodes.
  816. function updateLineHeight(line, height) {
  817. var diff = height - line.height;
  818. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  819. }
  820. // Given a line object, find its line number by walking up through
  821. // its parent links.
  822. function lineNo(line) {
  823. if (line.parent == null) { return null }
  824. var cur = line.parent, no = indexOf(cur.lines, line);
  825. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  826. for (var i = 0;; ++i) {
  827. if (chunk.children[i] == cur) { break }
  828. no += chunk.children[i].chunkSize();
  829. }
  830. }
  831. return no + cur.first
  832. }
  833. // Find the line at the given vertical position, using the height
  834. // information in the document tree.
  835. function lineAtHeight(chunk, h) {
  836. var n = chunk.first;
  837. outer: do {
  838. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  839. var child = chunk.children[i$1], ch = child.height;
  840. if (h < ch) { chunk = child; continue outer }
  841. h -= ch;
  842. n += child.chunkSize();
  843. }
  844. return n
  845. } while (!chunk.lines)
  846. var i = 0;
  847. for (; i < chunk.lines.length; ++i) {
  848. var line = chunk.lines[i], lh = line.height;
  849. if (h < lh) { break }
  850. h -= lh;
  851. }
  852. return n + i
  853. }
  854. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  855. function lineNumberFor(options, i) {
  856. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  857. }
  858. // A Pos instance represents a position within the text.
  859. function Pos(line, ch, sticky) {
  860. if ( sticky === void 0 ) sticky = null;
  861. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  862. this.line = line;
  863. this.ch = ch;
  864. this.sticky = sticky;
  865. }
  866. // Compare two positions, return 0 if they are the same, a negative
  867. // number when a is less, and a positive number otherwise.
  868. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  869. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  870. function copyPos(x) {return Pos(x.line, x.ch)}
  871. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  872. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  873. // Most of the external API clips given positions to make sure they
  874. // actually exist within the document.
  875. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  876. function clipPos(doc, pos) {
  877. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  878. var last = doc.first + doc.size - 1;
  879. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  880. return clipToLen(pos, getLine(doc, pos.line).text.length)
  881. }
  882. function clipToLen(pos, linelen) {
  883. var ch = pos.ch;
  884. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  885. else if (ch < 0) { return Pos(pos.line, 0) }
  886. else { return pos }
  887. }
  888. function clipPosArray(doc, array) {
  889. var out = [];
  890. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  891. return out
  892. }
  893. var SavedContext = function(state, lookAhead) {
  894. this.state = state;
  895. this.lookAhead = lookAhead;
  896. };
  897. var Context = function(doc, state, line, lookAhead) {
  898. this.state = state;
  899. this.doc = doc;
  900. this.line = line;
  901. this.maxLookAhead = lookAhead || 0;
  902. this.baseTokens = null;
  903. this.baseTokenPos = 1;
  904. };
  905. Context.prototype.lookAhead = function (n) {
  906. var line = this.doc.getLine(this.line + n);
  907. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  908. return line
  909. };
  910. Context.prototype.baseToken = function (n) {
  911. var this$1 = this;
  912. if (!this.baseTokens) { return null }
  913. while (this.baseTokens[this.baseTokenPos] <= n)
  914. { this$1.baseTokenPos += 2; }
  915. var type = this.baseTokens[this.baseTokenPos + 1];
  916. return {type: type && type.replace(/( |^)overlay .*/, ""),
  917. size: this.baseTokens[this.baseTokenPos] - n}
  918. };
  919. Context.prototype.nextLine = function () {
  920. this.line++;
  921. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  922. };
  923. Context.fromSaved = function (doc, saved, line) {
  924. if (saved instanceof SavedContext)
  925. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  926. else
  927. { return new Context(doc, copyState(doc.mode, saved), line) }
  928. };
  929. Context.prototype.save = function (copy) {
  930. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  931. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  932. };
  933. // Compute a style array (an array starting with a mode generation
  934. // -- for invalidation -- followed by pairs of end positions and
  935. // style strings), which is used to highlight the tokens on the
  936. // line.
  937. function highlightLine(cm, line, context, forceToEnd) {
  938. // A styles array always starts with a number identifying the
  939. // mode/overlays that it is based on (for easy invalidation).
  940. var st = [cm.state.modeGen], lineClasses = {};
  941. // Compute the base array of styles
  942. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  943. lineClasses, forceToEnd);
  944. var state = context.state;
  945. // Run overlays, adjust style array.
  946. var loop = function ( o ) {
  947. context.baseTokens = st;
  948. var overlay = cm.state.overlays[o], i = 1, at = 0;
  949. context.state = true;
  950. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  951. var start = i;
  952. // Ensure there's a token end at the current position, and that i points at it
  953. while (at < end) {
  954. var i_end = st[i];
  955. if (i_end > end)
  956. { st.splice(i, 1, end, st[i+1], i_end); }
  957. i += 2;
  958. at = Math.min(end, i_end);
  959. }
  960. if (!style) { return }
  961. if (overlay.opaque) {
  962. st.splice(start, i - start, end, "overlay " + style);
  963. i = start + 2;
  964. } else {
  965. for (; start < i; start += 2) {
  966. var cur = st[start+1];
  967. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  968. }
  969. }
  970. }, lineClasses);
  971. context.state = state;
  972. context.baseTokens = null;
  973. context.baseTokenPos = 1;
  974. };
  975. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  976. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  977. }
  978. function getLineStyles(cm, line, updateFrontier) {
  979. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  980. var context = getContextBefore(cm, lineNo(line));
  981. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  982. var result = highlightLine(cm, line, context);
  983. if (resetState) { context.state = resetState; }
  984. line.stateAfter = context.save(!resetState);
  985. line.styles = result.styles;
  986. if (result.classes) { line.styleClasses = result.classes; }
  987. else if (line.styleClasses) { line.styleClasses = null; }
  988. if (updateFrontier === cm.doc.highlightFrontier)
  989. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  990. }
  991. return line.styles
  992. }
  993. function getContextBefore(cm, n, precise) {
  994. var doc = cm.doc, display = cm.display;
  995. if (!doc.mode.startState) { return new Context(doc, true, n) }
  996. var start = findStartLine(cm, n, precise);
  997. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  998. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  999. doc.iter(start, n, function (line) {
  1000. processLine(cm, line.text, context);
  1001. var pos = context.line;
  1002. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1003. context.nextLine();
  1004. });
  1005. if (precise) { doc.modeFrontier = context.line; }
  1006. return context
  1007. }
  1008. // Lightweight form of highlight -- proceed over this line and
  1009. // update state, but don't save a style array. Used for lines that
  1010. // aren't currently visible.
  1011. function processLine(cm, text, context, startAt) {
  1012. var mode = cm.doc.mode;
  1013. var stream = new StringStream(text, cm.options.tabSize, context);
  1014. stream.start = stream.pos = startAt || 0;
  1015. if (text == "") { callBlankLine(mode, context.state); }
  1016. while (!stream.eol()) {
  1017. readToken(mode, stream, context.state);
  1018. stream.start = stream.pos;
  1019. }
  1020. }
  1021. function callBlankLine(mode, state) {
  1022. if (mode.blankLine) { return mode.blankLine(state) }
  1023. if (!mode.innerMode) { return }
  1024. var inner = innerMode(mode, state);
  1025. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1026. }
  1027. function readToken(mode, stream, state, inner) {
  1028. for (var i = 0; i < 10; i++) {
  1029. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1030. var style = mode.token(stream, state);
  1031. if (stream.pos > stream.start) { return style }
  1032. }
  1033. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1034. }
  1035. var Token = function(stream, type, state) {
  1036. this.start = stream.start; this.end = stream.pos;
  1037. this.string = stream.current();
  1038. this.type = type || null;
  1039. this.state = state;
  1040. };
  1041. // Utility for getTokenAt and getLineTokens
  1042. function takeToken(cm, pos, precise, asArray) {
  1043. var doc = cm.doc, mode = doc.mode, style;
  1044. pos = clipPos(doc, pos);
  1045. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1046. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1047. if (asArray) { tokens = []; }
  1048. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1049. stream.start = stream.pos;
  1050. style = readToken(mode, stream, context.state);
  1051. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1052. }
  1053. return asArray ? tokens : new Token(stream, style, context.state)
  1054. }
  1055. function extractLineClasses(type, output) {
  1056. if (type) { for (;;) {
  1057. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1058. if (!lineClass) { break }
  1059. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1060. var prop = lineClass[1] ? "bgClass" : "textClass";
  1061. if (output[prop] == null)
  1062. { output[prop] = lineClass[2]; }
  1063. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1064. { output[prop] += " " + lineClass[2]; }
  1065. } }
  1066. return type
  1067. }
  1068. // Run the given mode's parser over a line, calling f for each token.
  1069. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1070. var flattenSpans = mode.flattenSpans;
  1071. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1072. var curStart = 0, curStyle = null;
  1073. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1074. var inner = cm.options.addModeClass && [null];
  1075. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1076. while (!stream.eol()) {
  1077. if (stream.pos > cm.options.maxHighlightLength) {
  1078. flattenSpans = false;
  1079. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1080. stream.pos = text.length;
  1081. style = null;
  1082. } else {
  1083. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1084. }
  1085. if (inner) {
  1086. var mName = inner[0].name;
  1087. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1088. }
  1089. if (!flattenSpans || curStyle != style) {
  1090. while (curStart < stream.start) {
  1091. curStart = Math.min(stream.start, curStart + 5000);
  1092. f(curStart, curStyle);
  1093. }
  1094. curStyle = style;
  1095. }
  1096. stream.start = stream.pos;
  1097. }
  1098. while (curStart < stream.pos) {
  1099. // Webkit seems to refuse to render text nodes longer than 57444
  1100. // characters, and returns inaccurate measurements in nodes
  1101. // starting around 5000 chars.
  1102. var pos = Math.min(stream.pos, curStart + 5000);
  1103. f(pos, curStyle);
  1104. curStart = pos;
  1105. }
  1106. }
  1107. // Finds the line to start with when starting a parse. Tries to
  1108. // find a line with a stateAfter, so that it can start with a
  1109. // valid state. If that fails, it returns the line with the
  1110. // smallest indentation, which tends to need the least context to
  1111. // parse correctly.
  1112. function findStartLine(cm, n, precise) {
  1113. var minindent, minline, doc = cm.doc;
  1114. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1115. for (var search = n; search > lim; --search) {
  1116. if (search <= doc.first) { return doc.first }
  1117. var line = getLine(doc, search - 1), after = line.stateAfter;
  1118. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1119. { return search }
  1120. var indented = countColumn(line.text, null, cm.options.tabSize);
  1121. if (minline == null || minindent > indented) {
  1122. minline = search - 1;
  1123. minindent = indented;
  1124. }
  1125. }
  1126. return minline
  1127. }
  1128. function retreatFrontier(doc, n) {
  1129. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1130. if (doc.highlightFrontier < n - 10) { return }
  1131. var start = doc.first;
  1132. for (var line = n - 1; line > start; line--) {
  1133. var saved = getLine(doc, line).stateAfter;
  1134. // change is on 3
  1135. // state on line 1 looked ahead 2 -- so saw 3
  1136. // test 1 + 2 < 3 should cover this
  1137. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1138. start = line + 1;
  1139. break
  1140. }
  1141. }
  1142. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1143. }
  1144. // Optimize some code when these features are not used.
  1145. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1146. function seeReadOnlySpans() {
  1147. sawReadOnlySpans = true;
  1148. }
  1149. function seeCollapsedSpans() {
  1150. sawCollapsedSpans = true;
  1151. }
  1152. // TEXTMARKER SPANS
  1153. function MarkedSpan(marker, from, to) {
  1154. this.marker = marker;
  1155. this.from = from; this.to = to;
  1156. }
  1157. // Search an array of spans for a span matching the given marker.
  1158. function getMarkedSpanFor(spans, marker) {
  1159. if (spans) { for (var i = 0; i < spans.length; ++i) {
  1160. var span = spans[i];
  1161. if (span.marker == marker) { return span }
  1162. } }
  1163. }
  1164. // Remove a span from an array, returning undefined if no spans are
  1165. // left (we don't store arrays for lines without spans).
  1166. function removeMarkedSpan(spans, span) {
  1167. var r;
  1168. for (var i = 0; i < spans.length; ++i)
  1169. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1170. return r
  1171. }
  1172. // Add a span to a line.
  1173. function addMarkedSpan(line, span) {
  1174. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1175. span.marker.attachLine(line);
  1176. }
  1177. // Used for the algorithm that adjusts markers for a change in the
  1178. // document. These functions cut an array of spans at a given
  1179. // character position, returning an array of remaining chunks (or
  1180. // undefined if nothing remains).
  1181. function markedSpansBefore(old, startCh, isInsert) {
  1182. var nw;
  1183. if (old) { for (var i = 0; i < old.length; ++i) {
  1184. var span = old[i], marker = span.marker;
  1185. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1186. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1187. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1188. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1189. }
  1190. } }
  1191. return nw
  1192. }
  1193. function markedSpansAfter(old, endCh, isInsert) {
  1194. var nw;
  1195. if (old) { for (var i = 0; i < old.length; ++i) {
  1196. var span = old[i], marker = span.marker;
  1197. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1198. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1199. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1200. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1201. span.to == null ? null : span.to - endCh));
  1202. }
  1203. } }
  1204. return nw
  1205. }
  1206. // Given a change object, compute the new set of marker spans that
  1207. // cover the line in which the change took place. Removes spans
  1208. // entirely within the change, reconnects spans belonging to the
  1209. // same marker that appear on both sides of the change, and cuts off
  1210. // spans partially within the change. Returns an array of span
  1211. // arrays with one element for each line in (after) the change.
  1212. function stretchSpansOverChange(doc, change) {
  1213. if (change.full) { return null }
  1214. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1215. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1216. if (!oldFirst && !oldLast) { return null }
  1217. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1218. // Get the spans that 'stick out' on both sides
  1219. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1220. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1221. // Next, merge those two ends
  1222. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1223. if (first) {
  1224. // Fix up .to properties of first
  1225. for (var i = 0; i < first.length; ++i) {
  1226. var span = first[i];
  1227. if (span.to == null) {
  1228. var found = getMarkedSpanFor(last, span.marker);
  1229. if (!found) { span.to = startCh; }
  1230. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1231. }
  1232. }
  1233. }
  1234. if (last) {
  1235. // Fix up .from in last (or move them into first in case of sameLine)
  1236. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1237. var span$1 = last[i$1];
  1238. if (span$1.to != null) { span$1.to += offset; }
  1239. if (span$1.from == null) {
  1240. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1241. if (!found$1) {
  1242. span$1.from = offset;
  1243. if (sameLine) { (first || (first = [])).push(span$1); }
  1244. }
  1245. } else {
  1246. span$1.from += offset;
  1247. if (sameLine) { (first || (first = [])).push(span$1); }
  1248. }
  1249. }
  1250. }
  1251. // Make sure we didn't create any zero-length spans
  1252. if (first) { first = clearEmptySpans(first); }
  1253. if (last && last != first) { last = clearEmptySpans(last); }
  1254. var newMarkers = [first];
  1255. if (!sameLine) {
  1256. // Fill gap with whole-line-spans
  1257. var gap = change.text.length - 2, gapMarkers;
  1258. if (gap > 0 && first)
  1259. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1260. { if (first[i$2].to == null)
  1261. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1262. for (var i$3 = 0; i$3 < gap; ++i$3)
  1263. { newMarkers.push(gapMarkers); }
  1264. newMarkers.push(last);
  1265. }
  1266. return newMarkers
  1267. }
  1268. // Remove spans that are empty and don't have a clearWhenEmpty
  1269. // option of false.
  1270. function clearEmptySpans(spans) {
  1271. for (var i = 0; i < spans.length; ++i) {
  1272. var span = spans[i];
  1273. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1274. { spans.splice(i--, 1); }
  1275. }
  1276. if (!spans.length) { return null }
  1277. return spans
  1278. }
  1279. // Used to 'clip' out readOnly ranges when making a change.
  1280. function removeReadOnlyRanges(doc, from, to) {
  1281. var markers = null;
  1282. doc.iter(from.line, to.line + 1, function (line) {
  1283. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1284. var mark = line.markedSpans[i].marker;
  1285. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1286. { (markers || (markers = [])).push(mark); }
  1287. } }
  1288. });
  1289. if (!markers) { return null }
  1290. var parts = [{from: from, to: to}];
  1291. for (var i = 0; i < markers.length; ++i) {
  1292. var mk = markers[i], m = mk.find(0);
  1293. for (var j = 0; j < parts.length; ++j) {
  1294. var p = parts[j];
  1295. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1296. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1297. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1298. { newParts.push({from: p.from, to: m.from}); }
  1299. if (dto > 0 || !mk.inclusiveRight && !dto)
  1300. { newParts.push({from: m.to, to: p.to}); }
  1301. parts.splice.apply(parts, newParts);
  1302. j += newParts.length - 3;
  1303. }
  1304. }
  1305. return parts
  1306. }
  1307. // Connect or disconnect spans from a line.
  1308. function detachMarkedSpans(line) {
  1309. var spans = line.markedSpans;
  1310. if (!spans) { return }
  1311. for (var i = 0; i < spans.length; ++i)
  1312. { spans[i].marker.detachLine(line); }
  1313. line.markedSpans = null;
  1314. }
  1315. function attachMarkedSpans(line, spans) {
  1316. if (!spans) { return }
  1317. for (var i = 0; i < spans.length; ++i)
  1318. { spans[i].marker.attachLine(line); }
  1319. line.markedSpans = spans;
  1320. }
  1321. // Helpers used when computing which overlapping collapsed span
  1322. // counts as the larger one.
  1323. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1324. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1325. // Returns a number indicating which of two overlapping collapsed
  1326. // spans is larger (and thus includes the other). Falls back to
  1327. // comparing ids when the spans cover exactly the same range.
  1328. function compareCollapsedMarkers(a, b) {
  1329. var lenDiff = a.lines.length - b.lines.length;
  1330. if (lenDiff != 0) { return lenDiff }
  1331. var aPos = a.find(), bPos = b.find();
  1332. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1333. if (fromCmp) { return -fromCmp }
  1334. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1335. if (toCmp) { return toCmp }
  1336. return b.id - a.id
  1337. }
  1338. // Find out whether a line ends or starts in a collapsed span. If
  1339. // so, return the marker for that span.
  1340. function collapsedSpanAtSide(line, start) {
  1341. var sps = sawCollapsedSpans && line.markedSpans, found;
  1342. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1343. sp = sps[i];
  1344. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1345. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1346. { found = sp.marker; }
  1347. } }
  1348. return found
  1349. }
  1350. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1351. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1352. function collapsedSpanAround(line, ch) {
  1353. var sps = sawCollapsedSpans && line.markedSpans, found;
  1354. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1355. var sp = sps[i];
  1356. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1357. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1358. } }
  1359. return found
  1360. }
  1361. // Test whether there exists a collapsed span that partially
  1362. // overlaps (covers the start or end, but not both) of a new span.
  1363. // Such overlap is not allowed.
  1364. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  1365. var line = getLine(doc, lineNo$$1);
  1366. var sps = sawCollapsedSpans && line.markedSpans;
  1367. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1368. var sp = sps[i];
  1369. if (!sp.marker.collapsed) { continue }
  1370. var found = sp.marker.find(0);
  1371. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1372. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1373. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1374. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1375. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1376. { return true }
  1377. } }
  1378. }
  1379. // A visual line is a line as drawn on the screen. Folding, for
  1380. // example, can cause multiple logical lines to appear on the same
  1381. // visual line. This finds the start of the visual line that the
  1382. // given line is part of (usually that is the line itself).
  1383. function visualLine(line) {
  1384. var merged;
  1385. while (merged = collapsedSpanAtStart(line))
  1386. { line = merged.find(-1, true).line; }
  1387. return line
  1388. }
  1389. function visualLineEnd(line) {
  1390. var merged;
  1391. while (merged = collapsedSpanAtEnd(line))
  1392. { line = merged.find(1, true).line; }
  1393. return line
  1394. }
  1395. // Returns an array of logical lines that continue the visual line
  1396. // started by the argument, or undefined if there are no such lines.
  1397. function visualLineContinued(line) {
  1398. var merged, lines;
  1399. while (merged = collapsedSpanAtEnd(line)) {
  1400. line = merged.find(1, true).line
  1401. ;(lines || (lines = [])).push(line);
  1402. }
  1403. return lines
  1404. }
  1405. // Get the line number of the start of the visual line that the
  1406. // given line number is part of.
  1407. function visualLineNo(doc, lineN) {
  1408. var line = getLine(doc, lineN), vis = visualLine(line);
  1409. if (line == vis) { return lineN }
  1410. return lineNo(vis)
  1411. }
  1412. // Get the line number of the start of the next visual line after
  1413. // the given line.
  1414. function visualLineEndNo(doc, lineN) {
  1415. if (lineN > doc.lastLine()) { return lineN }
  1416. var line = getLine(doc, lineN), merged;
  1417. if (!lineIsHidden(doc, line)) { return lineN }
  1418. while (merged = collapsedSpanAtEnd(line))
  1419. { line = merged.find(1, true).line; }
  1420. return lineNo(line) + 1
  1421. }
  1422. // Compute whether a line is hidden. Lines count as hidden when they
  1423. // are part of a visual line that starts with another line, or when
  1424. // they are entirely covered by collapsed, non-widget span.
  1425. function lineIsHidden(doc, line) {
  1426. var sps = sawCollapsedSpans && line.markedSpans;
  1427. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1428. sp = sps[i];
  1429. if (!sp.marker.collapsed) { continue }
  1430. if (sp.from == null) { return true }
  1431. if (sp.marker.widgetNode) { continue }
  1432. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1433. { return true }
  1434. } }
  1435. }
  1436. function lineIsHiddenInner(doc, line, span) {
  1437. if (span.to == null) {
  1438. var end = span.marker.find(1, true);
  1439. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1440. }
  1441. if (span.marker.inclusiveRight && span.to == line.text.length)
  1442. { return true }
  1443. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1444. sp = line.markedSpans[i];
  1445. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1446. (sp.to == null || sp.to != span.from) &&
  1447. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1448. lineIsHiddenInner(doc, line, sp)) { return true }
  1449. }
  1450. }
  1451. // Find the height above the given line.
  1452. function heightAtLine(lineObj) {
  1453. lineObj = visualLine(lineObj);
  1454. var h = 0, chunk = lineObj.parent;
  1455. for (var i = 0; i < chunk.lines.length; ++i) {
  1456. var line = chunk.lines[i];
  1457. if (line == lineObj) { break }
  1458. else { h += line.height; }
  1459. }
  1460. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1461. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1462. var cur = p.children[i$1];
  1463. if (cur == chunk) { break }
  1464. else { h += cur.height; }
  1465. }
  1466. }
  1467. return h
  1468. }
  1469. // Compute the character length of a line, taking into account
  1470. // collapsed ranges (see markText) that might hide parts, and join
  1471. // other lines onto it.
  1472. function lineLength(line) {
  1473. if (line.height == 0) { return 0 }
  1474. var len = line.text.length, merged, cur = line;
  1475. while (merged = collapsedSpanAtStart(cur)) {
  1476. var found = merged.find(0, true);
  1477. cur = found.from.line;
  1478. len += found.from.ch - found.to.ch;
  1479. }
  1480. cur = line;
  1481. while (merged = collapsedSpanAtEnd(cur)) {
  1482. var found$1 = merged.find(0, true);
  1483. len -= cur.text.length - found$1.from.ch;
  1484. cur = found$1.to.line;
  1485. len += cur.text.length - found$1.to.ch;
  1486. }
  1487. return len
  1488. }
  1489. // Find the longest line in the document.
  1490. function findMaxLine(cm) {
  1491. var d = cm.display, doc = cm.doc;
  1492. d.maxLine = getLine(doc, doc.first);
  1493. d.maxLineLength = lineLength(d.maxLine);
  1494. d.maxLineChanged = true;
  1495. doc.iter(function (line) {
  1496. var len = lineLength(line);
  1497. if (len > d.maxLineLength) {
  1498. d.maxLineLength = len;
  1499. d.maxLine = line;
  1500. }
  1501. });
  1502. }
  1503. // LINE DATA STRUCTURE
  1504. // Line objects. These hold state related to a line, including
  1505. // highlighting info (the styles array).
  1506. var Line = function(text, markedSpans, estimateHeight) {
  1507. this.text = text;
  1508. attachMarkedSpans(this, markedSpans);
  1509. this.height = estimateHeight ? estimateHeight(this) : 1;
  1510. };
  1511. Line.prototype.lineNo = function () { return lineNo(this) };
  1512. eventMixin(Line);
  1513. // Change the content (text, markers) of a line. Automatically
  1514. // invalidates cached information and tries to re-estimate the
  1515. // line's height.
  1516. function updateLine(line, text, markedSpans, estimateHeight) {
  1517. line.text = text;
  1518. if (line.stateAfter) { line.stateAfter = null; }
  1519. if (line.styles) { line.styles = null; }
  1520. if (line.order != null) { line.order = null; }
  1521. detachMarkedSpans(line);
  1522. attachMarkedSpans(line, markedSpans);
  1523. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1524. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1525. }
  1526. // Detach a line from the document tree and its markers.
  1527. function cleanUpLine(line) {
  1528. line.parent = null;
  1529. detachMarkedSpans(line);
  1530. }
  1531. // Convert a style as returned by a mode (either null, or a string
  1532. // containing one or more styles) to a CSS style. This is cached,
  1533. // and also looks for line-wide styles.
  1534. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1535. function interpretTokenStyle(style, options) {
  1536. if (!style || /^\s*$/.test(style)) { return null }
  1537. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1538. return cache[style] ||
  1539. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1540. }
  1541. // Render the DOM representation of the text of a line. Also builds
  1542. // up a 'line map', which points at the DOM nodes that represent
  1543. // specific stretches of text, and is used by the measuring code.
  1544. // The returned object contains the DOM node, this map, and
  1545. // information about line-wide styles that were set by the mode.
  1546. function buildLineContent(cm, lineView) {
  1547. // The padding-right forces the element to have a 'border', which
  1548. // is needed on Webkit to be able to get line-level bounding
  1549. // rectangles for it (in measureChar).
  1550. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1551. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1552. col: 0, pos: 0, cm: cm,
  1553. trailingSpace: false,
  1554. splitSpaces: cm.getOption("lineWrapping")};
  1555. lineView.measure = {};
  1556. // Iterate over the logical lines that make up this visual line.
  1557. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1558. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1559. builder.pos = 0;
  1560. builder.addToken = buildToken;
  1561. // Optionally wire in some hacks into the token-rendering
  1562. // algorithm, to deal with browser quirks.
  1563. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1564. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1565. builder.map = [];
  1566. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1567. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1568. if (line.styleClasses) {
  1569. if (line.styleClasses.bgClass)
  1570. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1571. if (line.styleClasses.textClass)
  1572. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1573. }
  1574. // Ensure at least a single node is present, for measuring.
  1575. if (builder.map.length == 0)
  1576. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1577. // Store the map and a cache object for the current logical line
  1578. if (i == 0) {
  1579. lineView.measure.map = builder.map;
  1580. lineView.measure.cache = {};
  1581. } else {
  1582. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1583. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1584. }
  1585. }
  1586. // See issue #2901
  1587. if (webkit) {
  1588. var last = builder.content.lastChild;
  1589. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1590. { builder.content.className = "cm-tab-wrap-hack"; }
  1591. }
  1592. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1593. if (builder.pre.className)
  1594. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1595. return builder
  1596. }
  1597. function defaultSpecialCharPlaceholder(ch) {
  1598. var token = elt("span", "\u2022", "cm-invalidchar");
  1599. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1600. token.setAttribute("aria-label", token.title);
  1601. return token
  1602. }
  1603. // Build up the DOM representation for a single token, and add it to
  1604. // the line map. Takes care to render special characters separately.
  1605. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1606. if (!text) { return }
  1607. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1608. var special = builder.cm.state.specialChars, mustWrap = false;
  1609. var content;
  1610. if (!special.test(text)) {
  1611. builder.col += text.length;
  1612. content = document.createTextNode(displayText);
  1613. builder.map.push(builder.pos, builder.pos + text.length, content);
  1614. if (ie && ie_version < 9) { mustWrap = true; }
  1615. builder.pos += text.length;
  1616. } else {
  1617. content = document.createDocumentFragment();
  1618. var pos = 0;
  1619. while (true) {
  1620. special.lastIndex = pos;
  1621. var m = special.exec(text);
  1622. var skipped = m ? m.index - pos : text.length - pos;
  1623. if (skipped) {
  1624. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1625. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1626. else { content.appendChild(txt); }
  1627. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1628. builder.col += skipped;
  1629. builder.pos += skipped;
  1630. }
  1631. if (!m) { break }
  1632. pos += skipped + 1;
  1633. var txt$1 = (void 0);
  1634. if (m[0] == "\t") {
  1635. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1636. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1637. txt$1.setAttribute("role", "presentation");
  1638. txt$1.setAttribute("cm-text", "\t");
  1639. builder.col += tabWidth;
  1640. } else if (m[0] == "\r" || m[0] == "\n") {
  1641. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1642. txt$1.setAttribute("cm-text", m[0]);
  1643. builder.col += 1;
  1644. } else {
  1645. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1646. txt$1.setAttribute("cm-text", m[0]);
  1647. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1648. else { content.appendChild(txt$1); }
  1649. builder.col += 1;
  1650. }
  1651. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1652. builder.pos++;
  1653. }
  1654. }
  1655. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1656. if (style || startStyle || endStyle || mustWrap || css) {
  1657. var fullStyle = style || "";
  1658. if (startStyle) { fullStyle += startStyle; }
  1659. if (endStyle) { fullStyle += endStyle; }
  1660. var token = elt("span", [content], fullStyle, css);
  1661. if (attributes) {
  1662. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1663. { token.setAttribute(attr, attributes[attr]); } }
  1664. }
  1665. return builder.content.appendChild(token)
  1666. }
  1667. builder.content.appendChild(content);
  1668. }
  1669. // Change some spaces to NBSP to prevent the browser from collapsing
  1670. // trailing spaces at the end of a line when rendering text (issue #1362).
  1671. function splitSpaces(text, trailingBefore) {
  1672. if (text.length > 1 && !/ /.test(text)) { return text }
  1673. var spaceBefore = trailingBefore, result = "";
  1674. for (var i = 0; i < text.length; i++) {
  1675. var ch = text.charAt(i);
  1676. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1677. { ch = "\u00a0"; }
  1678. result += ch;
  1679. spaceBefore = ch == " ";
  1680. }
  1681. return result
  1682. }
  1683. // Work around nonsense dimensions being reported for stretches of
  1684. // right-to-left text.
  1685. function buildTokenBadBidi(inner, order) {
  1686. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1687. style = style ? style + " cm-force-border" : "cm-force-border";
  1688. var start = builder.pos, end = start + text.length;
  1689. for (;;) {
  1690. // Find the part that overlaps with the start of this text
  1691. var part = (void 0);
  1692. for (var i = 0; i < order.length; i++) {
  1693. part = order[i];
  1694. if (part.to > start && part.from <= start) { break }
  1695. }
  1696. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1697. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1698. startStyle = null;
  1699. text = text.slice(part.to - start);
  1700. start = part.to;
  1701. }
  1702. }
  1703. }
  1704. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1705. var widget = !ignoreWidget && marker.widgetNode;
  1706. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1707. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1708. if (!widget)
  1709. { widget = builder.content.appendChild(document.createElement("span")); }
  1710. widget.setAttribute("cm-marker", marker.id);
  1711. }
  1712. if (widget) {
  1713. builder.cm.display.input.setUneditable(widget);
  1714. builder.content.appendChild(widget);
  1715. }
  1716. builder.pos += size;
  1717. builder.trailingSpace = false;
  1718. }
  1719. // Outputs a number of spans to make up a line, taking highlighting
  1720. // and marked text into account.
  1721. function insertLineContent(line, builder, styles) {
  1722. var spans = line.markedSpans, allText = line.text, at = 0;
  1723. if (!spans) {
  1724. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1725. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1726. return
  1727. }
  1728. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1729. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1730. for (;;) {
  1731. if (nextChange == pos) { // Update current marker set
  1732. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1733. attributes = null;
  1734. collapsed = null; nextChange = Infinity;
  1735. var foundBookmarks = [], endStyles = (void 0);
  1736. for (var j = 0; j < spans.length; ++j) {
  1737. var sp = spans[j], m = sp.marker;
  1738. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1739. foundBookmarks.push(m);
  1740. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1741. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1742. nextChange = sp.to;
  1743. spanEndStyle = "";
  1744. }
  1745. if (m.className) { spanStyle += " " + m.className; }
  1746. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1747. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1748. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1749. // support for the old title property
  1750. // https://github.com/codemirror/CodeMirror/pull/5673
  1751. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1752. if (m.attributes) {
  1753. for (var attr in m.attributes)
  1754. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1755. }
  1756. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1757. { collapsed = sp; }
  1758. } else if (sp.from > pos && nextChange > sp.from) {
  1759. nextChange = sp.from;
  1760. }
  1761. }
  1762. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1763. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1764. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1765. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1766. if (collapsed && (collapsed.from || 0) == pos) {
  1767. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1768. collapsed.marker, collapsed.from == null);
  1769. if (collapsed.to == null) { return }
  1770. if (collapsed.to == pos) { collapsed = false; }
  1771. }
  1772. }
  1773. if (pos >= len) { break }
  1774. var upto = Math.min(len, nextChange);
  1775. while (true) {
  1776. if (text) {
  1777. var end = pos + text.length;
  1778. if (!collapsed) {
  1779. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1780. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1781. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1782. }
  1783. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1784. pos = end;
  1785. spanStartStyle = "";
  1786. }
  1787. text = allText.slice(at, at = styles[i++]);
  1788. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1789. }
  1790. }
  1791. }
  1792. // These objects are used to represent the visible (currently drawn)
  1793. // part of the document. A LineView may correspond to multiple
  1794. // logical lines, if those are connected by collapsed ranges.
  1795. function LineView(doc, line, lineN) {
  1796. // The starting line
  1797. this.line = line;
  1798. // Continuing lines, if any
  1799. this.rest = visualLineContinued(line);
  1800. // Number of logical lines in this visual line
  1801. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1802. this.node = this.text = null;
  1803. this.hidden = lineIsHidden(doc, line);
  1804. }
  1805. // Create a range of LineView objects for the given lines.
  1806. function buildViewArray(cm, from, to) {
  1807. var array = [], nextPos;
  1808. for (var pos = from; pos < to; pos = nextPos) {
  1809. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1810. nextPos = pos + view.size;
  1811. array.push(view);
  1812. }
  1813. return array
  1814. }
  1815. var operationGroup = null;
  1816. function pushOperation(op) {
  1817. if (operationGroup) {
  1818. operationGroup.ops.push(op);
  1819. } else {
  1820. op.ownsGroup = operationGroup = {
  1821. ops: [op],
  1822. delayedCallbacks: []
  1823. };
  1824. }
  1825. }
  1826. function fireCallbacksForOps(group) {
  1827. // Calls delayed callbacks and cursorActivity handlers until no
  1828. // new ones appear
  1829. var callbacks = group.delayedCallbacks, i = 0;
  1830. do {
  1831. for (; i < callbacks.length; i++)
  1832. { callbacks[i].call(null); }
  1833. for (var j = 0; j < group.ops.length; j++) {
  1834. var op = group.ops[j];
  1835. if (op.cursorActivityHandlers)
  1836. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1837. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1838. }
  1839. } while (i < callbacks.length)
  1840. }
  1841. function finishOperation(op, endCb) {
  1842. var group = op.ownsGroup;
  1843. if (!group) { return }
  1844. try { fireCallbacksForOps(group); }
  1845. finally {
  1846. operationGroup = null;
  1847. endCb(group);
  1848. }
  1849. }
  1850. var orphanDelayedCallbacks = null;
  1851. // Often, we want to signal events at a point where we are in the
  1852. // middle of some work, but don't want the handler to start calling
  1853. // other methods on the editor, which might be in an inconsistent
  1854. // state or simply not expect any other events to happen.
  1855. // signalLater looks whether there are any handlers, and schedules
  1856. // them to be executed when the last operation ends, or, if no
  1857. // operation is active, when a timeout fires.
  1858. function signalLater(emitter, type /*, values...*/) {
  1859. var arr = getHandlers(emitter, type);
  1860. if (!arr.length) { return }
  1861. var args = Array.prototype.slice.call(arguments, 2), list;
  1862. if (operationGroup) {
  1863. list = operationGroup.delayedCallbacks;
  1864. } else if (orphanDelayedCallbacks) {
  1865. list = orphanDelayedCallbacks;
  1866. } else {
  1867. list = orphanDelayedCallbacks = [];
  1868. setTimeout(fireOrphanDelayed, 0);
  1869. }
  1870. var loop = function ( i ) {
  1871. list.push(function () { return arr[i].apply(null, args); });
  1872. };
  1873. for (var i = 0; i < arr.length; ++i)
  1874. loop( i );
  1875. }
  1876. function fireOrphanDelayed() {
  1877. var delayed = orphanDelayedCallbacks;
  1878. orphanDelayedCallbacks = null;
  1879. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1880. }
  1881. // When an aspect of a line changes, a string is added to
  1882. // lineView.changes. This updates the relevant part of the line's
  1883. // DOM structure.
  1884. function updateLineForChanges(cm, lineView, lineN, dims) {
  1885. for (var j = 0; j < lineView.changes.length; j++) {
  1886. var type = lineView.changes[j];
  1887. if (type == "text") { updateLineText(cm, lineView); }
  1888. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1889. else if (type == "class") { updateLineClasses(cm, lineView); }
  1890. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1891. }
  1892. lineView.changes = null;
  1893. }
  1894. // Lines with gutter elements, widgets or a background class need to
  1895. // be wrapped, and have the extra elements added to the wrapper div
  1896. function ensureLineWrapped(lineView) {
  1897. if (lineView.node == lineView.text) {
  1898. lineView.node = elt("div", null, null, "position: relative");
  1899. if (lineView.text.parentNode)
  1900. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1901. lineView.node.appendChild(lineView.text);
  1902. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1903. }
  1904. return lineView.node
  1905. }
  1906. function updateLineBackground(cm, lineView) {
  1907. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1908. if (cls) { cls += " CodeMirror-linebackground"; }
  1909. if (lineView.background) {
  1910. if (cls) { lineView.background.className = cls; }
  1911. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1912. } else if (cls) {
  1913. var wrap = ensureLineWrapped(lineView);
  1914. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1915. cm.display.input.setUneditable(lineView.background);
  1916. }
  1917. }
  1918. // Wrapper around buildLineContent which will reuse the structure
  1919. // in display.externalMeasured when possible.
  1920. function getLineContent(cm, lineView) {
  1921. var ext = cm.display.externalMeasured;
  1922. if (ext && ext.line == lineView.line) {
  1923. cm.display.externalMeasured = null;
  1924. lineView.measure = ext.measure;
  1925. return ext.built
  1926. }
  1927. return buildLineContent(cm, lineView)
  1928. }
  1929. // Redraw the line's text. Interacts with the background and text
  1930. // classes because the mode may output tokens that influence these
  1931. // classes.
  1932. function updateLineText(cm, lineView) {
  1933. var cls = lineView.text.className;
  1934. var built = getLineContent(cm, lineView);
  1935. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  1936. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  1937. lineView.text = built.pre;
  1938. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1939. lineView.bgClass = built.bgClass;
  1940. lineView.textClass = built.textClass;
  1941. updateLineClasses(cm, lineView);
  1942. } else if (cls) {
  1943. lineView.text.className = cls;
  1944. }
  1945. }
  1946. function updateLineClasses(cm, lineView) {
  1947. updateLineBackground(cm, lineView);
  1948. if (lineView.line.wrapClass)
  1949. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  1950. else if (lineView.node != lineView.text)
  1951. { lineView.node.className = ""; }
  1952. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  1953. lineView.text.className = textClass || "";
  1954. }
  1955. function updateLineGutter(cm, lineView, lineN, dims) {
  1956. if (lineView.gutter) {
  1957. lineView.node.removeChild(lineView.gutter);
  1958. lineView.gutter = null;
  1959. }
  1960. if (lineView.gutterBackground) {
  1961. lineView.node.removeChild(lineView.gutterBackground);
  1962. lineView.gutterBackground = null;
  1963. }
  1964. if (lineView.line.gutterClass) {
  1965. var wrap = ensureLineWrapped(lineView);
  1966. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1967. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  1968. cm.display.input.setUneditable(lineView.gutterBackground);
  1969. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  1970. }
  1971. var markers = lineView.line.gutterMarkers;
  1972. if (cm.options.lineNumbers || markers) {
  1973. var wrap$1 = ensureLineWrapped(lineView);
  1974. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  1975. cm.display.input.setUneditable(gutterWrap);
  1976. wrap$1.insertBefore(gutterWrap, lineView.text);
  1977. if (lineView.line.gutterClass)
  1978. { gutterWrap.className += " " + lineView.line.gutterClass; }
  1979. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  1980. { lineView.lineNumber = gutterWrap.appendChild(
  1981. elt("div", lineNumberFor(cm.options, lineN),
  1982. "CodeMirror-linenumber CodeMirror-gutter-elt",
  1983. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  1984. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  1985. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  1986. if (found)
  1987. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  1988. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  1989. } }
  1990. }
  1991. }
  1992. function updateLineWidgets(cm, lineView, dims) {
  1993. if (lineView.alignable) { lineView.alignable = null; }
  1994. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  1995. next = node.nextSibling;
  1996. if (node.className == "CodeMirror-linewidget")
  1997. { lineView.node.removeChild(node); }
  1998. }
  1999. insertLineWidgets(cm, lineView, dims);
  2000. }
  2001. // Build a line's DOM representation from scratch
  2002. function buildLineElement(cm, lineView, lineN, dims) {
  2003. var built = getLineContent(cm, lineView);
  2004. lineView.text = lineView.node = built.pre;
  2005. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2006. if (built.textClass) { lineView.textClass = built.textClass; }
  2007. updateLineClasses(cm, lineView);
  2008. updateLineGutter(cm, lineView, lineN, dims);
  2009. insertLineWidgets(cm, lineView, dims);
  2010. return lineView.node
  2011. }
  2012. // A lineView may contain multiple logical lines (when merged by
  2013. // collapsed spans). The widgets for all of them need to be drawn.
  2014. function insertLineWidgets(cm, lineView, dims) {
  2015. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2016. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2017. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2018. }
  2019. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2020. if (!line.widgets) { return }
  2021. var wrap = ensureLineWrapped(lineView);
  2022. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2023. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  2024. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2025. positionLineWidget(widget, node, lineView, dims);
  2026. cm.display.input.setUneditable(node);
  2027. if (allowAbove && widget.above)
  2028. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2029. else
  2030. { wrap.appendChild(node); }
  2031. signalLater(widget, "redraw");
  2032. }
  2033. }
  2034. function positionLineWidget(widget, node, lineView, dims) {
  2035. if (widget.noHScroll) {
  2036. (lineView.alignable || (lineView.alignable = [])).push(node);
  2037. var width = dims.wrapperWidth;
  2038. node.style.left = dims.fixedPos + "px";
  2039. if (!widget.coverGutter) {
  2040. width -= dims.gutterTotalWidth;
  2041. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2042. }
  2043. node.style.width = width + "px";
  2044. }
  2045. if (widget.coverGutter) {
  2046. node.style.zIndex = 5;
  2047. node.style.position = "relative";
  2048. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2049. }
  2050. }
  2051. function widgetHeight(widget) {
  2052. if (widget.height != null) { return widget.height }
  2053. var cm = widget.doc.cm;
  2054. if (!cm) { return 0 }
  2055. if (!contains(document.body, widget.node)) {
  2056. var parentStyle = "position: relative;";
  2057. if (widget.coverGutter)
  2058. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2059. if (widget.noHScroll)
  2060. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2061. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2062. }
  2063. return widget.height = widget.node.parentNode.offsetHeight
  2064. }
  2065. // Return true when the given mouse event happened in a widget
  2066. function eventInWidget(display, e) {
  2067. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2068. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2069. (n.parentNode == display.sizer && n != display.mover))
  2070. { return true }
  2071. }
  2072. }
  2073. // POSITION MEASUREMENT
  2074. function paddingTop(display) {return display.lineSpace.offsetTop}
  2075. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2076. function paddingH(display) {
  2077. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2078. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2079. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2080. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2081. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2082. return data
  2083. }
  2084. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2085. function displayWidth(cm) {
  2086. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2087. }
  2088. function displayHeight(cm) {
  2089. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2090. }
  2091. // Ensure the lineView.wrapping.heights array is populated. This is
  2092. // an array of bottom offsets for the lines that make up a drawn
  2093. // line. When lineWrapping is on, there might be more than one
  2094. // height.
  2095. function ensureLineHeights(cm, lineView, rect) {
  2096. var wrapping = cm.options.lineWrapping;
  2097. var curWidth = wrapping && displayWidth(cm);
  2098. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2099. var heights = lineView.measure.heights = [];
  2100. if (wrapping) {
  2101. lineView.measure.width = curWidth;
  2102. var rects = lineView.text.firstChild.getClientRects();
  2103. for (var i = 0; i < rects.length - 1; i++) {
  2104. var cur = rects[i], next = rects[i + 1];
  2105. if (Math.abs(cur.bottom - next.bottom) > 2)
  2106. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2107. }
  2108. }
  2109. heights.push(rect.bottom - rect.top);
  2110. }
  2111. }
  2112. // Find a line map (mapping character offsets to text nodes) and a
  2113. // measurement cache for the given line number. (A line view might
  2114. // contain multiple lines when collapsed ranges are present.)
  2115. function mapFromLineView(lineView, line, lineN) {
  2116. if (lineView.line == line)
  2117. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2118. for (var i = 0; i < lineView.rest.length; i++)
  2119. { if (lineView.rest[i] == line)
  2120. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2121. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2122. { if (lineNo(lineView.rest[i$1]) > lineN)
  2123. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2124. }
  2125. // Render a line into the hidden node display.externalMeasured. Used
  2126. // when measurement is needed for a line that's not in the viewport.
  2127. function updateExternalMeasurement(cm, line) {
  2128. line = visualLine(line);
  2129. var lineN = lineNo(line);
  2130. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2131. view.lineN = lineN;
  2132. var built = view.built = buildLineContent(cm, view);
  2133. view.text = built.pre;
  2134. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2135. return view
  2136. }
  2137. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2138. // for a given character.
  2139. function measureChar(cm, line, ch, bias) {
  2140. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2141. }
  2142. // Find a line view that corresponds to the given line number.
  2143. function findViewForLine(cm, lineN) {
  2144. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2145. { return cm.display.view[findViewIndex(cm, lineN)] }
  2146. var ext = cm.display.externalMeasured;
  2147. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2148. { return ext }
  2149. }
  2150. // Measurement can be split in two steps, the set-up work that
  2151. // applies to the whole line, and the measurement of the actual
  2152. // character. Functions like coordsChar, that need to do a lot of
  2153. // measurements in a row, can thus ensure that the set-up work is
  2154. // only done once.
  2155. function prepareMeasureForLine(cm, line) {
  2156. var lineN = lineNo(line);
  2157. var view = findViewForLine(cm, lineN);
  2158. if (view && !view.text) {
  2159. view = null;
  2160. } else if (view && view.changes) {
  2161. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2162. cm.curOp.forceUpdate = true;
  2163. }
  2164. if (!view)
  2165. { view = updateExternalMeasurement(cm, line); }
  2166. var info = mapFromLineView(view, line, lineN);
  2167. return {
  2168. line: line, view: view, rect: null,
  2169. map: info.map, cache: info.cache, before: info.before,
  2170. hasHeights: false
  2171. }
  2172. }
  2173. // Given a prepared measurement object, measures the position of an
  2174. // actual character (or fetches it from the cache).
  2175. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2176. if (prepared.before) { ch = -1; }
  2177. var key = ch + (bias || ""), found;
  2178. if (prepared.cache.hasOwnProperty(key)) {
  2179. found = prepared.cache[key];
  2180. } else {
  2181. if (!prepared.rect)
  2182. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2183. if (!prepared.hasHeights) {
  2184. ensureLineHeights(cm, prepared.view, prepared.rect);
  2185. prepared.hasHeights = true;
  2186. }
  2187. found = measureCharInner(cm, prepared, ch, bias);
  2188. if (!found.bogus) { prepared.cache[key] = found; }
  2189. }
  2190. return {left: found.left, right: found.right,
  2191. top: varHeight ? found.rtop : found.top,
  2192. bottom: varHeight ? found.rbottom : found.bottom}
  2193. }
  2194. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2195. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  2196. var node, start, end, collapse, mStart, mEnd;
  2197. // First, search the line map for the text node corresponding to,
  2198. // or closest to, the target character.
  2199. for (var i = 0; i < map$$1.length; i += 3) {
  2200. mStart = map$$1[i];
  2201. mEnd = map$$1[i + 1];
  2202. if (ch < mStart) {
  2203. start = 0; end = 1;
  2204. collapse = "left";
  2205. } else if (ch < mEnd) {
  2206. start = ch - mStart;
  2207. end = start + 1;
  2208. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  2209. end = mEnd - mStart;
  2210. start = end - 1;
  2211. if (ch >= mEnd) { collapse = "right"; }
  2212. }
  2213. if (start != null) {
  2214. node = map$$1[i + 2];
  2215. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2216. { collapse = bias; }
  2217. if (bias == "left" && start == 0)
  2218. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  2219. node = map$$1[(i -= 3) + 2];
  2220. collapse = "left";
  2221. } }
  2222. if (bias == "right" && start == mEnd - mStart)
  2223. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  2224. node = map$$1[(i += 3) + 2];
  2225. collapse = "right";
  2226. } }
  2227. break
  2228. }
  2229. }
  2230. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2231. }
  2232. function getUsefulRect(rects, bias) {
  2233. var rect = nullRect;
  2234. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2235. if ((rect = rects[i]).left != rect.right) { break }
  2236. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2237. if ((rect = rects[i$1]).left != rect.right) { break }
  2238. } }
  2239. return rect
  2240. }
  2241. function measureCharInner(cm, prepared, ch, bias) {
  2242. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2243. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2244. var rect;
  2245. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2246. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2247. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2248. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2249. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2250. { rect = node.parentNode.getBoundingClientRect(); }
  2251. else
  2252. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2253. if (rect.left || rect.right || start == 0) { break }
  2254. end = start;
  2255. start = start - 1;
  2256. collapse = "right";
  2257. }
  2258. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2259. } else { // If it is a widget, simply get the box for the whole widget.
  2260. if (start > 0) { collapse = bias = "right"; }
  2261. var rects;
  2262. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2263. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2264. else
  2265. { rect = node.getBoundingClientRect(); }
  2266. }
  2267. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2268. var rSpan = node.parentNode.getClientRects()[0];
  2269. if (rSpan)
  2270. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2271. else
  2272. { rect = nullRect; }
  2273. }
  2274. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2275. var mid = (rtop + rbot) / 2;
  2276. var heights = prepared.view.measure.heights;
  2277. var i = 0;
  2278. for (; i < heights.length - 1; i++)
  2279. { if (mid < heights[i]) { break } }
  2280. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2281. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2282. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2283. top: top, bottom: bot};
  2284. if (!rect.left && !rect.right) { result.bogus = true; }
  2285. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2286. return result
  2287. }
  2288. // Work around problem with bounding client rects on ranges being
  2289. // returned incorrectly when zoomed on IE10 and below.
  2290. function maybeUpdateRectForZooming(measure, rect) {
  2291. if (!window.screen || screen.logicalXDPI == null ||
  2292. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2293. { return rect }
  2294. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2295. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2296. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2297. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2298. }
  2299. function clearLineMeasurementCacheFor(lineView) {
  2300. if (lineView.measure) {
  2301. lineView.measure.cache = {};
  2302. lineView.measure.heights = null;
  2303. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2304. { lineView.measure.caches[i] = {}; } }
  2305. }
  2306. }
  2307. function clearLineMeasurementCache(cm) {
  2308. cm.display.externalMeasure = null;
  2309. removeChildren(cm.display.lineMeasure);
  2310. for (var i = 0; i < cm.display.view.length; i++)
  2311. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2312. }
  2313. function clearCaches(cm) {
  2314. clearLineMeasurementCache(cm);
  2315. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2316. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2317. cm.display.lineNumChars = null;
  2318. }
  2319. function pageScrollX() {
  2320. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2321. // which causes page_Offset and bounding client rects to use
  2322. // different reference viewports and invalidate our calculations.
  2323. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2324. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2325. }
  2326. function pageScrollY() {
  2327. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2328. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2329. }
  2330. function widgetTopHeight(lineObj) {
  2331. var height = 0;
  2332. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2333. { height += widgetHeight(lineObj.widgets[i]); } } }
  2334. return height
  2335. }
  2336. // Converts a {top, bottom, left, right} box from line-local
  2337. // coordinates into another coordinate system. Context may be one of
  2338. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2339. // or "page".
  2340. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2341. if (!includeWidgets) {
  2342. var height = widgetTopHeight(lineObj);
  2343. rect.top += height; rect.bottom += height;
  2344. }
  2345. if (context == "line") { return rect }
  2346. if (!context) { context = "local"; }
  2347. var yOff = heightAtLine(lineObj);
  2348. if (context == "local") { yOff += paddingTop(cm.display); }
  2349. else { yOff -= cm.display.viewOffset; }
  2350. if (context == "page" || context == "window") {
  2351. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2352. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2353. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2354. rect.left += xOff; rect.right += xOff;
  2355. }
  2356. rect.top += yOff; rect.bottom += yOff;
  2357. return rect
  2358. }
  2359. // Coverts a box from "div" coords to another coordinate system.
  2360. // Context may be "window", "page", "div", or "local"./null.
  2361. function fromCoordSystem(cm, coords, context) {
  2362. if (context == "div") { return coords }
  2363. var left = coords.left, top = coords.top;
  2364. // First move into "page" coordinate system
  2365. if (context == "page") {
  2366. left -= pageScrollX();
  2367. top -= pageScrollY();
  2368. } else if (context == "local" || !context) {
  2369. var localBox = cm.display.sizer.getBoundingClientRect();
  2370. left += localBox.left;
  2371. top += localBox.top;
  2372. }
  2373. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2374. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2375. }
  2376. function charCoords(cm, pos, context, lineObj, bias) {
  2377. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2378. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2379. }
  2380. // Returns a box for a given cursor position, which may have an
  2381. // 'other' property containing the position of the secondary cursor
  2382. // on a bidi boundary.
  2383. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2384. // and after `char - 1` in writing order of `char - 1`
  2385. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2386. // and before `char` in writing order of `char`
  2387. // Examples (upper-case letters are RTL, lower-case are LTR):
  2388. // Pos(0, 1, ...)
  2389. // before after
  2390. // ab a|b a|b
  2391. // aB a|B aB|
  2392. // Ab |Ab A|b
  2393. // AB B|A B|A
  2394. // Every position after the last character on a line is considered to stick
  2395. // to the last character on the line.
  2396. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2397. lineObj = lineObj || getLine(cm.doc, pos.line);
  2398. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2399. function get(ch, right) {
  2400. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2401. if (right) { m.left = m.right; } else { m.right = m.left; }
  2402. return intoCoordSystem(cm, lineObj, m, context)
  2403. }
  2404. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2405. if (ch >= lineObj.text.length) {
  2406. ch = lineObj.text.length;
  2407. sticky = "before";
  2408. } else if (ch <= 0) {
  2409. ch = 0;
  2410. sticky = "after";
  2411. }
  2412. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2413. function getBidi(ch, partPos, invert) {
  2414. var part = order[partPos], right = part.level == 1;
  2415. return get(invert ? ch - 1 : ch, right != invert)
  2416. }
  2417. var partPos = getBidiPartAt(order, ch, sticky);
  2418. var other = bidiOther;
  2419. var val = getBidi(ch, partPos, sticky == "before");
  2420. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2421. return val
  2422. }
  2423. // Used to cheaply estimate the coordinates for a position. Used for
  2424. // intermediate scroll updates.
  2425. function estimateCoords(cm, pos) {
  2426. var left = 0;
  2427. pos = clipPos(cm.doc, pos);
  2428. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2429. var lineObj = getLine(cm.doc, pos.line);
  2430. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2431. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2432. }
  2433. // Positions returned by coordsChar contain some extra information.
  2434. // xRel is the relative x position of the input coordinates compared
  2435. // to the found position (so xRel > 0 means the coordinates are to
  2436. // the right of the character position, for example). When outside
  2437. // is true, that means the coordinates lie outside the line's
  2438. // vertical range.
  2439. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2440. var pos = Pos(line, ch, sticky);
  2441. pos.xRel = xRel;
  2442. if (outside) { pos.outside = true; }
  2443. return pos
  2444. }
  2445. // Compute the character position closest to the given coordinates.
  2446. // Input must be lineSpace-local ("div" coordinate system).
  2447. function coordsChar(cm, x, y) {
  2448. var doc = cm.doc;
  2449. y += cm.display.viewOffset;
  2450. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2451. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2452. if (lineN > last)
  2453. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2454. if (x < 0) { x = 0; }
  2455. var lineObj = getLine(doc, lineN);
  2456. for (;;) {
  2457. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2458. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));
  2459. if (!collapsed) { return found }
  2460. var rangeEnd = collapsed.find(1);
  2461. if (rangeEnd.line == lineN) { return rangeEnd }
  2462. lineObj = getLine(doc, lineN = rangeEnd.line);
  2463. }
  2464. }
  2465. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2466. y -= widgetTopHeight(lineObj);
  2467. var end = lineObj.text.length;
  2468. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2469. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2470. return {begin: begin, end: end}
  2471. }
  2472. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2473. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2474. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2475. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2476. }
  2477. // Returns true if the given side of a box is after the given
  2478. // coordinates, in top-to-bottom, left-to-right order.
  2479. function boxIsAfter(box, x, y, left) {
  2480. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2481. }
  2482. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  2483. // Move y into line-local coordinate space
  2484. y -= heightAtLine(lineObj);
  2485. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2486. // When directly calling `measureCharPrepared`, we have to adjust
  2487. // for the widgets at this line.
  2488. var widgetHeight$$1 = widgetTopHeight(lineObj);
  2489. var begin = 0, end = lineObj.text.length, ltr = true;
  2490. var order = getOrder(lineObj, cm.doc.direction);
  2491. // If the line isn't plain left-to-right text, first figure out
  2492. // which bidi section the coordinates fall into.
  2493. if (order) {
  2494. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2495. (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
  2496. ltr = part.level != 1;
  2497. // The awkward -1 offsets are needed because findFirst (called
  2498. // on these below) will treat its first bound as inclusive,
  2499. // second as exclusive, but we want to actually address the
  2500. // characters in the part's range
  2501. begin = ltr ? part.from : part.to - 1;
  2502. end = ltr ? part.to : part.from - 1;
  2503. }
  2504. // A binary search to find the first character whose bounding box
  2505. // starts after the coordinates. If we run across any whose box wrap
  2506. // the coordinates, store that.
  2507. var chAround = null, boxAround = null;
  2508. var ch = findFirst(function (ch) {
  2509. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2510. box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
  2511. if (!boxIsAfter(box, x, y, false)) { return false }
  2512. if (box.top <= y && box.left <= x) {
  2513. chAround = ch;
  2514. boxAround = box;
  2515. }
  2516. return true
  2517. }, begin, end);
  2518. var baseX, sticky, outside = false;
  2519. // If a box around the coordinates was found, use that
  2520. if (boxAround) {
  2521. // Distinguish coordinates nearer to the left or right side of the box
  2522. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2523. ch = chAround + (atStart ? 0 : 1);
  2524. sticky = atStart ? "after" : "before";
  2525. baseX = atLeft ? boxAround.left : boxAround.right;
  2526. } else {
  2527. // (Adjust for extended bound, if necessary.)
  2528. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2529. // To determine which side to associate with, get the box to the
  2530. // left of the character and compare it's vertical position to the
  2531. // coordinates
  2532. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2533. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
  2534. "after" : "before";
  2535. // Now get accurate coordinates for this place, in order to get a
  2536. // base X position
  2537. var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
  2538. baseX = coords.left;
  2539. outside = y < coords.top || y >= coords.bottom;
  2540. }
  2541. ch = skipExtendingChars(lineObj.text, ch, 1);
  2542. return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
  2543. }
  2544. function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  2545. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2546. // situation, we can take this ordering to correspond to the visual
  2547. // ordering. This finds the first part whose end is after the given
  2548. // coordinates.
  2549. var index = findFirst(function (i) {
  2550. var part = order[i], ltr = part.level != 1;
  2551. return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2552. "line", lineObj, preparedMeasure), x, y, true)
  2553. }, 0, order.length - 1);
  2554. var part = order[index];
  2555. // If this isn't the first part, the part's start is also after
  2556. // the coordinates, and the coordinates aren't on the same line as
  2557. // that start, move one part back.
  2558. if (index > 0) {
  2559. var ltr = part.level != 1;
  2560. var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2561. "line", lineObj, preparedMeasure);
  2562. if (boxIsAfter(start, x, y, true) && start.top > y)
  2563. { part = order[index - 1]; }
  2564. }
  2565. return part
  2566. }
  2567. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2568. // In a wrapped line, rtl text on wrapping boundaries can do things
  2569. // that don't correspond to the ordering in our `order` array at
  2570. // all, so a binary search doesn't work, and we want to return a
  2571. // part that only spans one line so that the binary search in
  2572. // coordsCharInner is safe. As such, we first find the extent of the
  2573. // wrapped line, and then do a flat search in which we discard any
  2574. // spans that aren't on the line.
  2575. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2576. var begin = ref.begin;
  2577. var end = ref.end;
  2578. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2579. var part = null, closestDist = null;
  2580. for (var i = 0; i < order.length; i++) {
  2581. var p = order[i];
  2582. if (p.from >= end || p.to <= begin) { continue }
  2583. var ltr = p.level != 1;
  2584. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2585. // Weigh against spans ending before this, so that they are only
  2586. // picked if nothing ends after
  2587. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2588. if (!part || closestDist > dist) {
  2589. part = p;
  2590. closestDist = dist;
  2591. }
  2592. }
  2593. if (!part) { part = order[order.length - 1]; }
  2594. // Clip the part to the wrapped line.
  2595. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2596. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2597. return part
  2598. }
  2599. var measureText;
  2600. // Compute the default text height.
  2601. function textHeight(display) {
  2602. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2603. if (measureText == null) {
  2604. measureText = elt("pre");
  2605. // Measure a bunch of lines, for browsers that compute
  2606. // fractional heights.
  2607. for (var i = 0; i < 49; ++i) {
  2608. measureText.appendChild(document.createTextNode("x"));
  2609. measureText.appendChild(elt("br"));
  2610. }
  2611. measureText.appendChild(document.createTextNode("x"));
  2612. }
  2613. removeChildrenAndAdd(display.measure, measureText);
  2614. var height = measureText.offsetHeight / 50;
  2615. if (height > 3) { display.cachedTextHeight = height; }
  2616. removeChildren(display.measure);
  2617. return height || 1
  2618. }
  2619. // Compute the default character width.
  2620. function charWidth(display) {
  2621. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2622. var anchor = elt("span", "xxxxxxxxxx");
  2623. var pre = elt("pre", [anchor]);
  2624. removeChildrenAndAdd(display.measure, pre);
  2625. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2626. if (width > 2) { display.cachedCharWidth = width; }
  2627. return width || 10
  2628. }
  2629. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2630. // view, so that we don't interleave reading and writing to the DOM.
  2631. function getDimensions(cm) {
  2632. var d = cm.display, left = {}, width = {};
  2633. var gutterLeft = d.gutters.clientLeft;
  2634. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2635. var id = cm.display.gutterSpecs[i].className;
  2636. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2637. width[id] = n.clientWidth;
  2638. }
  2639. return {fixedPos: compensateForHScroll(d),
  2640. gutterTotalWidth: d.gutters.offsetWidth,
  2641. gutterLeft: left,
  2642. gutterWidth: width,
  2643. wrapperWidth: d.wrapper.clientWidth}
  2644. }
  2645. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2646. // but using getBoundingClientRect to get a sub-pixel-accurate
  2647. // result.
  2648. function compensateForHScroll(display) {
  2649. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2650. }
  2651. // Returns a function that estimates the height of a line, to use as
  2652. // first approximation until the line becomes visible (and is thus
  2653. // properly measurable).
  2654. function estimateHeight(cm) {
  2655. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2656. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2657. return function (line) {
  2658. if (lineIsHidden(cm.doc, line)) { return 0 }
  2659. var widgetsHeight = 0;
  2660. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2661. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2662. } }
  2663. if (wrapping)
  2664. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2665. else
  2666. { return widgetsHeight + th }
  2667. }
  2668. }
  2669. function estimateLineHeights(cm) {
  2670. var doc = cm.doc, est = estimateHeight(cm);
  2671. doc.iter(function (line) {
  2672. var estHeight = est(line);
  2673. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2674. });
  2675. }
  2676. // Given a mouse event, find the corresponding position. If liberal
  2677. // is false, it checks whether a gutter or scrollbar was clicked,
  2678. // and returns null if it was. forRect is used by rectangular
  2679. // selections, and tries to estimate a character position even for
  2680. // coordinates beyond the right of the text.
  2681. function posFromMouse(cm, e, liberal, forRect) {
  2682. var display = cm.display;
  2683. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2684. var x, y, space = display.lineSpace.getBoundingClientRect();
  2685. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2686. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2687. catch (e) { return null }
  2688. var coords = coordsChar(cm, x, y), line;
  2689. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2690. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2691. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2692. }
  2693. return coords
  2694. }
  2695. // Find the view element corresponding to a given line. Return null
  2696. // when the line isn't visible.
  2697. function findViewIndex(cm, n) {
  2698. if (n >= cm.display.viewTo) { return null }
  2699. n -= cm.display.viewFrom;
  2700. if (n < 0) { return null }
  2701. var view = cm.display.view;
  2702. for (var i = 0; i < view.length; i++) {
  2703. n -= view[i].size;
  2704. if (n < 0) { return i }
  2705. }
  2706. }
  2707. // Updates the display.view data structure for a given change to the
  2708. // document. From and to are in pre-change coordinates. Lendiff is
  2709. // the amount of lines added or subtracted by the change. This is
  2710. // used for changes that span multiple lines, or change the way
  2711. // lines are divided into visual lines. regLineChange (below)
  2712. // registers single-line changes.
  2713. function regChange(cm, from, to, lendiff) {
  2714. if (from == null) { from = cm.doc.first; }
  2715. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2716. if (!lendiff) { lendiff = 0; }
  2717. var display = cm.display;
  2718. if (lendiff && to < display.viewTo &&
  2719. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2720. { display.updateLineNumbers = from; }
  2721. cm.curOp.viewChanged = true;
  2722. if (from >= display.viewTo) { // Change after
  2723. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2724. { resetView(cm); }
  2725. } else if (to <= display.viewFrom) { // Change before
  2726. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2727. resetView(cm);
  2728. } else {
  2729. display.viewFrom += lendiff;
  2730. display.viewTo += lendiff;
  2731. }
  2732. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2733. resetView(cm);
  2734. } else if (from <= display.viewFrom) { // Top overlap
  2735. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2736. if (cut) {
  2737. display.view = display.view.slice(cut.index);
  2738. display.viewFrom = cut.lineN;
  2739. display.viewTo += lendiff;
  2740. } else {
  2741. resetView(cm);
  2742. }
  2743. } else if (to >= display.viewTo) { // Bottom overlap
  2744. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2745. if (cut$1) {
  2746. display.view = display.view.slice(0, cut$1.index);
  2747. display.viewTo = cut$1.lineN;
  2748. } else {
  2749. resetView(cm);
  2750. }
  2751. } else { // Gap in the middle
  2752. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2753. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2754. if (cutTop && cutBot) {
  2755. display.view = display.view.slice(0, cutTop.index)
  2756. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2757. .concat(display.view.slice(cutBot.index));
  2758. display.viewTo += lendiff;
  2759. } else {
  2760. resetView(cm);
  2761. }
  2762. }
  2763. var ext = display.externalMeasured;
  2764. if (ext) {
  2765. if (to < ext.lineN)
  2766. { ext.lineN += lendiff; }
  2767. else if (from < ext.lineN + ext.size)
  2768. { display.externalMeasured = null; }
  2769. }
  2770. }
  2771. // Register a change to a single line. Type must be one of "text",
  2772. // "gutter", "class", "widget"
  2773. function regLineChange(cm, line, type) {
  2774. cm.curOp.viewChanged = true;
  2775. var display = cm.display, ext = cm.display.externalMeasured;
  2776. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2777. { display.externalMeasured = null; }
  2778. if (line < display.viewFrom || line >= display.viewTo) { return }
  2779. var lineView = display.view[findViewIndex(cm, line)];
  2780. if (lineView.node == null) { return }
  2781. var arr = lineView.changes || (lineView.changes = []);
  2782. if (indexOf(arr, type) == -1) { arr.push(type); }
  2783. }
  2784. // Clear the view.
  2785. function resetView(cm) {
  2786. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2787. cm.display.view = [];
  2788. cm.display.viewOffset = 0;
  2789. }
  2790. function viewCuttingPoint(cm, oldN, newN, dir) {
  2791. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2792. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2793. { return {index: index, lineN: newN} }
  2794. var n = cm.display.viewFrom;
  2795. for (var i = 0; i < index; i++)
  2796. { n += view[i].size; }
  2797. if (n != oldN) {
  2798. if (dir > 0) {
  2799. if (index == view.length - 1) { return null }
  2800. diff = (n + view[index].size) - oldN;
  2801. index++;
  2802. } else {
  2803. diff = n - oldN;
  2804. }
  2805. oldN += diff; newN += diff;
  2806. }
  2807. while (visualLineNo(cm.doc, newN) != newN) {
  2808. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2809. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2810. index += dir;
  2811. }
  2812. return {index: index, lineN: newN}
  2813. }
  2814. // Force the view to cover a given range, adding empty view element
  2815. // or clipping off existing ones as needed.
  2816. function adjustView(cm, from, to) {
  2817. var display = cm.display, view = display.view;
  2818. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2819. display.view = buildViewArray(cm, from, to);
  2820. display.viewFrom = from;
  2821. } else {
  2822. if (display.viewFrom > from)
  2823. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2824. else if (display.viewFrom < from)
  2825. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2826. display.viewFrom = from;
  2827. if (display.viewTo < to)
  2828. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2829. else if (display.viewTo > to)
  2830. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2831. }
  2832. display.viewTo = to;
  2833. }
  2834. // Count the number of lines in the view whose DOM representation is
  2835. // out of date (or nonexistent).
  2836. function countDirtyView(cm) {
  2837. var view = cm.display.view, dirty = 0;
  2838. for (var i = 0; i < view.length; i++) {
  2839. var lineView = view[i];
  2840. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2841. }
  2842. return dirty
  2843. }
  2844. function updateSelection(cm) {
  2845. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2846. }
  2847. function prepareSelection(cm, primary) {
  2848. if ( primary === void 0 ) primary = true;
  2849. var doc = cm.doc, result = {};
  2850. var curFragment = result.cursors = document.createDocumentFragment();
  2851. var selFragment = result.selection = document.createDocumentFragment();
  2852. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2853. if (!primary && i == doc.sel.primIndex) { continue }
  2854. var range$$1 = doc.sel.ranges[i];
  2855. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  2856. var collapsed = range$$1.empty();
  2857. if (collapsed || cm.options.showCursorWhenSelecting)
  2858. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  2859. if (!collapsed)
  2860. { drawSelectionRange(cm, range$$1, selFragment); }
  2861. }
  2862. return result
  2863. }
  2864. // Draws a cursor for the given range
  2865. function drawSelectionCursor(cm, head, output) {
  2866. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2867. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2868. cursor.style.left = pos.left + "px";
  2869. cursor.style.top = pos.top + "px";
  2870. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2871. if (pos.other) {
  2872. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2873. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2874. otherCursor.style.display = "";
  2875. otherCursor.style.left = pos.other.left + "px";
  2876. otherCursor.style.top = pos.other.top + "px";
  2877. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2878. }
  2879. }
  2880. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2881. // Draws the given range as a highlighted selection
  2882. function drawSelectionRange(cm, range$$1, output) {
  2883. var display = cm.display, doc = cm.doc;
  2884. var fragment = document.createDocumentFragment();
  2885. var padding = paddingH(cm.display), leftSide = padding.left;
  2886. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2887. var docLTR = doc.direction == "ltr";
  2888. function add(left, top, width, bottom) {
  2889. if (top < 0) { top = 0; }
  2890. top = Math.round(top);
  2891. bottom = Math.round(bottom);
  2892. 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")));
  2893. }
  2894. function drawForLine(line, fromArg, toArg) {
  2895. var lineObj = getLine(doc, line);
  2896. var lineLen = lineObj.text.length;
  2897. var start, end;
  2898. function coords(ch, bias) {
  2899. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2900. }
  2901. function wrapX(pos, dir, side) {
  2902. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2903. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2904. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2905. return coords(ch, prop)[prop]
  2906. }
  2907. var order = getOrder(lineObj, doc.direction);
  2908. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2909. var ltr = dir == "ltr";
  2910. var fromPos = coords(from, ltr ? "left" : "right");
  2911. var toPos = coords(to - 1, ltr ? "right" : "left");
  2912. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2913. var first = i == 0, last = !order || i == order.length - 1;
  2914. if (toPos.top - fromPos.top <= 3) { // Single line
  2915. var openLeft = (docLTR ? openStart : openEnd) && first;
  2916. var openRight = (docLTR ? openEnd : openStart) && last;
  2917. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2918. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2919. add(left, fromPos.top, right - left, fromPos.bottom);
  2920. } else { // Multiple lines
  2921. var topLeft, topRight, botLeft, botRight;
  2922. if (ltr) {
  2923. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2924. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2925. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2926. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2927. } else {
  2928. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2929. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2930. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2931. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2932. }
  2933. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2934. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2935. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2936. }
  2937. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2938. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2939. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2940. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2941. });
  2942. return {start: start, end: end}
  2943. }
  2944. var sFrom = range$$1.from(), sTo = range$$1.to();
  2945. if (sFrom.line == sTo.line) {
  2946. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2947. } else {
  2948. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2949. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2950. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2951. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2952. if (singleVLine) {
  2953. if (leftEnd.top < rightStart.top - 2) {
  2954. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2955. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2956. } else {
  2957. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2958. }
  2959. }
  2960. if (leftEnd.bottom < rightStart.top)
  2961. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  2962. }
  2963. output.appendChild(fragment);
  2964. }
  2965. // Cursor-blinking
  2966. function restartBlink(cm) {
  2967. if (!cm.state.focused) { return }
  2968. var display = cm.display;
  2969. clearInterval(display.blinker);
  2970. var on = true;
  2971. display.cursorDiv.style.visibility = "";
  2972. if (cm.options.cursorBlinkRate > 0)
  2973. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2974. cm.options.cursorBlinkRate); }
  2975. else if (cm.options.cursorBlinkRate < 0)
  2976. { display.cursorDiv.style.visibility = "hidden"; }
  2977. }
  2978. function ensureFocus(cm) {
  2979. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  2980. }
  2981. function delayBlurEvent(cm) {
  2982. cm.state.delayingBlurEvent = true;
  2983. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2984. cm.state.delayingBlurEvent = false;
  2985. onBlur(cm);
  2986. } }, 100);
  2987. }
  2988. function onFocus(cm, e) {
  2989. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  2990. if (cm.options.readOnly == "nocursor") { return }
  2991. if (!cm.state.focused) {
  2992. signal(cm, "focus", cm, e);
  2993. cm.state.focused = true;
  2994. addClass(cm.display.wrapper, "CodeMirror-focused");
  2995. // This test prevents this from firing when a context
  2996. // menu is closed (since the input reset would kill the
  2997. // select-all detection hack)
  2998. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2999. cm.display.input.reset();
  3000. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3001. }
  3002. cm.display.input.receivedFocus();
  3003. }
  3004. restartBlink(cm);
  3005. }
  3006. function onBlur(cm, e) {
  3007. if (cm.state.delayingBlurEvent) { return }
  3008. if (cm.state.focused) {
  3009. signal(cm, "blur", cm, e);
  3010. cm.state.focused = false;
  3011. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3012. }
  3013. clearInterval(cm.display.blinker);
  3014. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3015. }
  3016. // Read the actual heights of the rendered lines, and update their
  3017. // stored heights to match.
  3018. function updateHeightsInViewport(cm) {
  3019. var display = cm.display;
  3020. var prevBottom = display.lineDiv.offsetTop;
  3021. for (var i = 0; i < display.view.length; i++) {
  3022. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3023. var height = (void 0), width = 0;
  3024. if (cur.hidden) { continue }
  3025. if (ie && ie_version < 8) {
  3026. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3027. height = bot - prevBottom;
  3028. prevBottom = bot;
  3029. } else {
  3030. var box = cur.node.getBoundingClientRect();
  3031. height = box.bottom - box.top;
  3032. // Check that lines don't extend past the right of the current
  3033. // editor width
  3034. if (!wrapping && cur.text.firstChild)
  3035. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3036. }
  3037. var diff = cur.line.height - height;
  3038. if (diff > .005 || diff < -.005) {
  3039. updateLineHeight(cur.line, height);
  3040. updateWidgetHeight(cur.line);
  3041. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3042. { updateWidgetHeight(cur.rest[j]); } }
  3043. }
  3044. if (width > cm.display.sizerWidth) {
  3045. var chWidth = Math.ceil(width / charWidth(cm.display));
  3046. if (chWidth > cm.display.maxLineLength) {
  3047. cm.display.maxLineLength = chWidth;
  3048. cm.display.maxLine = cur.line;
  3049. cm.display.maxLineChanged = true;
  3050. }
  3051. }
  3052. }
  3053. }
  3054. // Read and store the height of line widgets associated with the
  3055. // given line.
  3056. function updateWidgetHeight(line) {
  3057. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3058. var w = line.widgets[i], parent = w.node.parentNode;
  3059. if (parent) { w.height = parent.offsetHeight; }
  3060. } }
  3061. }
  3062. // Compute the lines that are visible in a given viewport (defaults
  3063. // the the current scroll position). viewport may contain top,
  3064. // height, and ensure (see op.scrollToPos) properties.
  3065. function visibleLines(display, doc, viewport) {
  3066. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3067. top = Math.floor(top - paddingTop(display));
  3068. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3069. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3070. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3071. // forces those lines into the viewport (if possible).
  3072. if (viewport && viewport.ensure) {
  3073. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3074. if (ensureFrom < from) {
  3075. from = ensureFrom;
  3076. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3077. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3078. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3079. to = ensureTo;
  3080. }
  3081. }
  3082. return {from: from, to: Math.max(to, from + 1)}
  3083. }
  3084. // SCROLLING THINGS INTO VIEW
  3085. // If an editor sits on the top or bottom of the window, partially
  3086. // scrolled out of view, this ensures that the cursor is visible.
  3087. function maybeScrollWindow(cm, rect) {
  3088. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3089. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3090. if (rect.top + box.top < 0) { doScroll = true; }
  3091. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3092. if (doScroll != null && !phantom) {
  3093. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
  3094. cm.display.lineSpace.appendChild(scrollNode);
  3095. scrollNode.scrollIntoView(doScroll);
  3096. cm.display.lineSpace.removeChild(scrollNode);
  3097. }
  3098. }
  3099. // Scroll a given position into view (immediately), verifying that
  3100. // it actually became visible (as line heights are accurately
  3101. // measured, the position of something may 'drift' during drawing).
  3102. function scrollPosIntoView(cm, pos, end, margin) {
  3103. if (margin == null) { margin = 0; }
  3104. var rect;
  3105. if (!cm.options.lineWrapping && pos == end) {
  3106. // Set pos and end to the cursor positions around the character pos sticks to
  3107. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3108. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3109. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3110. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3111. }
  3112. for (var limit = 0; limit < 5; limit++) {
  3113. var changed = false;
  3114. var coords = cursorCoords(cm, pos);
  3115. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3116. rect = {left: Math.min(coords.left, endCoords.left),
  3117. top: Math.min(coords.top, endCoords.top) - margin,
  3118. right: Math.max(coords.left, endCoords.left),
  3119. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3120. var scrollPos = calculateScrollPos(cm, rect);
  3121. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3122. if (scrollPos.scrollTop != null) {
  3123. updateScrollTop(cm, scrollPos.scrollTop);
  3124. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3125. }
  3126. if (scrollPos.scrollLeft != null) {
  3127. setScrollLeft(cm, scrollPos.scrollLeft);
  3128. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3129. }
  3130. if (!changed) { break }
  3131. }
  3132. return rect
  3133. }
  3134. // Scroll a given set of coordinates into view (immediately).
  3135. function scrollIntoView(cm, rect) {
  3136. var scrollPos = calculateScrollPos(cm, rect);
  3137. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3138. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3139. }
  3140. // Calculate a new scroll position needed to scroll the given
  3141. // rectangle into view. Returns an object with scrollTop and
  3142. // scrollLeft properties. When these are undefined, the
  3143. // vertical/horizontal position does not need to be adjusted.
  3144. function calculateScrollPos(cm, rect) {
  3145. var display = cm.display, snapMargin = textHeight(cm.display);
  3146. if (rect.top < 0) { rect.top = 0; }
  3147. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3148. var screen = displayHeight(cm), result = {};
  3149. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3150. var docBottom = cm.doc.height + paddingVert(display);
  3151. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3152. if (rect.top < screentop) {
  3153. result.scrollTop = atTop ? 0 : rect.top;
  3154. } else if (rect.bottom > screentop + screen) {
  3155. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3156. if (newTop != screentop) { result.scrollTop = newTop; }
  3157. }
  3158. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  3159. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  3160. var tooWide = rect.right - rect.left > screenw;
  3161. if (tooWide) { rect.right = rect.left + screenw; }
  3162. if (rect.left < 10)
  3163. { result.scrollLeft = 0; }
  3164. else if (rect.left < screenleft)
  3165. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  3166. else if (rect.right > screenw + screenleft - 3)
  3167. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3168. return result
  3169. }
  3170. // Store a relative adjustment to the scroll position in the current
  3171. // operation (to be applied when the operation finishes).
  3172. function addToScrollTop(cm, top) {
  3173. if (top == null) { return }
  3174. resolveScrollToPos(cm);
  3175. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3176. }
  3177. // Make sure that at the end of the operation the current cursor is
  3178. // shown.
  3179. function ensureCursorVisible(cm) {
  3180. resolveScrollToPos(cm);
  3181. var cur = cm.getCursor();
  3182. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3183. }
  3184. function scrollToCoords(cm, x, y) {
  3185. if (x != null || y != null) { resolveScrollToPos(cm); }
  3186. if (x != null) { cm.curOp.scrollLeft = x; }
  3187. if (y != null) { cm.curOp.scrollTop = y; }
  3188. }
  3189. function scrollToRange(cm, range$$1) {
  3190. resolveScrollToPos(cm);
  3191. cm.curOp.scrollToPos = range$$1;
  3192. }
  3193. // When an operation has its scrollToPos property set, and another
  3194. // scroll action is applied before the end of the operation, this
  3195. // 'simulates' scrolling that position into view in a cheap way, so
  3196. // that the effect of intermediate scroll commands is not ignored.
  3197. function resolveScrollToPos(cm) {
  3198. var range$$1 = cm.curOp.scrollToPos;
  3199. if (range$$1) {
  3200. cm.curOp.scrollToPos = null;
  3201. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  3202. scrollToCoordsRange(cm, from, to, range$$1.margin);
  3203. }
  3204. }
  3205. function scrollToCoordsRange(cm, from, to, margin) {
  3206. var sPos = calculateScrollPos(cm, {
  3207. left: Math.min(from.left, to.left),
  3208. top: Math.min(from.top, to.top) - margin,
  3209. right: Math.max(from.right, to.right),
  3210. bottom: Math.max(from.bottom, to.bottom) + margin
  3211. });
  3212. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3213. }
  3214. // Sync the scrollable area and scrollbars, ensure the viewport
  3215. // covers the visible area.
  3216. function updateScrollTop(cm, val) {
  3217. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3218. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3219. setScrollTop(cm, val, true);
  3220. if (gecko) { updateDisplaySimple(cm); }
  3221. startWorker(cm, 100);
  3222. }
  3223. function setScrollTop(cm, val, forceScroll) {
  3224. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  3225. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3226. cm.doc.scrollTop = val;
  3227. cm.display.scrollbars.setScrollTop(val);
  3228. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3229. }
  3230. // Sync scroller and scrollbar, ensure the gutter elements are
  3231. // aligned.
  3232. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3233. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3234. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3235. cm.doc.scrollLeft = val;
  3236. alignHorizontally(cm);
  3237. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3238. cm.display.scrollbars.setScrollLeft(val);
  3239. }
  3240. // SCROLLBARS
  3241. // Prepare DOM reads needed to update the scrollbars. Done in one
  3242. // shot to minimize update/measure roundtrips.
  3243. function measureForScrollbars(cm) {
  3244. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3245. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3246. return {
  3247. clientHeight: d.scroller.clientHeight,
  3248. viewHeight: d.wrapper.clientHeight,
  3249. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3250. viewWidth: d.wrapper.clientWidth,
  3251. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3252. docHeight: docH,
  3253. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3254. nativeBarWidth: d.nativeBarWidth,
  3255. gutterWidth: gutterW
  3256. }
  3257. }
  3258. var NativeScrollbars = function(place, scroll, cm) {
  3259. this.cm = cm;
  3260. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3261. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3262. vert.tabIndex = horiz.tabIndex = -1;
  3263. place(vert); place(horiz);
  3264. on(vert, "scroll", function () {
  3265. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3266. });
  3267. on(horiz, "scroll", function () {
  3268. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3269. });
  3270. this.checkedZeroWidth = false;
  3271. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3272. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3273. };
  3274. NativeScrollbars.prototype.update = function (measure) {
  3275. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3276. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3277. var sWidth = measure.nativeBarWidth;
  3278. if (needsV) {
  3279. this.vert.style.display = "block";
  3280. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3281. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3282. // A bug in IE8 can cause this value to be negative, so guard it.
  3283. this.vert.firstChild.style.height =
  3284. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3285. } else {
  3286. this.vert.style.display = "";
  3287. this.vert.firstChild.style.height = "0";
  3288. }
  3289. if (needsH) {
  3290. this.horiz.style.display = "block";
  3291. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3292. this.horiz.style.left = measure.barLeft + "px";
  3293. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3294. this.horiz.firstChild.style.width =
  3295. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3296. } else {
  3297. this.horiz.style.display = "";
  3298. this.horiz.firstChild.style.width = "0";
  3299. }
  3300. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3301. if (sWidth == 0) { this.zeroWidthHack(); }
  3302. this.checkedZeroWidth = true;
  3303. }
  3304. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3305. };
  3306. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3307. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3308. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3309. };
  3310. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3311. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3312. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3313. };
  3314. NativeScrollbars.prototype.zeroWidthHack = function () {
  3315. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3316. this.horiz.style.height = this.vert.style.width = w;
  3317. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3318. this.disableHoriz = new Delayed;
  3319. this.disableVert = new Delayed;
  3320. };
  3321. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3322. bar.style.pointerEvents = "auto";
  3323. function maybeDisable() {
  3324. // To find out whether the scrollbar is still visible, we
  3325. // check whether the element under the pixel in the bottom
  3326. // right corner of the scrollbar box is the scrollbar box
  3327. // itself (when the bar is still visible) or its filler child
  3328. // (when the bar is hidden). If it is still visible, we keep
  3329. // it enabled, if it's hidden, we disable pointer events.
  3330. var box = bar.getBoundingClientRect();
  3331. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3332. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3333. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  3334. else { delay.set(1000, maybeDisable); }
  3335. }
  3336. delay.set(1000, maybeDisable);
  3337. };
  3338. NativeScrollbars.prototype.clear = function () {
  3339. var parent = this.horiz.parentNode;
  3340. parent.removeChild(this.horiz);
  3341. parent.removeChild(this.vert);
  3342. };
  3343. var NullScrollbars = function () {};
  3344. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3345. NullScrollbars.prototype.setScrollLeft = function () {};
  3346. NullScrollbars.prototype.setScrollTop = function () {};
  3347. NullScrollbars.prototype.clear = function () {};
  3348. function updateScrollbars(cm, measure) {
  3349. if (!measure) { measure = measureForScrollbars(cm); }
  3350. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3351. updateScrollbarsInner(cm, measure);
  3352. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3353. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3354. { updateHeightsInViewport(cm); }
  3355. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3356. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3357. }
  3358. }
  3359. // Re-synchronize the fake scrollbars with the actual size of the
  3360. // content.
  3361. function updateScrollbarsInner(cm, measure) {
  3362. var d = cm.display;
  3363. var sizes = d.scrollbars.update(measure);
  3364. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3365. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3366. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3367. if (sizes.right && sizes.bottom) {
  3368. d.scrollbarFiller.style.display = "block";
  3369. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3370. d.scrollbarFiller.style.width = sizes.right + "px";
  3371. } else { d.scrollbarFiller.style.display = ""; }
  3372. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3373. d.gutterFiller.style.display = "block";
  3374. d.gutterFiller.style.height = sizes.bottom + "px";
  3375. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3376. } else { d.gutterFiller.style.display = ""; }
  3377. }
  3378. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3379. function initScrollbars(cm) {
  3380. if (cm.display.scrollbars) {
  3381. cm.display.scrollbars.clear();
  3382. if (cm.display.scrollbars.addClass)
  3383. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3384. }
  3385. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3386. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3387. // Prevent clicks in the scrollbars from killing focus
  3388. on(node, "mousedown", function () {
  3389. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3390. });
  3391. node.setAttribute("cm-not-content", "true");
  3392. }, function (pos, axis) {
  3393. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3394. else { updateScrollTop(cm, pos); }
  3395. }, cm);
  3396. if (cm.display.scrollbars.addClass)
  3397. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3398. }
  3399. // Operations are used to wrap a series of changes to the editor
  3400. // state in such a way that each change won't have to update the
  3401. // cursor and display (which would be awkward, slow, and
  3402. // error-prone). Instead, display updates are batched and then all
  3403. // combined and executed at once.
  3404. var nextOpId = 0;
  3405. // Start a new operation.
  3406. function startOperation(cm) {
  3407. cm.curOp = {
  3408. cm: cm,
  3409. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3410. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3411. forceUpdate: false, // Used to force a redraw
  3412. updateInput: 0, // Whether to reset the input textarea
  3413. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3414. changeObjs: null, // Accumulated changes, for firing change events
  3415. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3416. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3417. selectionChanged: false, // Whether the selection needs to be redrawn
  3418. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3419. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3420. scrollToPos: null, // Used to scroll to a specific position
  3421. focus: false,
  3422. id: ++nextOpId // Unique ID
  3423. };
  3424. pushOperation(cm.curOp);
  3425. }
  3426. // Finish an operation, updating the display and signalling delayed events
  3427. function endOperation(cm) {
  3428. var op = cm.curOp;
  3429. if (op) { finishOperation(op, function (group) {
  3430. for (var i = 0; i < group.ops.length; i++)
  3431. { group.ops[i].cm.curOp = null; }
  3432. endOperations(group);
  3433. }); }
  3434. }
  3435. // The DOM updates done when an operation finishes are batched so
  3436. // that the minimum number of relayouts are required.
  3437. function endOperations(group) {
  3438. var ops = group.ops;
  3439. for (var i = 0; i < ops.length; i++) // Read DOM
  3440. { endOperation_R1(ops[i]); }
  3441. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3442. { endOperation_W1(ops[i$1]); }
  3443. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3444. { endOperation_R2(ops[i$2]); }
  3445. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3446. { endOperation_W2(ops[i$3]); }
  3447. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3448. { endOperation_finish(ops[i$4]); }
  3449. }
  3450. function endOperation_R1(op) {
  3451. var cm = op.cm, display = cm.display;
  3452. maybeClipScrollbars(cm);
  3453. if (op.updateMaxLine) { findMaxLine(cm); }
  3454. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3455. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3456. op.scrollToPos.to.line >= display.viewTo) ||
  3457. display.maxLineChanged && cm.options.lineWrapping;
  3458. op.update = op.mustUpdate &&
  3459. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3460. }
  3461. function endOperation_W1(op) {
  3462. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3463. }
  3464. function endOperation_R2(op) {
  3465. var cm = op.cm, display = cm.display;
  3466. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3467. op.barMeasure = measureForScrollbars(cm);
  3468. // If the max line changed since it was last measured, measure it,
  3469. // and ensure the document's width matches it.
  3470. // updateDisplay_W2 will use these properties to do the actual resizing
  3471. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3472. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3473. cm.display.sizerWidth = op.adjustWidthTo;
  3474. op.barMeasure.scrollWidth =
  3475. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3476. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3477. }
  3478. if (op.updatedDisplay || op.selectionChanged)
  3479. { op.preparedSelection = display.input.prepareSelection(); }
  3480. }
  3481. function endOperation_W2(op) {
  3482. var cm = op.cm;
  3483. if (op.adjustWidthTo != null) {
  3484. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3485. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3486. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3487. cm.display.maxLineChanged = false;
  3488. }
  3489. var takeFocus = op.focus && op.focus == activeElt();
  3490. if (op.preparedSelection)
  3491. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3492. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3493. { updateScrollbars(cm, op.barMeasure); }
  3494. if (op.updatedDisplay)
  3495. { setDocumentHeight(cm, op.barMeasure); }
  3496. if (op.selectionChanged) { restartBlink(cm); }
  3497. if (cm.state.focused && op.updateInput)
  3498. { cm.display.input.reset(op.typing); }
  3499. if (takeFocus) { ensureFocus(op.cm); }
  3500. }
  3501. function endOperation_finish(op) {
  3502. var cm = op.cm, display = cm.display, doc = cm.doc;
  3503. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3504. // Abort mouse wheel delta measurement, when scrolling explicitly
  3505. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3506. { display.wheelStartX = display.wheelStartY = null; }
  3507. // Propagate the scroll position to the actual DOM scroller
  3508. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3509. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3510. // If we need to scroll a specific position into view, do so.
  3511. if (op.scrollToPos) {
  3512. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3513. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3514. maybeScrollWindow(cm, rect);
  3515. }
  3516. // Fire events for markers that are hidden/unidden by editing or
  3517. // undoing
  3518. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3519. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3520. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3521. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3522. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3523. if (display.wrapper.offsetHeight)
  3524. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3525. // Fire change events, and delayed event handlers
  3526. if (op.changeObjs)
  3527. { signal(cm, "changes", cm, op.changeObjs); }
  3528. if (op.update)
  3529. { op.update.finish(); }
  3530. }
  3531. // Run the given function in an operation
  3532. function runInOp(cm, f) {
  3533. if (cm.curOp) { return f() }
  3534. startOperation(cm);
  3535. try { return f() }
  3536. finally { endOperation(cm); }
  3537. }
  3538. // Wraps a function in an operation. Returns the wrapped function.
  3539. function operation(cm, f) {
  3540. return function() {
  3541. if (cm.curOp) { return f.apply(cm, arguments) }
  3542. startOperation(cm);
  3543. try { return f.apply(cm, arguments) }
  3544. finally { endOperation(cm); }
  3545. }
  3546. }
  3547. // Used to add methods to editor and doc instances, wrapping them in
  3548. // operations.
  3549. function methodOp(f) {
  3550. return function() {
  3551. if (this.curOp) { return f.apply(this, arguments) }
  3552. startOperation(this);
  3553. try { return f.apply(this, arguments) }
  3554. finally { endOperation(this); }
  3555. }
  3556. }
  3557. function docMethodOp(f) {
  3558. return function() {
  3559. var cm = this.cm;
  3560. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3561. startOperation(cm);
  3562. try { return f.apply(this, arguments) }
  3563. finally { endOperation(cm); }
  3564. }
  3565. }
  3566. // HIGHLIGHT WORKER
  3567. function startWorker(cm, time) {
  3568. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3569. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3570. }
  3571. function highlightWorker(cm) {
  3572. var doc = cm.doc;
  3573. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3574. var end = +new Date + cm.options.workTime;
  3575. var context = getContextBefore(cm, doc.highlightFrontier);
  3576. var changedLines = [];
  3577. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3578. if (context.line >= cm.display.viewFrom) { // Visible
  3579. var oldStyles = line.styles;
  3580. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3581. var highlighted = highlightLine(cm, line, context, true);
  3582. if (resetState) { context.state = resetState; }
  3583. line.styles = highlighted.styles;
  3584. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3585. if (newCls) { line.styleClasses = newCls; }
  3586. else if (oldCls) { line.styleClasses = null; }
  3587. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3588. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3589. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3590. if (ischange) { changedLines.push(context.line); }
  3591. line.stateAfter = context.save();
  3592. context.nextLine();
  3593. } else {
  3594. if (line.text.length <= cm.options.maxHighlightLength)
  3595. { processLine(cm, line.text, context); }
  3596. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3597. context.nextLine();
  3598. }
  3599. if (+new Date > end) {
  3600. startWorker(cm, cm.options.workDelay);
  3601. return true
  3602. }
  3603. });
  3604. doc.highlightFrontier = context.line;
  3605. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3606. if (changedLines.length) { runInOp(cm, function () {
  3607. for (var i = 0; i < changedLines.length; i++)
  3608. { regLineChange(cm, changedLines[i], "text"); }
  3609. }); }
  3610. }
  3611. // DISPLAY DRAWING
  3612. var DisplayUpdate = function(cm, viewport, force) {
  3613. var display = cm.display;
  3614. this.viewport = viewport;
  3615. // Store some values that we'll need later (but don't want to force a relayout for)
  3616. this.visible = visibleLines(display, cm.doc, viewport);
  3617. this.editorIsHidden = !display.wrapper.offsetWidth;
  3618. this.wrapperHeight = display.wrapper.clientHeight;
  3619. this.wrapperWidth = display.wrapper.clientWidth;
  3620. this.oldDisplayWidth = displayWidth(cm);
  3621. this.force = force;
  3622. this.dims = getDimensions(cm);
  3623. this.events = [];
  3624. };
  3625. DisplayUpdate.prototype.signal = function (emitter, type) {
  3626. if (hasHandler(emitter, type))
  3627. { this.events.push(arguments); }
  3628. };
  3629. DisplayUpdate.prototype.finish = function () {
  3630. var this$1 = this;
  3631. for (var i = 0; i < this.events.length; i++)
  3632. { signal.apply(null, this$1.events[i]); }
  3633. };
  3634. function maybeClipScrollbars(cm) {
  3635. var display = cm.display;
  3636. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3637. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3638. display.heightForcer.style.height = scrollGap(cm) + "px";
  3639. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3640. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3641. display.scrollbarsClipped = true;
  3642. }
  3643. }
  3644. function selectionSnapshot(cm) {
  3645. if (cm.hasFocus()) { return null }
  3646. var active = activeElt();
  3647. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3648. var result = {activeElt: active};
  3649. if (window.getSelection) {
  3650. var sel = window.getSelection();
  3651. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3652. result.anchorNode = sel.anchorNode;
  3653. result.anchorOffset = sel.anchorOffset;
  3654. result.focusNode = sel.focusNode;
  3655. result.focusOffset = sel.focusOffset;
  3656. }
  3657. }
  3658. return result
  3659. }
  3660. function restoreSelection(snapshot) {
  3661. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3662. snapshot.activeElt.focus();
  3663. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3664. var sel = window.getSelection(), range$$1 = document.createRange();
  3665. range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3666. range$$1.collapse(false);
  3667. sel.removeAllRanges();
  3668. sel.addRange(range$$1);
  3669. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3670. }
  3671. }
  3672. // Does the actual updating of the line display. Bails out
  3673. // (returning false) when there is nothing to be done and forced is
  3674. // false.
  3675. function updateDisplayIfNeeded(cm, update) {
  3676. var display = cm.display, doc = cm.doc;
  3677. if (update.editorIsHidden) {
  3678. resetView(cm);
  3679. return false
  3680. }
  3681. // Bail out if the visible area is already rendered and nothing changed.
  3682. if (!update.force &&
  3683. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3684. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3685. display.renderedView == display.view && countDirtyView(cm) == 0)
  3686. { return false }
  3687. if (maybeUpdateLineNumberWidth(cm)) {
  3688. resetView(cm);
  3689. update.dims = getDimensions(cm);
  3690. }
  3691. // Compute a suitable new viewport (from & to)
  3692. var end = doc.first + doc.size;
  3693. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3694. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3695. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3696. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3697. if (sawCollapsedSpans) {
  3698. from = visualLineNo(cm.doc, from);
  3699. to = visualLineEndNo(cm.doc, to);
  3700. }
  3701. var different = from != display.viewFrom || to != display.viewTo ||
  3702. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3703. adjustView(cm, from, to);
  3704. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3705. // Position the mover div to align with the current scroll position
  3706. cm.display.mover.style.top = display.viewOffset + "px";
  3707. var toUpdate = countDirtyView(cm);
  3708. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3709. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3710. { return false }
  3711. // For big changes, we hide the enclosing element during the
  3712. // update, since that speeds up the operations on most browsers.
  3713. var selSnapshot = selectionSnapshot(cm);
  3714. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3715. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3716. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3717. display.renderedView = display.view;
  3718. // There might have been a widget with a focused element that got
  3719. // hidden or updated, if so re-focus it.
  3720. restoreSelection(selSnapshot);
  3721. // Prevent selection and cursors from interfering with the scroll
  3722. // width and height.
  3723. removeChildren(display.cursorDiv);
  3724. removeChildren(display.selectionDiv);
  3725. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3726. if (different) {
  3727. display.lastWrapHeight = update.wrapperHeight;
  3728. display.lastWrapWidth = update.wrapperWidth;
  3729. startWorker(cm, 400);
  3730. }
  3731. display.updateLineNumbers = null;
  3732. return true
  3733. }
  3734. function postUpdateDisplay(cm, update) {
  3735. var viewport = update.viewport;
  3736. for (var first = true;; first = false) {
  3737. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3738. // Clip forced viewport to actual scrollable area.
  3739. if (viewport && viewport.top != null)
  3740. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3741. // Updated line heights might result in the drawn area not
  3742. // actually covering the viewport. Keep looping until it does.
  3743. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3744. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3745. { break }
  3746. }
  3747. if (!updateDisplayIfNeeded(cm, update)) { break }
  3748. updateHeightsInViewport(cm);
  3749. var barMeasure = measureForScrollbars(cm);
  3750. updateSelection(cm);
  3751. updateScrollbars(cm, barMeasure);
  3752. setDocumentHeight(cm, barMeasure);
  3753. update.force = false;
  3754. }
  3755. update.signal(cm, "update", cm);
  3756. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3757. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3758. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3759. }
  3760. }
  3761. function updateDisplaySimple(cm, viewport) {
  3762. var update = new DisplayUpdate(cm, viewport);
  3763. if (updateDisplayIfNeeded(cm, update)) {
  3764. updateHeightsInViewport(cm);
  3765. postUpdateDisplay(cm, update);
  3766. var barMeasure = measureForScrollbars(cm);
  3767. updateSelection(cm);
  3768. updateScrollbars(cm, barMeasure);
  3769. setDocumentHeight(cm, barMeasure);
  3770. update.finish();
  3771. }
  3772. }
  3773. // Sync the actual display DOM structure with display.view, removing
  3774. // nodes for lines that are no longer in view, and creating the ones
  3775. // that are not there yet, and updating the ones that are out of
  3776. // date.
  3777. function patchDisplay(cm, updateNumbersFrom, dims) {
  3778. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3779. var container = display.lineDiv, cur = container.firstChild;
  3780. function rm(node) {
  3781. var next = node.nextSibling;
  3782. // Works around a throw-scroll bug in OS X Webkit
  3783. if (webkit && mac && cm.display.currentWheelTarget == node)
  3784. { node.style.display = "none"; }
  3785. else
  3786. { node.parentNode.removeChild(node); }
  3787. return next
  3788. }
  3789. var view = display.view, lineN = display.viewFrom;
  3790. // Loop over the elements in the view, syncing cur (the DOM nodes
  3791. // in display.lineDiv) with the view as we go.
  3792. for (var i = 0; i < view.length; i++) {
  3793. var lineView = view[i];
  3794. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3795. var node = buildLineElement(cm, lineView, lineN, dims);
  3796. container.insertBefore(node, cur);
  3797. } else { // Already drawn
  3798. while (cur != lineView.node) { cur = rm(cur); }
  3799. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3800. updateNumbersFrom <= lineN && lineView.lineNumber;
  3801. if (lineView.changes) {
  3802. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3803. updateLineForChanges(cm, lineView, lineN, dims);
  3804. }
  3805. if (updateNumber) {
  3806. removeChildren(lineView.lineNumber);
  3807. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3808. }
  3809. cur = lineView.node.nextSibling;
  3810. }
  3811. lineN += lineView.size;
  3812. }
  3813. while (cur) { cur = rm(cur); }
  3814. }
  3815. function updateGutterSpace(display) {
  3816. var width = display.gutters.offsetWidth;
  3817. display.sizer.style.marginLeft = width + "px";
  3818. }
  3819. function setDocumentHeight(cm, measure) {
  3820. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3821. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3822. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3823. }
  3824. // Re-align line numbers and gutter marks to compensate for
  3825. // horizontal scrolling.
  3826. function alignHorizontally(cm) {
  3827. var display = cm.display, view = display.view;
  3828. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3829. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3830. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3831. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3832. if (cm.options.fixedGutter) {
  3833. if (view[i].gutter)
  3834. { view[i].gutter.style.left = left; }
  3835. if (view[i].gutterBackground)
  3836. { view[i].gutterBackground.style.left = left; }
  3837. }
  3838. var align = view[i].alignable;
  3839. if (align) { for (var j = 0; j < align.length; j++)
  3840. { align[j].style.left = left; } }
  3841. } }
  3842. if (cm.options.fixedGutter)
  3843. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3844. }
  3845. // Used to ensure that the line number gutter is still the right
  3846. // size for the current document size. Returns true when an update
  3847. // is needed.
  3848. function maybeUpdateLineNumberWidth(cm) {
  3849. if (!cm.options.lineNumbers) { return false }
  3850. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3851. if (last.length != display.lineNumChars) {
  3852. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3853. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3854. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3855. display.lineGutter.style.width = "";
  3856. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3857. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3858. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3859. display.lineGutter.style.width = display.lineNumWidth + "px";
  3860. updateGutterSpace(cm.display);
  3861. return true
  3862. }
  3863. return false
  3864. }
  3865. function getGutters(gutters, lineNumbers) {
  3866. var result = [], sawLineNumbers = false;
  3867. for (var i = 0; i < gutters.length; i++) {
  3868. var name = gutters[i], style = null;
  3869. if (typeof name != "string") { style = name.style; name = name.className; }
  3870. if (name == "CodeMirror-linenumbers") {
  3871. if (!lineNumbers) { continue }
  3872. else { sawLineNumbers = true; }
  3873. }
  3874. result.push({className: name, style: style});
  3875. }
  3876. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  3877. return result
  3878. }
  3879. // Rebuild the gutter elements, ensure the margin to the left of the
  3880. // code matches their width.
  3881. function renderGutters(display) {
  3882. var gutters = display.gutters, specs = display.gutterSpecs;
  3883. removeChildren(gutters);
  3884. display.lineGutter = null;
  3885. for (var i = 0; i < specs.length; ++i) {
  3886. var ref = specs[i];
  3887. var className = ref.className;
  3888. var style = ref.style;
  3889. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  3890. if (style) { gElt.style.cssText = style; }
  3891. if (className == "CodeMirror-linenumbers") {
  3892. display.lineGutter = gElt;
  3893. gElt.style.width = (display.lineNumWidth || 1) + "px";
  3894. }
  3895. }
  3896. gutters.style.display = specs.length ? "" : "none";
  3897. updateGutterSpace(display);
  3898. }
  3899. function updateGutters(cm) {
  3900. renderGutters(cm.display);
  3901. regChange(cm);
  3902. alignHorizontally(cm);
  3903. }
  3904. // The display handles the DOM integration, both for input reading
  3905. // and content drawing. It holds references to DOM nodes and
  3906. // display-related state.
  3907. function Display(place, doc, input, options) {
  3908. var d = this;
  3909. this.input = input;
  3910. // Covers bottom-right square when both scrollbars are present.
  3911. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  3912. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  3913. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  3914. // and h scrollbar is present.
  3915. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  3916. d.gutterFiller.setAttribute("cm-not-content", "true");
  3917. // Will contain the actual code, positioned to cover the viewport.
  3918. d.lineDiv = eltP("div", null, "CodeMirror-code");
  3919. // Elements are added to these to represent selection and cursors.
  3920. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  3921. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  3922. // A visibility: hidden element used to find the size of things.
  3923. d.measure = elt("div", null, "CodeMirror-measure");
  3924. // When lines outside of the viewport are measured, they are drawn in this.
  3925. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  3926. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  3927. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  3928. null, "position: relative; outline: none");
  3929. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  3930. // Moved around its parent to cover visible view.
  3931. d.mover = elt("div", [lines], null, "position: relative");
  3932. // Set to the height of the document, allowing scrolling.
  3933. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  3934. d.sizerWidth = null;
  3935. // Behavior of elts with overflow: auto and padding is
  3936. // inconsistent across browsers. This is used to ensure the
  3937. // scrollable area is big enough.
  3938. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  3939. // Will contain the gutters, if any.
  3940. d.gutters = elt("div", null, "CodeMirror-gutters");
  3941. d.lineGutter = null;
  3942. // Actual scrollable element.
  3943. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  3944. d.scroller.setAttribute("tabIndex", "-1");
  3945. // The element in which the editor lives.
  3946. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  3947. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  3948. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  3949. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  3950. if (place) {
  3951. if (place.appendChild) { place.appendChild(d.wrapper); }
  3952. else { place(d.wrapper); }
  3953. }
  3954. // Current rendered range (may be bigger than the view window).
  3955. d.viewFrom = d.viewTo = doc.first;
  3956. d.reportedViewFrom = d.reportedViewTo = doc.first;
  3957. // Information about the rendered lines.
  3958. d.view = [];
  3959. d.renderedView = null;
  3960. // Holds info about a single rendered line when it was rendered
  3961. // for measurement, while not in view.
  3962. d.externalMeasured = null;
  3963. // Empty space (in pixels) above the view
  3964. d.viewOffset = 0;
  3965. d.lastWrapHeight = d.lastWrapWidth = 0;
  3966. d.updateLineNumbers = null;
  3967. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  3968. d.scrollbarsClipped = false;
  3969. // Used to only resize the line number gutter when necessary (when
  3970. // the amount of lines crosses a boundary that makes its width change)
  3971. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  3972. // Set to true when a non-horizontal-scrolling line widget is
  3973. // added. As an optimization, line widget aligning is skipped when
  3974. // this is false.
  3975. d.alignWidgets = false;
  3976. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3977. // Tracks the maximum line length so that the horizontal scrollbar
  3978. // can be kept static when scrolling.
  3979. d.maxLine = null;
  3980. d.maxLineLength = 0;
  3981. d.maxLineChanged = false;
  3982. // Used for measuring wheel scrolling granularity
  3983. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  3984. // True when shift is held down.
  3985. d.shift = false;
  3986. // Used to track whether anything happened since the context menu
  3987. // was opened.
  3988. d.selForContextMenu = null;
  3989. d.activeTouch = null;
  3990. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  3991. renderGutters(d);
  3992. input.init(d);
  3993. }
  3994. // Since the delta values reported on mouse wheel events are
  3995. // unstandardized between browsers and even browser versions, and
  3996. // generally horribly unpredictable, this code starts by measuring
  3997. // the scroll effect that the first few mouse wheel events have,
  3998. // and, from that, detects the way it can convert deltas to pixel
  3999. // offsets afterwards.
  4000. //
  4001. // The reason we want to know the amount a wheel event will scroll
  4002. // is that it gives us a chance to update the display before the
  4003. // actual scrolling happens, reducing flickering.
  4004. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4005. // Fill in a browser-detected starting value on browsers where we
  4006. // know one. These don't have to be accurate -- the result of them
  4007. // being wrong would just be a slight flicker on the first wheel
  4008. // scroll (if it is large enough).
  4009. if (ie) { wheelPixelsPerUnit = -.53; }
  4010. else if (gecko) { wheelPixelsPerUnit = 15; }
  4011. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4012. else if (safari) { wheelPixelsPerUnit = -1/3; }
  4013. function wheelEventDelta(e) {
  4014. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4015. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4016. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4017. else if (dy == null) { dy = e.wheelDelta; }
  4018. return {x: dx, y: dy}
  4019. }
  4020. function wheelEventPixels(e) {
  4021. var delta = wheelEventDelta(e);
  4022. delta.x *= wheelPixelsPerUnit;
  4023. delta.y *= wheelPixelsPerUnit;
  4024. return delta
  4025. }
  4026. function onScrollWheel(cm, e) {
  4027. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4028. var display = cm.display, scroll = display.scroller;
  4029. // Quit if there's nothing to scroll here
  4030. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4031. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4032. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4033. // Webkit browsers on OS X abort momentum scrolls when the target
  4034. // of the scroll event is removed from the scrollable element.
  4035. // This hack (see related code in patchDisplay) makes sure the
  4036. // element is kept around.
  4037. if (dy && mac && webkit) {
  4038. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4039. for (var i = 0; i < view.length; i++) {
  4040. if (view[i].node == cur) {
  4041. cm.display.currentWheelTarget = cur;
  4042. break outer
  4043. }
  4044. }
  4045. }
  4046. }
  4047. // On some browsers, horizontal scrolling will cause redraws to
  4048. // happen before the gutter has been realigned, causing it to
  4049. // wriggle around in a most unseemly way. When we have an
  4050. // estimated pixels/delta value, we just handle horizontal
  4051. // scrolling entirely here. It'll be slightly off from native, but
  4052. // better than glitching out.
  4053. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4054. if (dy && canScrollY)
  4055. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  4056. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  4057. // Only prevent default scrolling if vertical scrolling is
  4058. // actually possible. Otherwise, it causes vertical scroll
  4059. // jitter on OSX trackpads when deltaX is small and deltaY
  4060. // is large (issue #3579)
  4061. if (!dy || (dy && canScrollY))
  4062. { e_preventDefault(e); }
  4063. display.wheelStartX = null; // Abort measurement, if in progress
  4064. return
  4065. }
  4066. // 'Project' the visible viewport to cover the area that is being
  4067. // scrolled into view (if we know enough to estimate it).
  4068. if (dy && wheelPixelsPerUnit != null) {
  4069. var pixels = dy * wheelPixelsPerUnit;
  4070. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4071. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4072. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4073. updateDisplaySimple(cm, {top: top, bottom: bot});
  4074. }
  4075. if (wheelSamples < 20) {
  4076. if (display.wheelStartX == null) {
  4077. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4078. display.wheelDX = dx; display.wheelDY = dy;
  4079. setTimeout(function () {
  4080. if (display.wheelStartX == null) { return }
  4081. var movedX = scroll.scrollLeft - display.wheelStartX;
  4082. var movedY = scroll.scrollTop - display.wheelStartY;
  4083. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4084. (movedX && display.wheelDX && movedX / display.wheelDX);
  4085. display.wheelStartX = display.wheelStartY = null;
  4086. if (!sample) { return }
  4087. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4088. ++wheelSamples;
  4089. }, 200);
  4090. } else {
  4091. display.wheelDX += dx; display.wheelDY += dy;
  4092. }
  4093. }
  4094. }
  4095. // Selection objects are immutable. A new one is created every time
  4096. // the selection changes. A selection is one or more non-overlapping
  4097. // (and non-touching) ranges, sorted, and an integer that indicates
  4098. // which one is the primary selection (the one that's scrolled into
  4099. // view, that getCursor returns, etc).
  4100. var Selection = function(ranges, primIndex) {
  4101. this.ranges = ranges;
  4102. this.primIndex = primIndex;
  4103. };
  4104. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4105. Selection.prototype.equals = function (other) {
  4106. var this$1 = this;
  4107. if (other == this) { return true }
  4108. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4109. for (var i = 0; i < this.ranges.length; i++) {
  4110. var here = this$1.ranges[i], there = other.ranges[i];
  4111. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4112. }
  4113. return true
  4114. };
  4115. Selection.prototype.deepCopy = function () {
  4116. var this$1 = this;
  4117. var out = [];
  4118. for (var i = 0; i < this.ranges.length; i++)
  4119. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  4120. return new Selection(out, this.primIndex)
  4121. };
  4122. Selection.prototype.somethingSelected = function () {
  4123. var this$1 = this;
  4124. for (var i = 0; i < this.ranges.length; i++)
  4125. { if (!this$1.ranges[i].empty()) { return true } }
  4126. return false
  4127. };
  4128. Selection.prototype.contains = function (pos, end) {
  4129. var this$1 = this;
  4130. if (!end) { end = pos; }
  4131. for (var i = 0; i < this.ranges.length; i++) {
  4132. var range = this$1.ranges[i];
  4133. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4134. { return i }
  4135. }
  4136. return -1
  4137. };
  4138. var Range = function(anchor, head) {
  4139. this.anchor = anchor; this.head = head;
  4140. };
  4141. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4142. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4143. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4144. // Take an unsorted, potentially overlapping set of ranges, and
  4145. // build a selection out of it. 'Consumes' ranges array (modifying
  4146. // it).
  4147. function normalizeSelection(cm, ranges, primIndex) {
  4148. var mayTouch = cm && cm.options.selectionsMayTouch;
  4149. var prim = ranges[primIndex];
  4150. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4151. primIndex = indexOf(ranges, prim);
  4152. for (var i = 1; i < ranges.length; i++) {
  4153. var cur = ranges[i], prev = ranges[i - 1];
  4154. var diff = cmp(prev.to(), cur.from());
  4155. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4156. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4157. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4158. if (i <= primIndex) { --primIndex; }
  4159. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4160. }
  4161. }
  4162. return new Selection(ranges, primIndex)
  4163. }
  4164. function simpleSelection(anchor, head) {
  4165. return new Selection([new Range(anchor, head || anchor)], 0)
  4166. }
  4167. // Compute the position of the end of a change (its 'to' property
  4168. // refers to the pre-change end).
  4169. function changeEnd(change) {
  4170. if (!change.text) { return change.to }
  4171. return Pos(change.from.line + change.text.length - 1,
  4172. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4173. }
  4174. // Adjust a position to refer to the post-change position of the
  4175. // same text, or the end of the change if the change covers it.
  4176. function adjustForChange(pos, change) {
  4177. if (cmp(pos, change.from) < 0) { return pos }
  4178. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4179. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4180. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4181. return Pos(line, ch)
  4182. }
  4183. function computeSelAfterChange(doc, change) {
  4184. var out = [];
  4185. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4186. var range = doc.sel.ranges[i];
  4187. out.push(new Range(adjustForChange(range.anchor, change),
  4188. adjustForChange(range.head, change)));
  4189. }
  4190. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4191. }
  4192. function offsetPos(pos, old, nw) {
  4193. if (pos.line == old.line)
  4194. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4195. else
  4196. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4197. }
  4198. // Used by replaceSelections to allow moving the selection to the
  4199. // start or around the replaced test. Hint may be "start" or "around".
  4200. function computeReplacedSel(doc, changes, hint) {
  4201. var out = [];
  4202. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4203. for (var i = 0; i < changes.length; i++) {
  4204. var change = changes[i];
  4205. var from = offsetPos(change.from, oldPrev, newPrev);
  4206. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4207. oldPrev = change.to;
  4208. newPrev = to;
  4209. if (hint == "around") {
  4210. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4211. out[i] = new Range(inv ? to : from, inv ? from : to);
  4212. } else {
  4213. out[i] = new Range(from, from);
  4214. }
  4215. }
  4216. return new Selection(out, doc.sel.primIndex)
  4217. }
  4218. // Used to get the editor into a consistent state again when options change.
  4219. function loadMode(cm) {
  4220. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4221. resetModeState(cm);
  4222. }
  4223. function resetModeState(cm) {
  4224. cm.doc.iter(function (line) {
  4225. if (line.stateAfter) { line.stateAfter = null; }
  4226. if (line.styles) { line.styles = null; }
  4227. });
  4228. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4229. startWorker(cm, 100);
  4230. cm.state.modeGen++;
  4231. if (cm.curOp) { regChange(cm); }
  4232. }
  4233. // DOCUMENT DATA STRUCTURE
  4234. // By default, updates that start and end at the beginning of a line
  4235. // are treated specially, in order to make the association of line
  4236. // widgets and marker elements with the text behave more intuitive.
  4237. function isWholeLineUpdate(doc, change) {
  4238. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4239. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4240. }
  4241. // Perform a change on the document data structure.
  4242. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  4243. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4244. function update(line, text, spans) {
  4245. updateLine(line, text, spans, estimateHeight$$1);
  4246. signalLater(line, "change", line, change);
  4247. }
  4248. function linesFor(start, end) {
  4249. var result = [];
  4250. for (var i = start; i < end; ++i)
  4251. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  4252. return result
  4253. }
  4254. var from = change.from, to = change.to, text = change.text;
  4255. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4256. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4257. // Adjust the line structure
  4258. if (change.full) {
  4259. doc.insert(0, linesFor(0, text.length));
  4260. doc.remove(text.length, doc.size - text.length);
  4261. } else if (isWholeLineUpdate(doc, change)) {
  4262. // This is a whole-line replace. Treated specially to make
  4263. // sure line objects move the way they are supposed to.
  4264. var added = linesFor(0, text.length - 1);
  4265. update(lastLine, lastLine.text, lastSpans);
  4266. if (nlines) { doc.remove(from.line, nlines); }
  4267. if (added.length) { doc.insert(from.line, added); }
  4268. } else if (firstLine == lastLine) {
  4269. if (text.length == 1) {
  4270. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4271. } else {
  4272. var added$1 = linesFor(1, text.length - 1);
  4273. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  4274. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4275. doc.insert(from.line + 1, added$1);
  4276. }
  4277. } else if (text.length == 1) {
  4278. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4279. doc.remove(from.line + 1, nlines);
  4280. } else {
  4281. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4282. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4283. var added$2 = linesFor(1, text.length - 1);
  4284. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4285. doc.insert(from.line + 1, added$2);
  4286. }
  4287. signalLater(doc, "change", doc, change);
  4288. }
  4289. // Call f for all linked documents.
  4290. function linkedDocs(doc, f, sharedHistOnly) {
  4291. function propagate(doc, skip, sharedHist) {
  4292. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4293. var rel = doc.linked[i];
  4294. if (rel.doc == skip) { continue }
  4295. var shared = sharedHist && rel.sharedHist;
  4296. if (sharedHistOnly && !shared) { continue }
  4297. f(rel.doc, shared);
  4298. propagate(rel.doc, doc, shared);
  4299. } }
  4300. }
  4301. propagate(doc, null, true);
  4302. }
  4303. // Attach a document to an editor.
  4304. function attachDoc(cm, doc) {
  4305. if (doc.cm) { throw new Error("This document is already in use.") }
  4306. cm.doc = doc;
  4307. doc.cm = cm;
  4308. estimateLineHeights(cm);
  4309. loadMode(cm);
  4310. setDirectionClass(cm);
  4311. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4312. cm.options.mode = doc.modeOption;
  4313. regChange(cm);
  4314. }
  4315. function setDirectionClass(cm) {
  4316. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4317. }
  4318. function directionChanged(cm) {
  4319. runInOp(cm, function () {
  4320. setDirectionClass(cm);
  4321. regChange(cm);
  4322. });
  4323. }
  4324. function History(startGen) {
  4325. // Arrays of change events and selections. Doing something adds an
  4326. // event to done and clears undo. Undoing moves events from done
  4327. // to undone, redoing moves them in the other direction.
  4328. this.done = []; this.undone = [];
  4329. this.undoDepth = Infinity;
  4330. // Used to track when changes can be merged into a single undo
  4331. // event
  4332. this.lastModTime = this.lastSelTime = 0;
  4333. this.lastOp = this.lastSelOp = null;
  4334. this.lastOrigin = this.lastSelOrigin = null;
  4335. // Used by the isClean() method
  4336. this.generation = this.maxGeneration = startGen || 1;
  4337. }
  4338. // Create a history change event from an updateDoc-style change
  4339. // object.
  4340. function historyChangeFromChange(doc, change) {
  4341. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4342. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4343. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4344. return histChange
  4345. }
  4346. // Pop all selection events off the end of a history array. Stop at
  4347. // a change event.
  4348. function clearSelectionEvents(array) {
  4349. while (array.length) {
  4350. var last = lst(array);
  4351. if (last.ranges) { array.pop(); }
  4352. else { break }
  4353. }
  4354. }
  4355. // Find the top change event in the history. Pop off selection
  4356. // events that are in the way.
  4357. function lastChangeEvent(hist, force) {
  4358. if (force) {
  4359. clearSelectionEvents(hist.done);
  4360. return lst(hist.done)
  4361. } else if (hist.done.length && !lst(hist.done).ranges) {
  4362. return lst(hist.done)
  4363. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4364. hist.done.pop();
  4365. return lst(hist.done)
  4366. }
  4367. }
  4368. // Register a change in the history. Merges changes that are within
  4369. // a single operation, or are close together with an origin that
  4370. // allows merging (starting with "+") into a single event.
  4371. function addChangeToHistory(doc, change, selAfter, opId) {
  4372. var hist = doc.history;
  4373. hist.undone.length = 0;
  4374. var time = +new Date, cur;
  4375. var last;
  4376. if ((hist.lastOp == opId ||
  4377. hist.lastOrigin == change.origin && change.origin &&
  4378. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4379. change.origin.charAt(0) == "*")) &&
  4380. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4381. // Merge this change into the last event
  4382. last = lst(cur.changes);
  4383. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4384. // Optimized case for simple insertion -- don't want to add
  4385. // new changesets for every character typed
  4386. last.to = changeEnd(change);
  4387. } else {
  4388. // Add new sub-event
  4389. cur.changes.push(historyChangeFromChange(doc, change));
  4390. }
  4391. } else {
  4392. // Can not be merged, start a new event.
  4393. var before = lst(hist.done);
  4394. if (!before || !before.ranges)
  4395. { pushSelectionToHistory(doc.sel, hist.done); }
  4396. cur = {changes: [historyChangeFromChange(doc, change)],
  4397. generation: hist.generation};
  4398. hist.done.push(cur);
  4399. while (hist.done.length > hist.undoDepth) {
  4400. hist.done.shift();
  4401. if (!hist.done[0].ranges) { hist.done.shift(); }
  4402. }
  4403. }
  4404. hist.done.push(selAfter);
  4405. hist.generation = ++hist.maxGeneration;
  4406. hist.lastModTime = hist.lastSelTime = time;
  4407. hist.lastOp = hist.lastSelOp = opId;
  4408. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4409. if (!last) { signal(doc, "historyAdded"); }
  4410. }
  4411. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4412. var ch = origin.charAt(0);
  4413. return ch == "*" ||
  4414. ch == "+" &&
  4415. prev.ranges.length == sel.ranges.length &&
  4416. prev.somethingSelected() == sel.somethingSelected() &&
  4417. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4418. }
  4419. // Called whenever the selection changes, sets the new selection as
  4420. // the pending selection in the history, and pushes the old pending
  4421. // selection into the 'done' array when it was significantly
  4422. // different (in number of selected ranges, emptiness, or time).
  4423. function addSelectionToHistory(doc, sel, opId, options) {
  4424. var hist = doc.history, origin = options && options.origin;
  4425. // A new event is started when the previous origin does not match
  4426. // the current, or the origins don't allow matching. Origins
  4427. // starting with * are always merged, those starting with + are
  4428. // merged when similar and close together in time.
  4429. if (opId == hist.lastSelOp ||
  4430. (origin && hist.lastSelOrigin == origin &&
  4431. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4432. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4433. { hist.done[hist.done.length - 1] = sel; }
  4434. else
  4435. { pushSelectionToHistory(sel, hist.done); }
  4436. hist.lastSelTime = +new Date;
  4437. hist.lastSelOrigin = origin;
  4438. hist.lastSelOp = opId;
  4439. if (options && options.clearRedo !== false)
  4440. { clearSelectionEvents(hist.undone); }
  4441. }
  4442. function pushSelectionToHistory(sel, dest) {
  4443. var top = lst(dest);
  4444. if (!(top && top.ranges && top.equals(sel)))
  4445. { dest.push(sel); }
  4446. }
  4447. // Used to store marked span information in the history.
  4448. function attachLocalSpans(doc, change, from, to) {
  4449. var existing = change["spans_" + doc.id], n = 0;
  4450. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4451. if (line.markedSpans)
  4452. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4453. ++n;
  4454. });
  4455. }
  4456. // When un/re-doing restores text containing marked spans, those
  4457. // that have been explicitly cleared should not be restored.
  4458. function removeClearedSpans(spans) {
  4459. if (!spans) { return null }
  4460. var out;
  4461. for (var i = 0; i < spans.length; ++i) {
  4462. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4463. else if (out) { out.push(spans[i]); }
  4464. }
  4465. return !out ? spans : out.length ? out : null
  4466. }
  4467. // Retrieve and filter the old marked spans stored in a change event.
  4468. function getOldSpans(doc, change) {
  4469. var found = change["spans_" + doc.id];
  4470. if (!found) { return null }
  4471. var nw = [];
  4472. for (var i = 0; i < change.text.length; ++i)
  4473. { nw.push(removeClearedSpans(found[i])); }
  4474. return nw
  4475. }
  4476. // Used for un/re-doing changes from the history. Combines the
  4477. // result of computing the existing spans with the set of spans that
  4478. // existed in the history (so that deleting around a span and then
  4479. // undoing brings back the span).
  4480. function mergeOldSpans(doc, change) {
  4481. var old = getOldSpans(doc, change);
  4482. var stretched = stretchSpansOverChange(doc, change);
  4483. if (!old) { return stretched }
  4484. if (!stretched) { return old }
  4485. for (var i = 0; i < old.length; ++i) {
  4486. var oldCur = old[i], stretchCur = stretched[i];
  4487. if (oldCur && stretchCur) {
  4488. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4489. var span = stretchCur[j];
  4490. for (var k = 0; k < oldCur.length; ++k)
  4491. { if (oldCur[k].marker == span.marker) { continue spans } }
  4492. oldCur.push(span);
  4493. }
  4494. } else if (stretchCur) {
  4495. old[i] = stretchCur;
  4496. }
  4497. }
  4498. return old
  4499. }
  4500. // Used both to provide a JSON-safe object in .getHistory, and, when
  4501. // detaching a document, to split the history in two
  4502. function copyHistoryArray(events, newGroup, instantiateSel) {
  4503. var copy = [];
  4504. for (var i = 0; i < events.length; ++i) {
  4505. var event = events[i];
  4506. if (event.ranges) {
  4507. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4508. continue
  4509. }
  4510. var changes = event.changes, newChanges = [];
  4511. copy.push({changes: newChanges});
  4512. for (var j = 0; j < changes.length; ++j) {
  4513. var change = changes[j], m = (void 0);
  4514. newChanges.push({from: change.from, to: change.to, text: change.text});
  4515. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4516. if (indexOf(newGroup, Number(m[1])) > -1) {
  4517. lst(newChanges)[prop] = change[prop];
  4518. delete change[prop];
  4519. }
  4520. } } }
  4521. }
  4522. }
  4523. return copy
  4524. }
  4525. // The 'scroll' parameter given to many of these indicated whether
  4526. // the new cursor position should be scrolled into view after
  4527. // modifying the selection.
  4528. // If shift is held or the extend flag is set, extends a range to
  4529. // include a given position (and optionally a second position).
  4530. // Otherwise, simply returns the range between the given positions.
  4531. // Used for cursor motion and such.
  4532. function extendRange(range, head, other, extend) {
  4533. if (extend) {
  4534. var anchor = range.anchor;
  4535. if (other) {
  4536. var posBefore = cmp(head, anchor) < 0;
  4537. if (posBefore != (cmp(other, anchor) < 0)) {
  4538. anchor = head;
  4539. head = other;
  4540. } else if (posBefore != (cmp(head, other) < 0)) {
  4541. head = other;
  4542. }
  4543. }
  4544. return new Range(anchor, head)
  4545. } else {
  4546. return new Range(other || head, head)
  4547. }
  4548. }
  4549. // Extend the primary selection range, discard the rest.
  4550. function extendSelection(doc, head, other, options, extend) {
  4551. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4552. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4553. }
  4554. // Extend all selections (pos is an array of selections with length
  4555. // equal the number of selections)
  4556. function extendSelections(doc, heads, options) {
  4557. var out = [];
  4558. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4559. for (var i = 0; i < doc.sel.ranges.length; i++)
  4560. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4561. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4562. setSelection(doc, newSel, options);
  4563. }
  4564. // Updates a single range in the selection.
  4565. function replaceOneSelection(doc, i, range, options) {
  4566. var ranges = doc.sel.ranges.slice(0);
  4567. ranges[i] = range;
  4568. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4569. }
  4570. // Reset the selection to a single range.
  4571. function setSimpleSelection(doc, anchor, head, options) {
  4572. setSelection(doc, simpleSelection(anchor, head), options);
  4573. }
  4574. // Give beforeSelectionChange handlers a change to influence a
  4575. // selection update.
  4576. function filterSelectionChange(doc, sel, options) {
  4577. var obj = {
  4578. ranges: sel.ranges,
  4579. update: function(ranges) {
  4580. var this$1 = this;
  4581. this.ranges = [];
  4582. for (var i = 0; i < ranges.length; i++)
  4583. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4584. clipPos(doc, ranges[i].head)); }
  4585. },
  4586. origin: options && options.origin
  4587. };
  4588. signal(doc, "beforeSelectionChange", doc, obj);
  4589. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4590. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4591. else { return sel }
  4592. }
  4593. function setSelectionReplaceHistory(doc, sel, options) {
  4594. var done = doc.history.done, last = lst(done);
  4595. if (last && last.ranges) {
  4596. done[done.length - 1] = sel;
  4597. setSelectionNoUndo(doc, sel, options);
  4598. } else {
  4599. setSelection(doc, sel, options);
  4600. }
  4601. }
  4602. // Set a new selection.
  4603. function setSelection(doc, sel, options) {
  4604. setSelectionNoUndo(doc, sel, options);
  4605. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4606. }
  4607. function setSelectionNoUndo(doc, sel, options) {
  4608. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4609. { sel = filterSelectionChange(doc, sel, options); }
  4610. var bias = options && options.bias ||
  4611. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4612. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4613. if (!(options && options.scroll === false) && doc.cm)
  4614. { ensureCursorVisible(doc.cm); }
  4615. }
  4616. function setSelectionInner(doc, sel) {
  4617. if (sel.equals(doc.sel)) { return }
  4618. doc.sel = sel;
  4619. if (doc.cm) {
  4620. doc.cm.curOp.updateInput = 1;
  4621. doc.cm.curOp.selectionChanged = true;
  4622. signalCursorActivity(doc.cm);
  4623. }
  4624. signalLater(doc, "cursorActivity", doc);
  4625. }
  4626. // Verify that the selection does not partially select any atomic
  4627. // marked ranges.
  4628. function reCheckSelection(doc) {
  4629. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4630. }
  4631. // Return a selection that does not partially select any atomic
  4632. // ranges.
  4633. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4634. var out;
  4635. for (var i = 0; i < sel.ranges.length; i++) {
  4636. var range = sel.ranges[i];
  4637. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4638. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4639. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4640. if (out || newAnchor != range.anchor || newHead != range.head) {
  4641. if (!out) { out = sel.ranges.slice(0, i); }
  4642. out[i] = new Range(newAnchor, newHead);
  4643. }
  4644. }
  4645. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4646. }
  4647. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4648. var line = getLine(doc, pos.line);
  4649. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4650. var sp = line.markedSpans[i], m = sp.marker;
  4651. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4652. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4653. if (mayClear) {
  4654. signal(m, "beforeCursorEnter");
  4655. if (m.explicitlyCleared) {
  4656. if (!line.markedSpans) { break }
  4657. else {--i; continue}
  4658. }
  4659. }
  4660. if (!m.atomic) { continue }
  4661. if (oldPos) {
  4662. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4663. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4664. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4665. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4666. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4667. }
  4668. var far = m.find(dir < 0 ? -1 : 1);
  4669. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4670. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4671. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4672. }
  4673. } }
  4674. return pos
  4675. }
  4676. // Ensure a given position is not inside an atomic range.
  4677. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4678. var dir = bias || 1;
  4679. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4680. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4681. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4682. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4683. if (!found) {
  4684. doc.cantEdit = true;
  4685. return Pos(doc.first, 0)
  4686. }
  4687. return found
  4688. }
  4689. function movePos(doc, pos, dir, line) {
  4690. if (dir < 0 && pos.ch == 0) {
  4691. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4692. else { return null }
  4693. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4694. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4695. else { return null }
  4696. } else {
  4697. return new Pos(pos.line, pos.ch + dir)
  4698. }
  4699. }
  4700. function selectAll(cm) {
  4701. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4702. }
  4703. // UPDATING
  4704. // Allow "beforeChange" event handlers to influence a change
  4705. function filterChange(doc, change, update) {
  4706. var obj = {
  4707. canceled: false,
  4708. from: change.from,
  4709. to: change.to,
  4710. text: change.text,
  4711. origin: change.origin,
  4712. cancel: function () { return obj.canceled = true; }
  4713. };
  4714. if (update) { obj.update = function (from, to, text, origin) {
  4715. if (from) { obj.from = clipPos(doc, from); }
  4716. if (to) { obj.to = clipPos(doc, to); }
  4717. if (text) { obj.text = text; }
  4718. if (origin !== undefined) { obj.origin = origin; }
  4719. }; }
  4720. signal(doc, "beforeChange", doc, obj);
  4721. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4722. if (obj.canceled) {
  4723. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4724. return null
  4725. }
  4726. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4727. }
  4728. // Apply a change to a document, and add it to the document's
  4729. // history, and propagating it to all linked documents.
  4730. function makeChange(doc, change, ignoreReadOnly) {
  4731. if (doc.cm) {
  4732. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4733. if (doc.cm.state.suppressEdits) { return }
  4734. }
  4735. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4736. change = filterChange(doc, change, true);
  4737. if (!change) { return }
  4738. }
  4739. // Possibly split or suppress the update based on the presence
  4740. // of read-only spans in its range.
  4741. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4742. if (split) {
  4743. for (var i = split.length - 1; i >= 0; --i)
  4744. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4745. } else {
  4746. makeChangeInner(doc, change);
  4747. }
  4748. }
  4749. function makeChangeInner(doc, change) {
  4750. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4751. var selAfter = computeSelAfterChange(doc, change);
  4752. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4753. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4754. var rebased = [];
  4755. linkedDocs(doc, function (doc, sharedHist) {
  4756. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4757. rebaseHist(doc.history, change);
  4758. rebased.push(doc.history);
  4759. }
  4760. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4761. });
  4762. }
  4763. // Revert a change stored in a document's history.
  4764. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4765. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4766. if (suppress && !allowSelectionOnly) { return }
  4767. var hist = doc.history, event, selAfter = doc.sel;
  4768. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4769. // Verify that there is a useable event (so that ctrl-z won't
  4770. // needlessly clear selection events)
  4771. var i = 0;
  4772. for (; i < source.length; i++) {
  4773. event = source[i];
  4774. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4775. { break }
  4776. }
  4777. if (i == source.length) { return }
  4778. hist.lastOrigin = hist.lastSelOrigin = null;
  4779. for (;;) {
  4780. event = source.pop();
  4781. if (event.ranges) {
  4782. pushSelectionToHistory(event, dest);
  4783. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4784. setSelection(doc, event, {clearRedo: false});
  4785. return
  4786. }
  4787. selAfter = event;
  4788. } else if (suppress) {
  4789. source.push(event);
  4790. return
  4791. } else { break }
  4792. }
  4793. // Build up a reverse change object to add to the opposite history
  4794. // stack (redo when undoing, and vice versa).
  4795. var antiChanges = [];
  4796. pushSelectionToHistory(selAfter, dest);
  4797. dest.push({changes: antiChanges, generation: hist.generation});
  4798. hist.generation = event.generation || ++hist.maxGeneration;
  4799. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4800. var loop = function ( i ) {
  4801. var change = event.changes[i];
  4802. change.origin = type;
  4803. if (filter && !filterChange(doc, change, false)) {
  4804. source.length = 0;
  4805. return {}
  4806. }
  4807. antiChanges.push(historyChangeFromChange(doc, change));
  4808. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4809. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4810. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4811. var rebased = [];
  4812. // Propagate to the linked documents
  4813. linkedDocs(doc, function (doc, sharedHist) {
  4814. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4815. rebaseHist(doc.history, change);
  4816. rebased.push(doc.history);
  4817. }
  4818. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4819. });
  4820. };
  4821. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4822. var returned = loop( i$1 );
  4823. if ( returned ) return returned.v;
  4824. }
  4825. }
  4826. // Sub-views need their line numbers shifted when text is added
  4827. // above or below them in the parent document.
  4828. function shiftDoc(doc, distance) {
  4829. if (distance == 0) { return }
  4830. doc.first += distance;
  4831. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4832. Pos(range.anchor.line + distance, range.anchor.ch),
  4833. Pos(range.head.line + distance, range.head.ch)
  4834. ); }), doc.sel.primIndex);
  4835. if (doc.cm) {
  4836. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4837. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4838. { regLineChange(doc.cm, l, "gutter"); }
  4839. }
  4840. }
  4841. // More lower-level change function, handling only a single document
  4842. // (not linked ones).
  4843. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4844. if (doc.cm && !doc.cm.curOp)
  4845. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4846. if (change.to.line < doc.first) {
  4847. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4848. return
  4849. }
  4850. if (change.from.line > doc.lastLine()) { return }
  4851. // Clip the change to the size of this doc
  4852. if (change.from.line < doc.first) {
  4853. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4854. shiftDoc(doc, shift);
  4855. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4856. text: [lst(change.text)], origin: change.origin};
  4857. }
  4858. var last = doc.lastLine();
  4859. if (change.to.line > last) {
  4860. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4861. text: [change.text[0]], origin: change.origin};
  4862. }
  4863. change.removed = getBetween(doc, change.from, change.to);
  4864. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4865. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4866. else { updateDoc(doc, change, spans); }
  4867. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4868. }
  4869. // Handle the interaction of a change to a document with the editor
  4870. // that this document is part of.
  4871. function makeChangeSingleDocInEditor(cm, change, spans) {
  4872. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4873. var recomputeMaxLength = false, checkWidthStart = from.line;
  4874. if (!cm.options.lineWrapping) {
  4875. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4876. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4877. if (line == display.maxLine) {
  4878. recomputeMaxLength = true;
  4879. return true
  4880. }
  4881. });
  4882. }
  4883. if (doc.sel.contains(change.from, change.to) > -1)
  4884. { signalCursorActivity(cm); }
  4885. updateDoc(doc, change, spans, estimateHeight(cm));
  4886. if (!cm.options.lineWrapping) {
  4887. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4888. var len = lineLength(line);
  4889. if (len > display.maxLineLength) {
  4890. display.maxLine = line;
  4891. display.maxLineLength = len;
  4892. display.maxLineChanged = true;
  4893. recomputeMaxLength = false;
  4894. }
  4895. });
  4896. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4897. }
  4898. retreatFrontier(doc, from.line);
  4899. startWorker(cm, 400);
  4900. var lendiff = change.text.length - (to.line - from.line) - 1;
  4901. // Remember that these lines changed, for updating the display
  4902. if (change.full)
  4903. { regChange(cm); }
  4904. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4905. { regLineChange(cm, from.line, "text"); }
  4906. else
  4907. { regChange(cm, from.line, to.line + 1, lendiff); }
  4908. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4909. if (changeHandler || changesHandler) {
  4910. var obj = {
  4911. from: from, to: to,
  4912. text: change.text,
  4913. removed: change.removed,
  4914. origin: change.origin
  4915. };
  4916. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  4917. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  4918. }
  4919. cm.display.selForContextMenu = null;
  4920. }
  4921. function replaceRange(doc, code, from, to, origin) {
  4922. var assign;
  4923. if (!to) { to = from; }
  4924. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  4925. if (typeof code == "string") { code = doc.splitLines(code); }
  4926. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4927. }
  4928. // Rebasing/resetting history to deal with externally-sourced changes
  4929. function rebaseHistSelSingle(pos, from, to, diff) {
  4930. if (to < pos.line) {
  4931. pos.line += diff;
  4932. } else if (from < pos.line) {
  4933. pos.line = from;
  4934. pos.ch = 0;
  4935. }
  4936. }
  4937. // Tries to rebase an array of history events given a change in the
  4938. // document. If the change touches the same lines as the event, the
  4939. // event, and everything 'behind' it, is discarded. If the change is
  4940. // before the event, the event's positions are updated. Uses a
  4941. // copy-on-write scheme for the positions, to avoid having to
  4942. // reallocate them all on every rebase, but also avoid problems with
  4943. // shared position objects being unsafely updated.
  4944. function rebaseHistArray(array, from, to, diff) {
  4945. for (var i = 0; i < array.length; ++i) {
  4946. var sub = array[i], ok = true;
  4947. if (sub.ranges) {
  4948. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  4949. for (var j = 0; j < sub.ranges.length; j++) {
  4950. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  4951. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  4952. }
  4953. continue
  4954. }
  4955. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4956. var cur = sub.changes[j$1];
  4957. if (to < cur.from.line) {
  4958. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  4959. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  4960. } else if (from <= cur.to.line) {
  4961. ok = false;
  4962. break
  4963. }
  4964. }
  4965. if (!ok) {
  4966. array.splice(0, i + 1);
  4967. i = 0;
  4968. }
  4969. }
  4970. }
  4971. function rebaseHist(hist, change) {
  4972. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  4973. rebaseHistArray(hist.done, from, to, diff);
  4974. rebaseHistArray(hist.undone, from, to, diff);
  4975. }
  4976. // Utility for applying a change to a line by handle or number,
  4977. // returning the number and optionally registering the line as
  4978. // changed.
  4979. function changeLine(doc, handle, changeType, op) {
  4980. var no = handle, line = handle;
  4981. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  4982. else { no = lineNo(handle); }
  4983. if (no == null) { return null }
  4984. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  4985. return line
  4986. }
  4987. // The document is represented as a BTree consisting of leaves, with
  4988. // chunk of lines in them, and branches, with up to ten leaves or
  4989. // other branch nodes below them. The top node is always a branch
  4990. // node, and is the document object itself (meaning it has
  4991. // additional methods and properties).
  4992. //
  4993. // All nodes have parent links. The tree is used both to go from
  4994. // line numbers to line objects, and to go from objects to numbers.
  4995. // It also indexes by height, and is used to convert between height
  4996. // and line object, and to find the total height of the document.
  4997. //
  4998. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4999. function LeafChunk(lines) {
  5000. var this$1 = this;
  5001. this.lines = lines;
  5002. this.parent = null;
  5003. var height = 0;
  5004. for (var i = 0; i < lines.length; ++i) {
  5005. lines[i].parent = this$1;
  5006. height += lines[i].height;
  5007. }
  5008. this.height = height;
  5009. }
  5010. LeafChunk.prototype = {
  5011. chunkSize: function() { return this.lines.length },
  5012. // Remove the n lines at offset 'at'.
  5013. removeInner: function(at, n) {
  5014. var this$1 = this;
  5015. for (var i = at, e = at + n; i < e; ++i) {
  5016. var line = this$1.lines[i];
  5017. this$1.height -= line.height;
  5018. cleanUpLine(line);
  5019. signalLater(line, "delete");
  5020. }
  5021. this.lines.splice(at, n);
  5022. },
  5023. // Helper used to collapse a small branch into a single leaf.
  5024. collapse: function(lines) {
  5025. lines.push.apply(lines, this.lines);
  5026. },
  5027. // Insert the given array of lines at offset 'at', count them as
  5028. // having the given height.
  5029. insertInner: function(at, lines, height) {
  5030. var this$1 = this;
  5031. this.height += height;
  5032. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5033. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  5034. },
  5035. // Used to iterate over a part of the tree.
  5036. iterN: function(at, n, op) {
  5037. var this$1 = this;
  5038. for (var e = at + n; at < e; ++at)
  5039. { if (op(this$1.lines[at])) { return true } }
  5040. }
  5041. };
  5042. function BranchChunk(children) {
  5043. var this$1 = this;
  5044. this.children = children;
  5045. var size = 0, height = 0;
  5046. for (var i = 0; i < children.length; ++i) {
  5047. var ch = children[i];
  5048. size += ch.chunkSize(); height += ch.height;
  5049. ch.parent = this$1;
  5050. }
  5051. this.size = size;
  5052. this.height = height;
  5053. this.parent = null;
  5054. }
  5055. BranchChunk.prototype = {
  5056. chunkSize: function() { return this.size },
  5057. removeInner: function(at, n) {
  5058. var this$1 = this;
  5059. this.size -= n;
  5060. for (var i = 0; i < this.children.length; ++i) {
  5061. var child = this$1.children[i], sz = child.chunkSize();
  5062. if (at < sz) {
  5063. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5064. child.removeInner(at, rm);
  5065. this$1.height -= oldHeight - child.height;
  5066. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  5067. if ((n -= rm) == 0) { break }
  5068. at = 0;
  5069. } else { at -= sz; }
  5070. }
  5071. // If the result is smaller than 25 lines, ensure that it is a
  5072. // single leaf node.
  5073. if (this.size - n < 25 &&
  5074. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5075. var lines = [];
  5076. this.collapse(lines);
  5077. this.children = [new LeafChunk(lines)];
  5078. this.children[0].parent = this;
  5079. }
  5080. },
  5081. collapse: function(lines) {
  5082. var this$1 = this;
  5083. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  5084. },
  5085. insertInner: function(at, lines, height) {
  5086. var this$1 = this;
  5087. this.size += lines.length;
  5088. this.height += height;
  5089. for (var i = 0; i < this.children.length; ++i) {
  5090. var child = this$1.children[i], sz = child.chunkSize();
  5091. if (at <= sz) {
  5092. child.insertInner(at, lines, height);
  5093. if (child.lines && child.lines.length > 50) {
  5094. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5095. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5096. var remaining = child.lines.length % 25 + 25;
  5097. for (var pos = remaining; pos < child.lines.length;) {
  5098. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5099. child.height -= leaf.height;
  5100. this$1.children.splice(++i, 0, leaf);
  5101. leaf.parent = this$1;
  5102. }
  5103. child.lines = child.lines.slice(0, remaining);
  5104. this$1.maybeSpill();
  5105. }
  5106. break
  5107. }
  5108. at -= sz;
  5109. }
  5110. },
  5111. // When a node has grown, check whether it should be split.
  5112. maybeSpill: function() {
  5113. if (this.children.length <= 10) { return }
  5114. var me = this;
  5115. do {
  5116. var spilled = me.children.splice(me.children.length - 5, 5);
  5117. var sibling = new BranchChunk(spilled);
  5118. if (!me.parent) { // Become the parent node
  5119. var copy = new BranchChunk(me.children);
  5120. copy.parent = me;
  5121. me.children = [copy, sibling];
  5122. me = copy;
  5123. } else {
  5124. me.size -= sibling.size;
  5125. me.height -= sibling.height;
  5126. var myIndex = indexOf(me.parent.children, me);
  5127. me.parent.children.splice(myIndex + 1, 0, sibling);
  5128. }
  5129. sibling.parent = me.parent;
  5130. } while (me.children.length > 10)
  5131. me.parent.maybeSpill();
  5132. },
  5133. iterN: function(at, n, op) {
  5134. var this$1 = this;
  5135. for (var i = 0; i < this.children.length; ++i) {
  5136. var child = this$1.children[i], sz = child.chunkSize();
  5137. if (at < sz) {
  5138. var used = Math.min(n, sz - at);
  5139. if (child.iterN(at, used, op)) { return true }
  5140. if ((n -= used) == 0) { break }
  5141. at = 0;
  5142. } else { at -= sz; }
  5143. }
  5144. }
  5145. };
  5146. // Line widgets are block elements displayed above or below a line.
  5147. var LineWidget = function(doc, node, options) {
  5148. var this$1 = this;
  5149. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5150. { this$1[opt] = options[opt]; } } }
  5151. this.doc = doc;
  5152. this.node = node;
  5153. };
  5154. LineWidget.prototype.clear = function () {
  5155. var this$1 = this;
  5156. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5157. if (no == null || !ws) { return }
  5158. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  5159. if (!ws.length) { line.widgets = null; }
  5160. var height = widgetHeight(this);
  5161. updateLineHeight(line, Math.max(0, line.height - height));
  5162. if (cm) {
  5163. runInOp(cm, function () {
  5164. adjustScrollWhenAboveVisible(cm, line, -height);
  5165. regLineChange(cm, no, "widget");
  5166. });
  5167. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5168. }
  5169. };
  5170. LineWidget.prototype.changed = function () {
  5171. var this$1 = this;
  5172. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5173. this.height = null;
  5174. var diff = widgetHeight(this) - oldH;
  5175. if (!diff) { return }
  5176. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5177. if (cm) {
  5178. runInOp(cm, function () {
  5179. cm.curOp.forceUpdate = true;
  5180. adjustScrollWhenAboveVisible(cm, line, diff);
  5181. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5182. });
  5183. }
  5184. };
  5185. eventMixin(LineWidget);
  5186. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5187. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5188. { addToScrollTop(cm, diff); }
  5189. }
  5190. function addLineWidget(doc, handle, node, options) {
  5191. var widget = new LineWidget(doc, node, options);
  5192. var cm = doc.cm;
  5193. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5194. changeLine(doc, handle, "widget", function (line) {
  5195. var widgets = line.widgets || (line.widgets = []);
  5196. if (widget.insertAt == null) { widgets.push(widget); }
  5197. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  5198. widget.line = line;
  5199. if (cm && !lineIsHidden(doc, line)) {
  5200. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5201. updateLineHeight(line, line.height + widgetHeight(widget));
  5202. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5203. cm.curOp.forceUpdate = true;
  5204. }
  5205. return true
  5206. });
  5207. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5208. return widget
  5209. }
  5210. // TEXTMARKERS
  5211. // Created with markText and setBookmark methods. A TextMarker is a
  5212. // handle that can be used to clear or find a marked position in the
  5213. // document. Line objects hold arrays (markedSpans) containing
  5214. // {from, to, marker} object pointing to such marker objects, and
  5215. // indicating that such a marker is present on that line. Multiple
  5216. // lines may point to the same marker when it spans across lines.
  5217. // The spans will have null for their from/to properties when the
  5218. // marker continues beyond the start/end of the line. Markers have
  5219. // links back to the lines they currently touch.
  5220. // Collapsed markers have unique ids, in order to be able to order
  5221. // them, which is needed for uniquely determining an outer marker
  5222. // when they overlap (they may nest, but not partially overlap).
  5223. var nextMarkerId = 0;
  5224. var TextMarker = function(doc, type) {
  5225. this.lines = [];
  5226. this.type = type;
  5227. this.doc = doc;
  5228. this.id = ++nextMarkerId;
  5229. };
  5230. // Clear the marker.
  5231. TextMarker.prototype.clear = function () {
  5232. var this$1 = this;
  5233. if (this.explicitlyCleared) { return }
  5234. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5235. if (withOp) { startOperation(cm); }
  5236. if (hasHandler(this, "clear")) {
  5237. var found = this.find();
  5238. if (found) { signalLater(this, "clear", found.from, found.to); }
  5239. }
  5240. var min = null, max = null;
  5241. for (var i = 0; i < this.lines.length; ++i) {
  5242. var line = this$1.lines[i];
  5243. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5244. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5245. else if (cm) {
  5246. if (span.to != null) { max = lineNo(line); }
  5247. if (span.from != null) { min = lineNo(line); }
  5248. }
  5249. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5250. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5251. { updateLineHeight(line, textHeight(cm.display)); }
  5252. }
  5253. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5254. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  5255. if (len > cm.display.maxLineLength) {
  5256. cm.display.maxLine = visual;
  5257. cm.display.maxLineLength = len;
  5258. cm.display.maxLineChanged = true;
  5259. }
  5260. } }
  5261. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5262. this.lines.length = 0;
  5263. this.explicitlyCleared = true;
  5264. if (this.atomic && this.doc.cantEdit) {
  5265. this.doc.cantEdit = false;
  5266. if (cm) { reCheckSelection(cm.doc); }
  5267. }
  5268. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5269. if (withOp) { endOperation(cm); }
  5270. if (this.parent) { this.parent.clear(); }
  5271. };
  5272. // Find the position of the marker in the document. Returns a {from,
  5273. // to} object by default. Side can be passed to get a specific side
  5274. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5275. // Pos objects returned contain a line object, rather than a line
  5276. // number (used to prevent looking up the same line twice).
  5277. TextMarker.prototype.find = function (side, lineObj) {
  5278. var this$1 = this;
  5279. if (side == null && this.type == "bookmark") { side = 1; }
  5280. var from, to;
  5281. for (var i = 0; i < this.lines.length; ++i) {
  5282. var line = this$1.lines[i];
  5283. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5284. if (span.from != null) {
  5285. from = Pos(lineObj ? line : lineNo(line), span.from);
  5286. if (side == -1) { return from }
  5287. }
  5288. if (span.to != null) {
  5289. to = Pos(lineObj ? line : lineNo(line), span.to);
  5290. if (side == 1) { return to }
  5291. }
  5292. }
  5293. return from && {from: from, to: to}
  5294. };
  5295. // Signals that the marker's widget changed, and surrounding layout
  5296. // should be recomputed.
  5297. TextMarker.prototype.changed = function () {
  5298. var this$1 = this;
  5299. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5300. if (!pos || !cm) { return }
  5301. runInOp(cm, function () {
  5302. var line = pos.line, lineN = lineNo(pos.line);
  5303. var view = findViewForLine(cm, lineN);
  5304. if (view) {
  5305. clearLineMeasurementCacheFor(view);
  5306. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5307. }
  5308. cm.curOp.updateMaxLine = true;
  5309. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5310. var oldHeight = widget.height;
  5311. widget.height = null;
  5312. var dHeight = widgetHeight(widget) - oldHeight;
  5313. if (dHeight)
  5314. { updateLineHeight(line, line.height + dHeight); }
  5315. }
  5316. signalLater(cm, "markerChanged", cm, this$1);
  5317. });
  5318. };
  5319. TextMarker.prototype.attachLine = function (line) {
  5320. if (!this.lines.length && this.doc.cm) {
  5321. var op = this.doc.cm.curOp;
  5322. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5323. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5324. }
  5325. this.lines.push(line);
  5326. };
  5327. TextMarker.prototype.detachLine = function (line) {
  5328. this.lines.splice(indexOf(this.lines, line), 1);
  5329. if (!this.lines.length && this.doc.cm) {
  5330. var op = this.doc.cm.curOp
  5331. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5332. }
  5333. };
  5334. eventMixin(TextMarker);
  5335. // Create a marker, wire it up to the right lines, and
  5336. function markText(doc, from, to, options, type) {
  5337. // Shared markers (across linked documents) are handled separately
  5338. // (markTextShared will call out to this again, once per
  5339. // document).
  5340. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5341. // Ensure we are in an operation.
  5342. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5343. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5344. if (options) { copyObj(options, marker, false); }
  5345. // Don't connect empty markers unless clearWhenEmpty is false
  5346. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5347. { return marker }
  5348. if (marker.replacedWith) {
  5349. // Showing up as a widget implies collapsed (widget replaces text)
  5350. marker.collapsed = true;
  5351. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5352. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5353. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5354. }
  5355. if (marker.collapsed) {
  5356. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5357. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5358. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5359. seeCollapsedSpans();
  5360. }
  5361. if (marker.addToHistory)
  5362. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5363. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5364. doc.iter(curLine, to.line + 1, function (line) {
  5365. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5366. { updateMaxLine = true; }
  5367. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5368. addMarkedSpan(line, new MarkedSpan(marker,
  5369. curLine == from.line ? from.ch : null,
  5370. curLine == to.line ? to.ch : null));
  5371. ++curLine;
  5372. });
  5373. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5374. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5375. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5376. }); }
  5377. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5378. if (marker.readOnly) {
  5379. seeReadOnlySpans();
  5380. if (doc.history.done.length || doc.history.undone.length)
  5381. { doc.clearHistory(); }
  5382. }
  5383. if (marker.collapsed) {
  5384. marker.id = ++nextMarkerId;
  5385. marker.atomic = true;
  5386. }
  5387. if (cm) {
  5388. // Sync editor state
  5389. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5390. if (marker.collapsed)
  5391. { regChange(cm, from.line, to.line + 1); }
  5392. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5393. marker.attributes || marker.title)
  5394. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5395. if (marker.atomic) { reCheckSelection(cm.doc); }
  5396. signalLater(cm, "markerAdded", cm, marker);
  5397. }
  5398. return marker
  5399. }
  5400. // SHARED TEXTMARKERS
  5401. // A shared marker spans multiple linked documents. It is
  5402. // implemented as a meta-marker-object controlling multiple normal
  5403. // markers.
  5404. var SharedTextMarker = function(markers, primary) {
  5405. var this$1 = this;
  5406. this.markers = markers;
  5407. this.primary = primary;
  5408. for (var i = 0; i < markers.length; ++i)
  5409. { markers[i].parent = this$1; }
  5410. };
  5411. SharedTextMarker.prototype.clear = function () {
  5412. var this$1 = this;
  5413. if (this.explicitlyCleared) { return }
  5414. this.explicitlyCleared = true;
  5415. for (var i = 0; i < this.markers.length; ++i)
  5416. { this$1.markers[i].clear(); }
  5417. signalLater(this, "clear");
  5418. };
  5419. SharedTextMarker.prototype.find = function (side, lineObj) {
  5420. return this.primary.find(side, lineObj)
  5421. };
  5422. eventMixin(SharedTextMarker);
  5423. function markTextShared(doc, from, to, options, type) {
  5424. options = copyObj(options);
  5425. options.shared = false;
  5426. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5427. var widget = options.widgetNode;
  5428. linkedDocs(doc, function (doc) {
  5429. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5430. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5431. for (var i = 0; i < doc.linked.length; ++i)
  5432. { if (doc.linked[i].isParent) { return } }
  5433. primary = lst(markers);
  5434. });
  5435. return new SharedTextMarker(markers, primary)
  5436. }
  5437. function findSharedMarkers(doc) {
  5438. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5439. }
  5440. function copySharedMarkers(doc, markers) {
  5441. for (var i = 0; i < markers.length; i++) {
  5442. var marker = markers[i], pos = marker.find();
  5443. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5444. if (cmp(mFrom, mTo)) {
  5445. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5446. marker.markers.push(subMark);
  5447. subMark.parent = marker;
  5448. }
  5449. }
  5450. }
  5451. function detachSharedMarkers(markers) {
  5452. var loop = function ( i ) {
  5453. var marker = markers[i], linked = [marker.primary.doc];
  5454. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5455. for (var j = 0; j < marker.markers.length; j++) {
  5456. var subMarker = marker.markers[j];
  5457. if (indexOf(linked, subMarker.doc) == -1) {
  5458. subMarker.parent = null;
  5459. marker.markers.splice(j--, 1);
  5460. }
  5461. }
  5462. };
  5463. for (var i = 0; i < markers.length; i++) loop( i );
  5464. }
  5465. var nextDocId = 0;
  5466. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5467. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5468. if (firstLine == null) { firstLine = 0; }
  5469. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5470. this.first = firstLine;
  5471. this.scrollTop = this.scrollLeft = 0;
  5472. this.cantEdit = false;
  5473. this.cleanGeneration = 1;
  5474. this.modeFrontier = this.highlightFrontier = firstLine;
  5475. var start = Pos(firstLine, 0);
  5476. this.sel = simpleSelection(start);
  5477. this.history = new History(null);
  5478. this.id = ++nextDocId;
  5479. this.modeOption = mode;
  5480. this.lineSep = lineSep;
  5481. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5482. this.extend = false;
  5483. if (typeof text == "string") { text = this.splitLines(text); }
  5484. updateDoc(this, {from: start, to: start, text: text});
  5485. setSelection(this, simpleSelection(start), sel_dontScroll);
  5486. };
  5487. Doc.prototype = createObj(BranchChunk.prototype, {
  5488. constructor: Doc,
  5489. // Iterate over the document. Supports two forms -- with only one
  5490. // argument, it calls that for each line in the document. With
  5491. // three, it iterates over the range given by the first two (with
  5492. // the second being non-inclusive).
  5493. iter: function(from, to, op) {
  5494. if (op) { this.iterN(from - this.first, to - from, op); }
  5495. else { this.iterN(this.first, this.first + this.size, from); }
  5496. },
  5497. // Non-public interface for adding and removing lines.
  5498. insert: function(at, lines) {
  5499. var height = 0;
  5500. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5501. this.insertInner(at - this.first, lines, height);
  5502. },
  5503. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5504. // From here, the methods are part of the public interface. Most
  5505. // are also available from CodeMirror (editor) instances.
  5506. getValue: function(lineSep) {
  5507. var lines = getLines(this, this.first, this.first + this.size);
  5508. if (lineSep === false) { return lines }
  5509. return lines.join(lineSep || this.lineSeparator())
  5510. },
  5511. setValue: docMethodOp(function(code) {
  5512. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5513. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5514. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5515. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5516. setSelection(this, simpleSelection(top), sel_dontScroll);
  5517. }),
  5518. replaceRange: function(code, from, to, origin) {
  5519. from = clipPos(this, from);
  5520. to = to ? clipPos(this, to) : from;
  5521. replaceRange(this, code, from, to, origin);
  5522. },
  5523. getRange: function(from, to, lineSep) {
  5524. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5525. if (lineSep === false) { return lines }
  5526. return lines.join(lineSep || this.lineSeparator())
  5527. },
  5528. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5529. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5530. getLineNumber: function(line) {return lineNo(line)},
  5531. getLineHandleVisualStart: function(line) {
  5532. if (typeof line == "number") { line = getLine(this, line); }
  5533. return visualLine(line)
  5534. },
  5535. lineCount: function() {return this.size},
  5536. firstLine: function() {return this.first},
  5537. lastLine: function() {return this.first + this.size - 1},
  5538. clipPos: function(pos) {return clipPos(this, pos)},
  5539. getCursor: function(start) {
  5540. var range$$1 = this.sel.primary(), pos;
  5541. if (start == null || start == "head") { pos = range$$1.head; }
  5542. else if (start == "anchor") { pos = range$$1.anchor; }
  5543. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  5544. else { pos = range$$1.from(); }
  5545. return pos
  5546. },
  5547. listSelections: function() { return this.sel.ranges },
  5548. somethingSelected: function() {return this.sel.somethingSelected()},
  5549. setCursor: docMethodOp(function(line, ch, options) {
  5550. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5551. }),
  5552. setSelection: docMethodOp(function(anchor, head, options) {
  5553. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5554. }),
  5555. extendSelection: docMethodOp(function(head, other, options) {
  5556. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5557. }),
  5558. extendSelections: docMethodOp(function(heads, options) {
  5559. extendSelections(this, clipPosArray(this, heads), options);
  5560. }),
  5561. extendSelectionsBy: docMethodOp(function(f, options) {
  5562. var heads = map(this.sel.ranges, f);
  5563. extendSelections(this, clipPosArray(this, heads), options);
  5564. }),
  5565. setSelections: docMethodOp(function(ranges, primary, options) {
  5566. var this$1 = this;
  5567. if (!ranges.length) { return }
  5568. var out = [];
  5569. for (var i = 0; i < ranges.length; i++)
  5570. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5571. clipPos(this$1, ranges[i].head)); }
  5572. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5573. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5574. }),
  5575. addSelection: docMethodOp(function(anchor, head, options) {
  5576. var ranges = this.sel.ranges.slice(0);
  5577. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5578. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5579. }),
  5580. getSelection: function(lineSep) {
  5581. var this$1 = this;
  5582. var ranges = this.sel.ranges, lines;
  5583. for (var i = 0; i < ranges.length; i++) {
  5584. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5585. lines = lines ? lines.concat(sel) : sel;
  5586. }
  5587. if (lineSep === false) { return lines }
  5588. else { return lines.join(lineSep || this.lineSeparator()) }
  5589. },
  5590. getSelections: function(lineSep) {
  5591. var this$1 = this;
  5592. var parts = [], ranges = this.sel.ranges;
  5593. for (var i = 0; i < ranges.length; i++) {
  5594. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5595. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  5596. parts[i] = sel;
  5597. }
  5598. return parts
  5599. },
  5600. replaceSelection: function(code, collapse, origin) {
  5601. var dup = [];
  5602. for (var i = 0; i < this.sel.ranges.length; i++)
  5603. { dup[i] = code; }
  5604. this.replaceSelections(dup, collapse, origin || "+input");
  5605. },
  5606. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5607. var this$1 = this;
  5608. var changes = [], sel = this.sel;
  5609. for (var i = 0; i < sel.ranges.length; i++) {
  5610. var range$$1 = sel.ranges[i];
  5611. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  5612. }
  5613. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5614. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5615. { makeChange(this$1, changes[i$1]); }
  5616. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5617. else if (this.cm) { ensureCursorVisible(this.cm); }
  5618. }),
  5619. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5620. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5621. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5622. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5623. setExtending: function(val) {this.extend = val;},
  5624. getExtending: function() {return this.extend},
  5625. historySize: function() {
  5626. var hist = this.history, done = 0, undone = 0;
  5627. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5628. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5629. return {undo: done, redo: undone}
  5630. },
  5631. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  5632. markClean: function() {
  5633. this.cleanGeneration = this.changeGeneration(true);
  5634. },
  5635. changeGeneration: function(forceSplit) {
  5636. if (forceSplit)
  5637. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5638. return this.history.generation
  5639. },
  5640. isClean: function (gen) {
  5641. return this.history.generation == (gen || this.cleanGeneration)
  5642. },
  5643. getHistory: function() {
  5644. return {done: copyHistoryArray(this.history.done),
  5645. undone: copyHistoryArray(this.history.undone)}
  5646. },
  5647. setHistory: function(histData) {
  5648. var hist = this.history = new History(this.history.maxGeneration);
  5649. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5650. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5651. },
  5652. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5653. return changeLine(this, line, "gutter", function (line) {
  5654. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5655. markers[gutterID] = value;
  5656. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5657. return true
  5658. })
  5659. }),
  5660. clearGutter: docMethodOp(function(gutterID) {
  5661. var this$1 = this;
  5662. this.iter(function (line) {
  5663. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5664. changeLine(this$1, line, "gutter", function () {
  5665. line.gutterMarkers[gutterID] = null;
  5666. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5667. return true
  5668. });
  5669. }
  5670. });
  5671. }),
  5672. lineInfo: function(line) {
  5673. var n;
  5674. if (typeof line == "number") {
  5675. if (!isLine(this, line)) { return null }
  5676. n = line;
  5677. line = getLine(this, line);
  5678. if (!line) { return null }
  5679. } else {
  5680. n = lineNo(line);
  5681. if (n == null) { return null }
  5682. }
  5683. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5684. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5685. widgets: line.widgets}
  5686. },
  5687. addLineClass: docMethodOp(function(handle, where, cls) {
  5688. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5689. var prop = where == "text" ? "textClass"
  5690. : where == "background" ? "bgClass"
  5691. : where == "gutter" ? "gutterClass" : "wrapClass";
  5692. if (!line[prop]) { line[prop] = cls; }
  5693. else if (classTest(cls).test(line[prop])) { return false }
  5694. else { line[prop] += " " + cls; }
  5695. return true
  5696. })
  5697. }),
  5698. removeLineClass: docMethodOp(function(handle, where, cls) {
  5699. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5700. var prop = where == "text" ? "textClass"
  5701. : where == "background" ? "bgClass"
  5702. : where == "gutter" ? "gutterClass" : "wrapClass";
  5703. var cur = line[prop];
  5704. if (!cur) { return false }
  5705. else if (cls == null) { line[prop] = null; }
  5706. else {
  5707. var found = cur.match(classTest(cls));
  5708. if (!found) { return false }
  5709. var end = found.index + found[0].length;
  5710. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5711. }
  5712. return true
  5713. })
  5714. }),
  5715. addLineWidget: docMethodOp(function(handle, node, options) {
  5716. return addLineWidget(this, handle, node, options)
  5717. }),
  5718. removeLineWidget: function(widget) { widget.clear(); },
  5719. markText: function(from, to, options) {
  5720. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5721. },
  5722. setBookmark: function(pos, options) {
  5723. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5724. insertLeft: options && options.insertLeft,
  5725. clearWhenEmpty: false, shared: options && options.shared,
  5726. handleMouseEvents: options && options.handleMouseEvents};
  5727. pos = clipPos(this, pos);
  5728. return markText(this, pos, pos, realOpts, "bookmark")
  5729. },
  5730. findMarksAt: function(pos) {
  5731. pos = clipPos(this, pos);
  5732. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5733. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5734. var span = spans[i];
  5735. if ((span.from == null || span.from <= pos.ch) &&
  5736. (span.to == null || span.to >= pos.ch))
  5737. { markers.push(span.marker.parent || span.marker); }
  5738. } }
  5739. return markers
  5740. },
  5741. findMarks: function(from, to, filter) {
  5742. from = clipPos(this, from); to = clipPos(this, to);
  5743. var found = [], lineNo$$1 = from.line;
  5744. this.iter(from.line, to.line + 1, function (line) {
  5745. var spans = line.markedSpans;
  5746. if (spans) { for (var i = 0; i < spans.length; i++) {
  5747. var span = spans[i];
  5748. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  5749. span.from == null && lineNo$$1 != from.line ||
  5750. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  5751. (!filter || filter(span.marker)))
  5752. { found.push(span.marker.parent || span.marker); }
  5753. } }
  5754. ++lineNo$$1;
  5755. });
  5756. return found
  5757. },
  5758. getAllMarks: function() {
  5759. var markers = [];
  5760. this.iter(function (line) {
  5761. var sps = line.markedSpans;
  5762. if (sps) { for (var i = 0; i < sps.length; ++i)
  5763. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5764. });
  5765. return markers
  5766. },
  5767. posFromIndex: function(off) {
  5768. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  5769. this.iter(function (line) {
  5770. var sz = line.text.length + sepSize;
  5771. if (sz > off) { ch = off; return true }
  5772. off -= sz;
  5773. ++lineNo$$1;
  5774. });
  5775. return clipPos(this, Pos(lineNo$$1, ch))
  5776. },
  5777. indexFromPos: function (coords) {
  5778. coords = clipPos(this, coords);
  5779. var index = coords.ch;
  5780. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5781. var sepSize = this.lineSeparator().length;
  5782. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5783. index += line.text.length + sepSize;
  5784. });
  5785. return index
  5786. },
  5787. copy: function(copyHistory) {
  5788. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5789. this.modeOption, this.first, this.lineSep, this.direction);
  5790. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5791. doc.sel = this.sel;
  5792. doc.extend = false;
  5793. if (copyHistory) {
  5794. doc.history.undoDepth = this.history.undoDepth;
  5795. doc.setHistory(this.getHistory());
  5796. }
  5797. return doc
  5798. },
  5799. linkedDoc: function(options) {
  5800. if (!options) { options = {}; }
  5801. var from = this.first, to = this.first + this.size;
  5802. if (options.from != null && options.from > from) { from = options.from; }
  5803. if (options.to != null && options.to < to) { to = options.to; }
  5804. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5805. if (options.sharedHist) { copy.history = this.history
  5806. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5807. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5808. copySharedMarkers(copy, findSharedMarkers(this));
  5809. return copy
  5810. },
  5811. unlinkDoc: function(other) {
  5812. var this$1 = this;
  5813. if (other instanceof CodeMirror) { other = other.doc; }
  5814. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5815. var link = this$1.linked[i];
  5816. if (link.doc != other) { continue }
  5817. this$1.linked.splice(i, 1);
  5818. other.unlinkDoc(this$1);
  5819. detachSharedMarkers(findSharedMarkers(this$1));
  5820. break
  5821. } }
  5822. // If the histories were shared, split them again
  5823. if (other.history == this.history) {
  5824. var splitIds = [other.id];
  5825. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5826. other.history = new History(null);
  5827. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5828. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5829. }
  5830. },
  5831. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5832. getMode: function() {return this.mode},
  5833. getEditor: function() {return this.cm},
  5834. splitLines: function(str) {
  5835. if (this.lineSep) { return str.split(this.lineSep) }
  5836. return splitLinesAuto(str)
  5837. },
  5838. lineSeparator: function() { return this.lineSep || "\n" },
  5839. setDirection: docMethodOp(function (dir) {
  5840. if (dir != "rtl") { dir = "ltr"; }
  5841. if (dir == this.direction) { return }
  5842. this.direction = dir;
  5843. this.iter(function (line) { return line.order = null; });
  5844. if (this.cm) { directionChanged(this.cm); }
  5845. })
  5846. });
  5847. // Public alias.
  5848. Doc.prototype.eachLine = Doc.prototype.iter;
  5849. // Kludge to work around strange IE behavior where it'll sometimes
  5850. // re-fire a series of drag-related events right after the drop (#1551)
  5851. var lastDrop = 0;
  5852. function onDrop(e) {
  5853. var cm = this;
  5854. clearDragCursor(cm);
  5855. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5856. { return }
  5857. e_preventDefault(e);
  5858. if (ie) { lastDrop = +new Date; }
  5859. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5860. if (!pos || cm.isReadOnly()) { return }
  5861. // Might be a file drop, in which case we simply extract the text
  5862. // and insert it.
  5863. if (files && files.length && window.FileReader && window.File) {
  5864. var n = files.length, text = Array(n), read = 0;
  5865. var loadFile = function (file, i) {
  5866. if (cm.options.allowDropFileTypes &&
  5867. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5868. { return }
  5869. var reader = new FileReader;
  5870. reader.onload = operation(cm, function () {
  5871. var content = reader.result;
  5872. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  5873. text[i] = content;
  5874. if (++read == n) {
  5875. pos = clipPos(cm.doc, pos);
  5876. var change = {from: pos, to: pos,
  5877. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5878. origin: "paste"};
  5879. makeChange(cm.doc, change);
  5880. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  5881. }
  5882. });
  5883. reader.readAsText(file);
  5884. };
  5885. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  5886. } else { // Normal drop
  5887. // Don't do a replace if the drop happened inside of the selected text.
  5888. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5889. cm.state.draggingText(e);
  5890. // Ensure the editor is re-focused
  5891. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5892. return
  5893. }
  5894. try {
  5895. var text$1 = e.dataTransfer.getData("Text");
  5896. if (text$1) {
  5897. var selected;
  5898. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5899. { selected = cm.listSelections(); }
  5900. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5901. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5902. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5903. cm.replaceSelection(text$1, "around", "paste");
  5904. cm.display.input.focus();
  5905. }
  5906. }
  5907. catch(e){}
  5908. }
  5909. }
  5910. function onDragStart(cm, e) {
  5911. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5912. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5913. e.dataTransfer.setData("Text", cm.getSelection());
  5914. e.dataTransfer.effectAllowed = "copyMove";
  5915. // Use dummy image instead of default browsers image.
  5916. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5917. if (e.dataTransfer.setDragImage && !safari) {
  5918. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5919. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5920. if (presto) {
  5921. img.width = img.height = 1;
  5922. cm.display.wrapper.appendChild(img);
  5923. // Force a relayout, or Opera won't use our image for some obscure reason
  5924. img._top = img.offsetTop;
  5925. }
  5926. e.dataTransfer.setDragImage(img, 0, 0);
  5927. if (presto) { img.parentNode.removeChild(img); }
  5928. }
  5929. }
  5930. function onDragOver(cm, e) {
  5931. var pos = posFromMouse(cm, e);
  5932. if (!pos) { return }
  5933. var frag = document.createDocumentFragment();
  5934. drawSelectionCursor(cm, pos, frag);
  5935. if (!cm.display.dragCursor) {
  5936. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5937. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5938. }
  5939. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5940. }
  5941. function clearDragCursor(cm) {
  5942. if (cm.display.dragCursor) {
  5943. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5944. cm.display.dragCursor = null;
  5945. }
  5946. }
  5947. // These must be handled carefully, because naively registering a
  5948. // handler for each editor will cause the editors to never be
  5949. // garbage collected.
  5950. function forEachCodeMirror(f) {
  5951. if (!document.getElementsByClassName) { return }
  5952. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  5953. for (var i = 0; i < byClass.length; i++) {
  5954. var cm = byClass[i].CodeMirror;
  5955. if (cm) { editors.push(cm); }
  5956. }
  5957. if (editors.length) { editors[0].operation(function () {
  5958. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  5959. }); }
  5960. }
  5961. var globalsRegistered = false;
  5962. function ensureGlobalHandlers() {
  5963. if (globalsRegistered) { return }
  5964. registerGlobalHandlers();
  5965. globalsRegistered = true;
  5966. }
  5967. function registerGlobalHandlers() {
  5968. // When the window resizes, we need to refresh active editors.
  5969. var resizeTimer;
  5970. on(window, "resize", function () {
  5971. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5972. resizeTimer = null;
  5973. forEachCodeMirror(onResize);
  5974. }, 100); }
  5975. });
  5976. // When the window loses focus, we want to show the editor as blurred
  5977. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  5978. }
  5979. // Called when the window resizes
  5980. function onResize(cm) {
  5981. var d = cm.display;
  5982. // Might be a text scaling operation, clear size caches.
  5983. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5984. d.scrollbarsClipped = false;
  5985. cm.setSize();
  5986. }
  5987. var keyNames = {
  5988. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5989. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5990. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5991. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5992. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  5993. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5994. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5995. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5996. };
  5997. // Number keys
  5998. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  5999. // Alphabetic keys
  6000. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6001. // Function keys
  6002. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6003. var keyMap = {};
  6004. keyMap.basic = {
  6005. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6006. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6007. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6008. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6009. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6010. "Esc": "singleSelection"
  6011. };
  6012. // Note that the save and find-related commands aren't defined by
  6013. // default. User code or addons can define them. Unknown commands
  6014. // are simply ignored.
  6015. keyMap.pcDefault = {
  6016. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6017. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6018. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6019. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6020. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6021. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6022. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6023. "fallthrough": "basic"
  6024. };
  6025. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6026. keyMap.emacsy = {
  6027. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6028. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  6029. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  6030. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  6031. "Ctrl-O": "openLine"
  6032. };
  6033. keyMap.macDefault = {
  6034. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6035. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6036. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6037. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6038. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6039. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6040. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6041. "fallthrough": ["basic", "emacsy"]
  6042. };
  6043. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6044. // KEYMAP DISPATCH
  6045. function normalizeKeyName(name) {
  6046. var parts = name.split(/-(?!$)/);
  6047. name = parts[parts.length - 1];
  6048. var alt, ctrl, shift, cmd;
  6049. for (var i = 0; i < parts.length - 1; i++) {
  6050. var mod = parts[i];
  6051. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6052. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6053. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6054. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6055. else { throw new Error("Unrecognized modifier name: " + mod) }
  6056. }
  6057. if (alt) { name = "Alt-" + name; }
  6058. if (ctrl) { name = "Ctrl-" + name; }
  6059. if (cmd) { name = "Cmd-" + name; }
  6060. if (shift) { name = "Shift-" + name; }
  6061. return name
  6062. }
  6063. // This is a kludge to keep keymaps mostly working as raw objects
  6064. // (backwards compatibility) while at the same time support features
  6065. // like normalization and multi-stroke key bindings. It compiles a
  6066. // new normalized keymap, and then updates the old object to reflect
  6067. // this.
  6068. function normalizeKeyMap(keymap) {
  6069. var copy = {};
  6070. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6071. var value = keymap[keyname];
  6072. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6073. if (value == "...") { delete keymap[keyname]; continue }
  6074. var keys = map(keyname.split(" "), normalizeKeyName);
  6075. for (var i = 0; i < keys.length; i++) {
  6076. var val = (void 0), name = (void 0);
  6077. if (i == keys.length - 1) {
  6078. name = keys.join(" ");
  6079. val = value;
  6080. } else {
  6081. name = keys.slice(0, i + 1).join(" ");
  6082. val = "...";
  6083. }
  6084. var prev = copy[name];
  6085. if (!prev) { copy[name] = val; }
  6086. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6087. }
  6088. delete keymap[keyname];
  6089. } }
  6090. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6091. return keymap
  6092. }
  6093. function lookupKey(key, map$$1, handle, context) {
  6094. map$$1 = getKeyMap(map$$1);
  6095. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  6096. if (found === false) { return "nothing" }
  6097. if (found === "...") { return "multi" }
  6098. if (found != null && handle(found)) { return "handled" }
  6099. if (map$$1.fallthrough) {
  6100. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  6101. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  6102. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  6103. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  6104. if (result) { return result }
  6105. }
  6106. }
  6107. }
  6108. // Modifier key presses don't count as 'real' key presses for the
  6109. // purpose of keymap fallthrough.
  6110. function isModifierKey(value) {
  6111. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6112. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6113. }
  6114. function addModifierNames(name, event, noShift) {
  6115. var base = name;
  6116. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6117. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6118. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  6119. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6120. return name
  6121. }
  6122. // Look up the name of a key as indicated by an event object.
  6123. function keyName(event, noShift) {
  6124. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6125. var name = keyNames[event.keyCode];
  6126. if (name == null || event.altGraphKey) { return false }
  6127. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6128. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6129. if (event.keyCode == 3 && event.code) { name = event.code; }
  6130. return addModifierNames(name, event, noShift)
  6131. }
  6132. function getKeyMap(val) {
  6133. return typeof val == "string" ? keyMap[val] : val
  6134. }
  6135. // Helper for deleting text near the selection(s), used to implement
  6136. // backspace, delete, and similar functionality.
  6137. function deleteNearSelection(cm, compute) {
  6138. var ranges = cm.doc.sel.ranges, kill = [];
  6139. // Build up a set of ranges to kill first, merging overlapping
  6140. // ranges.
  6141. for (var i = 0; i < ranges.length; i++) {
  6142. var toKill = compute(ranges[i]);
  6143. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6144. var replaced = kill.pop();
  6145. if (cmp(replaced.from, toKill.from) < 0) {
  6146. toKill.from = replaced.from;
  6147. break
  6148. }
  6149. }
  6150. kill.push(toKill);
  6151. }
  6152. // Next, remove those actual ranges.
  6153. runInOp(cm, function () {
  6154. for (var i = kill.length - 1; i >= 0; i--)
  6155. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6156. ensureCursorVisible(cm);
  6157. });
  6158. }
  6159. function moveCharLogically(line, ch, dir) {
  6160. var target = skipExtendingChars(line.text, ch + dir, dir);
  6161. return target < 0 || target > line.text.length ? null : target
  6162. }
  6163. function moveLogically(line, start, dir) {
  6164. var ch = moveCharLogically(line, start.ch, dir);
  6165. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6166. }
  6167. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6168. if (visually) {
  6169. var order = getOrder(lineObj, cm.doc.direction);
  6170. if (order) {
  6171. var part = dir < 0 ? lst(order) : order[0];
  6172. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6173. var sticky = moveInStorageOrder ? "after" : "before";
  6174. var ch;
  6175. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6176. // it could be that the last bidi part is not on the last visual line,
  6177. // since visual lines contain content order-consecutive chunks.
  6178. // Thus, in rtl, we are looking for the first (content-order) character
  6179. // in the rtl chunk that is on the last line (that is, the same line
  6180. // as the last (content-order) character).
  6181. if (part.level > 0 || cm.doc.direction == "rtl") {
  6182. var prep = prepareMeasureForLine(cm, lineObj);
  6183. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6184. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6185. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6186. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6187. } else { ch = dir < 0 ? part.to : part.from; }
  6188. return new Pos(lineNo, ch, sticky)
  6189. }
  6190. }
  6191. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6192. }
  6193. function moveVisually(cm, line, start, dir) {
  6194. var bidi = getOrder(line, cm.doc.direction);
  6195. if (!bidi) { return moveLogically(line, start, dir) }
  6196. if (start.ch >= line.text.length) {
  6197. start.ch = line.text.length;
  6198. start.sticky = "before";
  6199. } else if (start.ch <= 0) {
  6200. start.ch = 0;
  6201. start.sticky = "after";
  6202. }
  6203. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6204. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6205. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6206. // nothing interesting happens.
  6207. return moveLogically(line, start, dir)
  6208. }
  6209. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6210. var prep;
  6211. var getWrappedLineExtent = function (ch) {
  6212. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6213. prep = prep || prepareMeasureForLine(cm, line);
  6214. return wrappedLineExtentChar(cm, line, prep, ch)
  6215. };
  6216. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6217. if (cm.doc.direction == "rtl" || part.level == 1) {
  6218. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6219. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6220. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6221. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6222. var sticky = moveInStorageOrder ? "before" : "after";
  6223. return new Pos(start.line, ch, sticky)
  6224. }
  6225. }
  6226. // Case 3: Could not move within this bidi part in this visual line, so leave
  6227. // the current bidi part
  6228. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6229. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6230. ? new Pos(start.line, mv(ch, 1), "before")
  6231. : new Pos(start.line, ch, "after"); };
  6232. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6233. var part = bidi[partPos];
  6234. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6235. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6236. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6237. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6238. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6239. }
  6240. };
  6241. // Case 3a: Look for other bidi parts on the same visual line
  6242. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6243. if (res) { return res }
  6244. // Case 3b: Look for other bidi parts on the next visual line
  6245. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6246. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6247. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6248. if (res) { return res }
  6249. }
  6250. // Case 4: Nowhere to move
  6251. return null
  6252. }
  6253. // Commands are parameter-less actions that can be performed on an
  6254. // editor, mostly used for keybindings.
  6255. var commands = {
  6256. selectAll: selectAll,
  6257. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6258. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6259. if (range.empty()) {
  6260. var len = getLine(cm.doc, range.head.line).text.length;
  6261. if (range.head.ch == len && range.head.line < cm.lastLine())
  6262. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6263. else
  6264. { return {from: range.head, to: Pos(range.head.line, len)} }
  6265. } else {
  6266. return {from: range.from(), to: range.to()}
  6267. }
  6268. }); },
  6269. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6270. from: Pos(range.from().line, 0),
  6271. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6272. }); }); },
  6273. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6274. from: Pos(range.from().line, 0), to: range.from()
  6275. }); }); },
  6276. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6277. var top = cm.charCoords(range.head, "div").top + 5;
  6278. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6279. return {from: leftPos, to: range.from()}
  6280. }); },
  6281. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6282. var top = cm.charCoords(range.head, "div").top + 5;
  6283. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6284. return {from: range.from(), to: rightPos }
  6285. }); },
  6286. undo: function (cm) { return cm.undo(); },
  6287. redo: function (cm) { return cm.redo(); },
  6288. undoSelection: function (cm) { return cm.undoSelection(); },
  6289. redoSelection: function (cm) { return cm.redoSelection(); },
  6290. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6291. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6292. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6293. {origin: "+move", bias: 1}
  6294. ); },
  6295. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6296. {origin: "+move", bias: 1}
  6297. ); },
  6298. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6299. {origin: "+move", bias: -1}
  6300. ); },
  6301. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6302. var top = cm.cursorCoords(range.head, "div").top + 5;
  6303. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6304. }, sel_move); },
  6305. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6306. var top = cm.cursorCoords(range.head, "div").top + 5;
  6307. return cm.coordsChar({left: 0, top: top}, "div")
  6308. }, sel_move); },
  6309. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6310. var top = cm.cursorCoords(range.head, "div").top + 5;
  6311. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6312. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6313. return pos
  6314. }, sel_move); },
  6315. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6316. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6317. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6318. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6319. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6320. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6321. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6322. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6323. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6324. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6325. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6326. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6327. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6328. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6329. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6330. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6331. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6332. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6333. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6334. indentMore: function (cm) { return cm.indentSelection("add"); },
  6335. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6336. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6337. insertSoftTab: function (cm) {
  6338. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6339. for (var i = 0; i < ranges.length; i++) {
  6340. var pos = ranges[i].from();
  6341. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6342. spaces.push(spaceStr(tabSize - col % tabSize));
  6343. }
  6344. cm.replaceSelections(spaces);
  6345. },
  6346. defaultTab: function (cm) {
  6347. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6348. else { cm.execCommand("insertTab"); }
  6349. },
  6350. // Swap the two chars left and right of each selection's head.
  6351. // Move cursor behind the two swapped characters afterwards.
  6352. //
  6353. // Doesn't consider line feeds a character.
  6354. // Doesn't scan more than one line above to find a character.
  6355. // Doesn't do anything on an empty line.
  6356. // Doesn't do anything with non-empty selections.
  6357. transposeChars: function (cm) { return runInOp(cm, function () {
  6358. var ranges = cm.listSelections(), newSel = [];
  6359. for (var i = 0; i < ranges.length; i++) {
  6360. if (!ranges[i].empty()) { continue }
  6361. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6362. if (line) {
  6363. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6364. if (cur.ch > 0) {
  6365. cur = new Pos(cur.line, cur.ch + 1);
  6366. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6367. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6368. } else if (cur.line > cm.doc.first) {
  6369. var prev = getLine(cm.doc, cur.line - 1).text;
  6370. if (prev) {
  6371. cur = new Pos(cur.line, 1);
  6372. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6373. prev.charAt(prev.length - 1),
  6374. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6375. }
  6376. }
  6377. }
  6378. newSel.push(new Range(cur, cur));
  6379. }
  6380. cm.setSelections(newSel);
  6381. }); },
  6382. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6383. var sels = cm.listSelections();
  6384. for (var i = sels.length - 1; i >= 0; i--)
  6385. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6386. sels = cm.listSelections();
  6387. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6388. { cm.indentLine(sels[i$1].from().line, null, true); }
  6389. ensureCursorVisible(cm);
  6390. }); },
  6391. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6392. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6393. };
  6394. function lineStart(cm, lineN) {
  6395. var line = getLine(cm.doc, lineN);
  6396. var visual = visualLine(line);
  6397. if (visual != line) { lineN = lineNo(visual); }
  6398. return endOfLine(true, cm, visual, lineN, 1)
  6399. }
  6400. function lineEnd(cm, lineN) {
  6401. var line = getLine(cm.doc, lineN);
  6402. var visual = visualLineEnd(line);
  6403. if (visual != line) { lineN = lineNo(visual); }
  6404. return endOfLine(true, cm, line, lineN, -1)
  6405. }
  6406. function lineStartSmart(cm, pos) {
  6407. var start = lineStart(cm, pos.line);
  6408. var line = getLine(cm.doc, start.line);
  6409. var order = getOrder(line, cm.doc.direction);
  6410. if (!order || order[0].level == 0) {
  6411. var firstNonWS = Math.max(0, line.text.search(/\S/));
  6412. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6413. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6414. }
  6415. return start
  6416. }
  6417. // Run a handler that was bound to a key.
  6418. function doHandleBinding(cm, bound, dropShift) {
  6419. if (typeof bound == "string") {
  6420. bound = commands[bound];
  6421. if (!bound) { return false }
  6422. }
  6423. // Ensure previous input has been read, so that the handler sees a
  6424. // consistent view of the document
  6425. cm.display.input.ensurePolled();
  6426. var prevShift = cm.display.shift, done = false;
  6427. try {
  6428. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6429. if (dropShift) { cm.display.shift = false; }
  6430. done = bound(cm) != Pass;
  6431. } finally {
  6432. cm.display.shift = prevShift;
  6433. cm.state.suppressEdits = false;
  6434. }
  6435. return done
  6436. }
  6437. function lookupKeyForEditor(cm, name, handle) {
  6438. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6439. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6440. if (result) { return result }
  6441. }
  6442. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6443. || lookupKey(name, cm.options.keyMap, handle, cm)
  6444. }
  6445. // Note that, despite the name, this function is also used to check
  6446. // for bound mouse clicks.
  6447. var stopSeq = new Delayed;
  6448. function dispatchKey(cm, name, e, handle) {
  6449. var seq = cm.state.keySeq;
  6450. if (seq) {
  6451. if (isModifierKey(name)) { return "handled" }
  6452. if (/\'$/.test(name))
  6453. { cm.state.keySeq = null; }
  6454. else
  6455. { stopSeq.set(50, function () {
  6456. if (cm.state.keySeq == seq) {
  6457. cm.state.keySeq = null;
  6458. cm.display.input.reset();
  6459. }
  6460. }); }
  6461. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6462. }
  6463. return dispatchKeyInner(cm, name, e, handle)
  6464. }
  6465. function dispatchKeyInner(cm, name, e, handle) {
  6466. var result = lookupKeyForEditor(cm, name, handle);
  6467. if (result == "multi")
  6468. { cm.state.keySeq = name; }
  6469. if (result == "handled")
  6470. { signalLater(cm, "keyHandled", cm, name, e); }
  6471. if (result == "handled" || result == "multi") {
  6472. e_preventDefault(e);
  6473. restartBlink(cm);
  6474. }
  6475. return !!result
  6476. }
  6477. // Handle a key from the keydown event.
  6478. function handleKeyBinding(cm, e) {
  6479. var name = keyName(e, true);
  6480. if (!name) { return false }
  6481. if (e.shiftKey && !cm.state.keySeq) {
  6482. // First try to resolve full name (including 'Shift-'). Failing
  6483. // that, see if there is a cursor-motion command (starting with
  6484. // 'go') bound to the keyname without 'Shift-'.
  6485. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6486. || dispatchKey(cm, name, e, function (b) {
  6487. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6488. { return doHandleBinding(cm, b) }
  6489. })
  6490. } else {
  6491. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6492. }
  6493. }
  6494. // Handle a key from the keypress event
  6495. function handleCharBinding(cm, e, ch) {
  6496. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6497. }
  6498. var lastStoppedKey = null;
  6499. function onKeyDown(e) {
  6500. var cm = this;
  6501. cm.curOp.focus = activeElt();
  6502. if (signalDOMEvent(cm, e)) { return }
  6503. // IE does strange things with escape.
  6504. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6505. var code = e.keyCode;
  6506. cm.display.shift = code == 16 || e.shiftKey;
  6507. var handled = handleKeyBinding(cm, e);
  6508. if (presto) {
  6509. lastStoppedKey = handled ? code : null;
  6510. // Opera has no cut event... we try to at least catch the key combo
  6511. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6512. { cm.replaceSelection("", null, "cut"); }
  6513. }
  6514. // Turn mouse into crosshair when Alt is held on Mac.
  6515. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6516. { showCrossHair(cm); }
  6517. }
  6518. function showCrossHair(cm) {
  6519. var lineDiv = cm.display.lineDiv;
  6520. addClass(lineDiv, "CodeMirror-crosshair");
  6521. function up(e) {
  6522. if (e.keyCode == 18 || !e.altKey) {
  6523. rmClass(lineDiv, "CodeMirror-crosshair");
  6524. off(document, "keyup", up);
  6525. off(document, "mouseover", up);
  6526. }
  6527. }
  6528. on(document, "keyup", up);
  6529. on(document, "mouseover", up);
  6530. }
  6531. function onKeyUp(e) {
  6532. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6533. signalDOMEvent(this, e);
  6534. }
  6535. function onKeyPress(e) {
  6536. var cm = this;
  6537. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6538. var keyCode = e.keyCode, charCode = e.charCode;
  6539. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6540. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6541. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6542. // Some browsers fire keypress events for backspace
  6543. if (ch == "\x08") { return }
  6544. if (handleCharBinding(cm, e, ch)) { return }
  6545. cm.display.input.onKeyPress(e);
  6546. }
  6547. var DOUBLECLICK_DELAY = 400;
  6548. var PastClick = function(time, pos, button) {
  6549. this.time = time;
  6550. this.pos = pos;
  6551. this.button = button;
  6552. };
  6553. PastClick.prototype.compare = function (time, pos, button) {
  6554. return this.time + DOUBLECLICK_DELAY > time &&
  6555. cmp(pos, this.pos) == 0 && button == this.button
  6556. };
  6557. var lastClick, lastDoubleClick;
  6558. function clickRepeat(pos, button) {
  6559. var now = +new Date;
  6560. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6561. lastClick = lastDoubleClick = null;
  6562. return "triple"
  6563. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6564. lastDoubleClick = new PastClick(now, pos, button);
  6565. lastClick = null;
  6566. return "double"
  6567. } else {
  6568. lastClick = new PastClick(now, pos, button);
  6569. lastDoubleClick = null;
  6570. return "single"
  6571. }
  6572. }
  6573. // A mouse down can be a single click, double click, triple click,
  6574. // start of selection drag, start of text drag, new cursor
  6575. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6576. // middle-click-paste. Or it might be a click on something we should
  6577. // not interfere with, such as a scrollbar or widget.
  6578. function onMouseDown(e) {
  6579. var cm = this, display = cm.display;
  6580. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6581. display.input.ensurePolled();
  6582. display.shift = e.shiftKey;
  6583. if (eventInWidget(display, e)) {
  6584. if (!webkit) {
  6585. // Briefly turn off draggability, to allow widgets to do
  6586. // normal dragging things.
  6587. display.scroller.draggable = false;
  6588. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6589. }
  6590. return
  6591. }
  6592. if (clickInGutter(cm, e)) { return }
  6593. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6594. window.focus();
  6595. // #3261: make sure, that we're not starting a second selection
  6596. if (button == 1 && cm.state.selectingText)
  6597. { cm.state.selectingText(e); }
  6598. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6599. if (button == 1) {
  6600. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6601. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6602. } else if (button == 2) {
  6603. if (pos) { extendSelection(cm.doc, pos); }
  6604. setTimeout(function () { return display.input.focus(); }, 20);
  6605. } else if (button == 3) {
  6606. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6607. else { delayBlurEvent(cm); }
  6608. }
  6609. }
  6610. function handleMappedButton(cm, button, pos, repeat, event) {
  6611. var name = "Click";
  6612. if (repeat == "double") { name = "Double" + name; }
  6613. else if (repeat == "triple") { name = "Triple" + name; }
  6614. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6615. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6616. if (typeof bound == "string") { bound = commands[bound]; }
  6617. if (!bound) { return false }
  6618. var done = false;
  6619. try {
  6620. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6621. done = bound(cm, pos) != Pass;
  6622. } finally {
  6623. cm.state.suppressEdits = false;
  6624. }
  6625. return done
  6626. })
  6627. }
  6628. function configureMouse(cm, repeat, event) {
  6629. var option = cm.getOption("configureMouse");
  6630. var value = option ? option(cm, repeat, event) : {};
  6631. if (value.unit == null) {
  6632. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6633. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6634. }
  6635. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6636. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6637. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6638. return value
  6639. }
  6640. function leftButtonDown(cm, pos, repeat, event) {
  6641. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6642. else { cm.curOp.focus = activeElt(); }
  6643. var behavior = configureMouse(cm, repeat, event);
  6644. var sel = cm.doc.sel, contained;
  6645. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6646. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6647. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6648. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6649. { leftButtonStartDrag(cm, event, pos, behavior); }
  6650. else
  6651. { leftButtonSelect(cm, event, pos, behavior); }
  6652. }
  6653. // Start a text drag. When it ends, see if any dragging actually
  6654. // happen, and treat as a click if it didn't.
  6655. function leftButtonStartDrag(cm, event, pos, behavior) {
  6656. var display = cm.display, moved = false;
  6657. var dragEnd = operation(cm, function (e) {
  6658. if (webkit) { display.scroller.draggable = false; }
  6659. cm.state.draggingText = false;
  6660. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6661. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6662. off(display.scroller, "dragstart", dragStart);
  6663. off(display.scroller, "drop", dragEnd);
  6664. if (!moved) {
  6665. e_preventDefault(e);
  6666. if (!behavior.addNew)
  6667. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6668. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6669. if (webkit || ie && ie_version == 9)
  6670. { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }
  6671. else
  6672. { display.input.focus(); }
  6673. }
  6674. });
  6675. var mouseMove = function(e2) {
  6676. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6677. };
  6678. var dragStart = function () { return moved = true; };
  6679. // Let the drag handler handle this.
  6680. if (webkit) { display.scroller.draggable = true; }
  6681. cm.state.draggingText = dragEnd;
  6682. dragEnd.copy = !behavior.moveOnDrag;
  6683. // IE's approach to draggable
  6684. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6685. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6686. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6687. on(display.scroller, "dragstart", dragStart);
  6688. on(display.scroller, "drop", dragEnd);
  6689. delayBlurEvent(cm);
  6690. setTimeout(function () { return display.input.focus(); }, 20);
  6691. }
  6692. function rangeForUnit(cm, pos, unit) {
  6693. if (unit == "char") { return new Range(pos, pos) }
  6694. if (unit == "word") { return cm.findWordAt(pos) }
  6695. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6696. var result = unit(cm, pos);
  6697. return new Range(result.from, result.to)
  6698. }
  6699. // Normal selection, as opposed to text dragging.
  6700. function leftButtonSelect(cm, event, start, behavior) {
  6701. var display = cm.display, doc = cm.doc;
  6702. e_preventDefault(event);
  6703. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6704. if (behavior.addNew && !behavior.extend) {
  6705. ourIndex = doc.sel.contains(start);
  6706. if (ourIndex > -1)
  6707. { ourRange = ranges[ourIndex]; }
  6708. else
  6709. { ourRange = new Range(start, start); }
  6710. } else {
  6711. ourRange = doc.sel.primary();
  6712. ourIndex = doc.sel.primIndex;
  6713. }
  6714. if (behavior.unit == "rectangle") {
  6715. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6716. start = posFromMouse(cm, event, true, true);
  6717. ourIndex = -1;
  6718. } else {
  6719. var range$$1 = rangeForUnit(cm, start, behavior.unit);
  6720. if (behavior.extend)
  6721. { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
  6722. else
  6723. { ourRange = range$$1; }
  6724. }
  6725. if (!behavior.addNew) {
  6726. ourIndex = 0;
  6727. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6728. startSel = doc.sel;
  6729. } else if (ourIndex == -1) {
  6730. ourIndex = ranges.length;
  6731. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  6732. {scroll: false, origin: "*mouse"});
  6733. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6734. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6735. {scroll: false, origin: "*mouse"});
  6736. startSel = doc.sel;
  6737. } else {
  6738. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6739. }
  6740. var lastPos = start;
  6741. function extendTo(pos) {
  6742. if (cmp(lastPos, pos) == 0) { return }
  6743. lastPos = pos;
  6744. if (behavior.unit == "rectangle") {
  6745. var ranges = [], tabSize = cm.options.tabSize;
  6746. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6747. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6748. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6749. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6750. line <= end; line++) {
  6751. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6752. if (left == right)
  6753. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6754. else if (text.length > leftPos)
  6755. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6756. }
  6757. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6758. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6759. {origin: "*mouse", scroll: false});
  6760. cm.scrollIntoView(pos);
  6761. } else {
  6762. var oldRange = ourRange;
  6763. var range$$1 = rangeForUnit(cm, pos, behavior.unit);
  6764. var anchor = oldRange.anchor, head;
  6765. if (cmp(range$$1.anchor, anchor) > 0) {
  6766. head = range$$1.head;
  6767. anchor = minPos(oldRange.from(), range$$1.anchor);
  6768. } else {
  6769. head = range$$1.anchor;
  6770. anchor = maxPos(oldRange.to(), range$$1.head);
  6771. }
  6772. var ranges$1 = startSel.ranges.slice(0);
  6773. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  6774. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  6775. }
  6776. }
  6777. var editorSize = display.wrapper.getBoundingClientRect();
  6778. // Used to ensure timeout re-tries don't fire when another extend
  6779. // happened in the meantime (clearTimeout isn't reliable -- at
  6780. // least on Chrome, the timeouts still happen even when cleared,
  6781. // if the clear happens after their scheduled firing time).
  6782. var counter = 0;
  6783. function extend(e) {
  6784. var curCount = ++counter;
  6785. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6786. if (!cur) { return }
  6787. if (cmp(cur, lastPos) != 0) {
  6788. cm.curOp.focus = activeElt();
  6789. extendTo(cur);
  6790. var visible = visibleLines(display, doc);
  6791. if (cur.line >= visible.to || cur.line < visible.from)
  6792. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6793. } else {
  6794. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6795. if (outside) { setTimeout(operation(cm, function () {
  6796. if (counter != curCount) { return }
  6797. display.scroller.scrollTop += outside;
  6798. extend(e);
  6799. }), 50); }
  6800. }
  6801. }
  6802. function done(e) {
  6803. cm.state.selectingText = false;
  6804. counter = Infinity;
  6805. // If e is null or undefined we interpret this as someone trying
  6806. // to explicitly cancel the selection rather than the user
  6807. // letting go of the mouse button.
  6808. if (e) {
  6809. e_preventDefault(e);
  6810. display.input.focus();
  6811. }
  6812. off(display.wrapper.ownerDocument, "mousemove", move);
  6813. off(display.wrapper.ownerDocument, "mouseup", up);
  6814. doc.history.lastSelOrigin = null;
  6815. }
  6816. var move = operation(cm, function (e) {
  6817. if (e.buttons === 0 || !e_button(e)) { done(e); }
  6818. else { extend(e); }
  6819. });
  6820. var up = operation(cm, done);
  6821. cm.state.selectingText = up;
  6822. on(display.wrapper.ownerDocument, "mousemove", move);
  6823. on(display.wrapper.ownerDocument, "mouseup", up);
  6824. }
  6825. // Used when mouse-selecting to adjust the anchor to the proper side
  6826. // of a bidi jump depending on the visual position of the head.
  6827. function bidiSimplify(cm, range$$1) {
  6828. var anchor = range$$1.anchor;
  6829. var head = range$$1.head;
  6830. var anchorLine = getLine(cm.doc, anchor.line);
  6831. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  6832. var order = getOrder(anchorLine);
  6833. if (!order) { return range$$1 }
  6834. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6835. if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  6836. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6837. if (boundary == 0 || boundary == order.length) { return range$$1 }
  6838. // Compute the relative visual position of the head compared to the
  6839. // anchor (<0 is to the left, >0 to the right)
  6840. var leftSide;
  6841. if (head.line != anchor.line) {
  6842. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6843. } else {
  6844. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6845. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6846. if (headIndex == boundary - 1 || headIndex == boundary)
  6847. { leftSide = dir < 0; }
  6848. else
  6849. { leftSide = dir > 0; }
  6850. }
  6851. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6852. var from = leftSide == (usePart.level == 1);
  6853. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6854. return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
  6855. }
  6856. // Determines whether an event happened in the gutter, and fires the
  6857. // handlers for the corresponding event.
  6858. function gutterEvent(cm, e, type, prevent) {
  6859. var mX, mY;
  6860. if (e.touches) {
  6861. mX = e.touches[0].clientX;
  6862. mY = e.touches[0].clientY;
  6863. } else {
  6864. try { mX = e.clientX; mY = e.clientY; }
  6865. catch(e) { return false }
  6866. }
  6867. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6868. if (prevent) { e_preventDefault(e); }
  6869. var display = cm.display;
  6870. var lineBox = display.lineDiv.getBoundingClientRect();
  6871. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6872. mY -= lineBox.top - display.viewOffset;
  6873. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  6874. var g = display.gutters.childNodes[i];
  6875. if (g && g.getBoundingClientRect().right >= mX) {
  6876. var line = lineAtHeight(cm.doc, mY);
  6877. var gutter = cm.display.gutterSpecs[i];
  6878. signal(cm, type, cm, line, gutter.className, e);
  6879. return e_defaultPrevented(e)
  6880. }
  6881. }
  6882. }
  6883. function clickInGutter(cm, e) {
  6884. return gutterEvent(cm, e, "gutterClick", true)
  6885. }
  6886. // CONTEXT MENU HANDLING
  6887. // To make the context menu work, we need to briefly unhide the
  6888. // textarea (making it as unobtrusive as possible) to let the
  6889. // right-click take effect on it.
  6890. function onContextMenu(cm, e) {
  6891. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6892. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6893. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  6894. }
  6895. function contextMenuInGutter(cm, e) {
  6896. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6897. return gutterEvent(cm, e, "gutterContextMenu", false)
  6898. }
  6899. function themeChanged(cm) {
  6900. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6901. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6902. clearCaches(cm);
  6903. }
  6904. var Init = {toString: function(){return "CodeMirror.Init"}};
  6905. var defaults = {};
  6906. var optionHandlers = {};
  6907. function defineOptions(CodeMirror) {
  6908. var optionHandlers = CodeMirror.optionHandlers;
  6909. function option(name, deflt, handle, notOnInit) {
  6910. CodeMirror.defaults[name] = deflt;
  6911. if (handle) { optionHandlers[name] =
  6912. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  6913. }
  6914. CodeMirror.defineOption = option;
  6915. // Passed to option handlers when there is no old value.
  6916. CodeMirror.Init = Init;
  6917. // These two are, on init, called from the constructor because they
  6918. // have to be initialized before the editor can start at all.
  6919. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  6920. option("mode", null, function (cm, val) {
  6921. cm.doc.modeOption = val;
  6922. loadMode(cm);
  6923. }, true);
  6924. option("indentUnit", 2, loadMode, true);
  6925. option("indentWithTabs", false);
  6926. option("smartIndent", true);
  6927. option("tabSize", 4, function (cm) {
  6928. resetModeState(cm);
  6929. clearCaches(cm);
  6930. regChange(cm);
  6931. }, true);
  6932. option("lineSeparator", null, function (cm, val) {
  6933. cm.doc.lineSep = val;
  6934. if (!val) { return }
  6935. var newBreaks = [], lineNo = cm.doc.first;
  6936. cm.doc.iter(function (line) {
  6937. for (var pos = 0;;) {
  6938. var found = line.text.indexOf(val, pos);
  6939. if (found == -1) { break }
  6940. pos = found + val.length;
  6941. newBreaks.push(Pos(lineNo, found));
  6942. }
  6943. lineNo++;
  6944. });
  6945. for (var i = newBreaks.length - 1; i >= 0; i--)
  6946. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  6947. });
  6948. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6949. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6950. if (old != Init) { cm.refresh(); }
  6951. });
  6952. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  6953. option("electricChars", true);
  6954. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6955. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6956. }, true);
  6957. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  6958. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  6959. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  6960. option("rtlMoveVisually", !windows);
  6961. option("wholeLineUpdateBefore", true);
  6962. option("theme", "default", function (cm) {
  6963. themeChanged(cm);
  6964. updateGutters(cm);
  6965. }, true);
  6966. option("keyMap", "default", function (cm, val, old) {
  6967. var next = getKeyMap(val);
  6968. var prev = old != Init && getKeyMap(old);
  6969. if (prev && prev.detach) { prev.detach(cm, next); }
  6970. if (next.attach) { next.attach(cm, prev || null); }
  6971. });
  6972. option("extraKeys", null);
  6973. option("configureMouse", null);
  6974. option("lineWrapping", false, wrappingChanged, true);
  6975. option("gutters", [], function (cm, val) {
  6976. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  6977. updateGutters(cm);
  6978. }, true);
  6979. option("fixedGutter", true, function (cm, val) {
  6980. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  6981. cm.refresh();
  6982. }, true);
  6983. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  6984. option("scrollbarStyle", "native", function (cm) {
  6985. initScrollbars(cm);
  6986. updateScrollbars(cm);
  6987. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  6988. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  6989. }, true);
  6990. option("lineNumbers", false, function (cm, val) {
  6991. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  6992. updateGutters(cm);
  6993. }, true);
  6994. option("firstLineNumber", 1, updateGutters, true);
  6995. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  6996. option("showCursorWhenSelecting", false, updateSelection, true);
  6997. option("resetSelectionOnContextMenu", true);
  6998. option("lineWiseCopyCut", true);
  6999. option("pasteLinesPerSelection", true);
  7000. option("selectionsMayTouch", false);
  7001. option("readOnly", false, function (cm, val) {
  7002. if (val == "nocursor") {
  7003. onBlur(cm);
  7004. cm.display.input.blur();
  7005. }
  7006. cm.display.input.readOnlyChanged(val);
  7007. });
  7008. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7009. option("dragDrop", true, dragDropChanged);
  7010. option("allowDropFileTypes", null);
  7011. option("cursorBlinkRate", 530);
  7012. option("cursorScrollMargin", 0);
  7013. option("cursorHeight", 1, updateSelection, true);
  7014. option("singleCursorHeightPerLine", true, updateSelection, true);
  7015. option("workTime", 100);
  7016. option("workDelay", 100);
  7017. option("flattenSpans", true, resetModeState, true);
  7018. option("addModeClass", false, resetModeState, true);
  7019. option("pollInterval", 100);
  7020. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7021. option("historyEventDelay", 1250);
  7022. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7023. option("maxHighlightLength", 10000, resetModeState, true);
  7024. option("moveInputWithCursor", true, function (cm, val) {
  7025. if (!val) { cm.display.input.resetPosition(); }
  7026. });
  7027. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7028. option("autofocus", null);
  7029. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7030. option("phrases", null);
  7031. }
  7032. function dragDropChanged(cm, value, old) {
  7033. var wasOn = old && old != Init;
  7034. if (!value != !wasOn) {
  7035. var funcs = cm.display.dragFunctions;
  7036. var toggle = value ? on : off;
  7037. toggle(cm.display.scroller, "dragstart", funcs.start);
  7038. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7039. toggle(cm.display.scroller, "dragover", funcs.over);
  7040. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7041. toggle(cm.display.scroller, "drop", funcs.drop);
  7042. }
  7043. }
  7044. function wrappingChanged(cm) {
  7045. if (cm.options.lineWrapping) {
  7046. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7047. cm.display.sizer.style.minWidth = "";
  7048. cm.display.sizerWidth = null;
  7049. } else {
  7050. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7051. findMaxLine(cm);
  7052. }
  7053. estimateLineHeights(cm);
  7054. regChange(cm);
  7055. clearCaches(cm);
  7056. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7057. }
  7058. // A CodeMirror instance represents an editor. This is the object
  7059. // that user code is usually dealing with.
  7060. function CodeMirror(place, options) {
  7061. var this$1 = this;
  7062. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7063. this.options = options = options ? copyObj(options) : {};
  7064. // Determine effective options based on given values and defaults.
  7065. copyObj(defaults, options, false);
  7066. var doc = options.value;
  7067. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7068. else if (options.mode) { doc.modeOption = options.mode; }
  7069. this.doc = doc;
  7070. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7071. var display = this.display = new Display(place, doc, input, options);
  7072. display.wrapper.CodeMirror = this;
  7073. themeChanged(this);
  7074. if (options.lineWrapping)
  7075. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7076. initScrollbars(this);
  7077. this.state = {
  7078. keyMaps: [], // stores maps added by addKeyMap
  7079. overlays: [], // highlighting overlays, as added by addOverlay
  7080. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7081. overwrite: false,
  7082. delayingBlurEvent: false,
  7083. focused: false,
  7084. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7085. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7086. selectingText: false,
  7087. draggingText: false,
  7088. highlight: new Delayed(), // stores highlight worker timeout
  7089. keySeq: null, // Unfinished key sequence
  7090. specialChars: null
  7091. };
  7092. if (options.autofocus && !mobile) { display.input.focus(); }
  7093. // Override magic textarea content restore that IE sometimes does
  7094. // on our hidden textarea on reload
  7095. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7096. registerEventHandlers(this);
  7097. ensureGlobalHandlers();
  7098. startOperation(this);
  7099. this.curOp.forceUpdate = true;
  7100. attachDoc(this, doc);
  7101. if ((options.autofocus && !mobile) || this.hasFocus())
  7102. { setTimeout(bind(onFocus, this), 20); }
  7103. else
  7104. { onBlur(this); }
  7105. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7106. { optionHandlers[opt](this$1, options[opt], Init); } }
  7107. maybeUpdateLineNumberWidth(this);
  7108. if (options.finishInit) { options.finishInit(this); }
  7109. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  7110. endOperation(this);
  7111. // Suppress optimizelegibility in Webkit, since it breaks text
  7112. // measuring on line wrapping boundaries.
  7113. if (webkit && options.lineWrapping &&
  7114. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7115. { display.lineDiv.style.textRendering = "auto"; }
  7116. }
  7117. // The default configuration options.
  7118. CodeMirror.defaults = defaults;
  7119. // Functions to run when options are changed.
  7120. CodeMirror.optionHandlers = optionHandlers;
  7121. // Attach the necessary event handlers when initializing the editor
  7122. function registerEventHandlers(cm) {
  7123. var d = cm.display;
  7124. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7125. // Older IE's will not fire a second mousedown for a double click
  7126. if (ie && ie_version < 11)
  7127. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7128. if (signalDOMEvent(cm, e)) { return }
  7129. var pos = posFromMouse(cm, e);
  7130. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7131. e_preventDefault(e);
  7132. var word = cm.findWordAt(pos);
  7133. extendSelection(cm.doc, word.anchor, word.head);
  7134. })); }
  7135. else
  7136. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7137. // Some browsers fire contextmenu *after* opening the menu, at
  7138. // which point we can't mess with it anymore. Context menu is
  7139. // handled in onMouseDown for these browsers.
  7140. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7141. // Used to suppress mouse event handling when a touch happens
  7142. var touchFinished, prevTouch = {end: 0};
  7143. function finishTouch() {
  7144. if (d.activeTouch) {
  7145. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7146. prevTouch = d.activeTouch;
  7147. prevTouch.end = +new Date;
  7148. }
  7149. }
  7150. function isMouseLikeTouchEvent(e) {
  7151. if (e.touches.length != 1) { return false }
  7152. var touch = e.touches[0];
  7153. return touch.radiusX <= 1 && touch.radiusY <= 1
  7154. }
  7155. function farAway(touch, other) {
  7156. if (other.left == null) { return true }
  7157. var dx = other.left - touch.left, dy = other.top - touch.top;
  7158. return dx * dx + dy * dy > 20 * 20
  7159. }
  7160. on(d.scroller, "touchstart", function (e) {
  7161. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7162. d.input.ensurePolled();
  7163. clearTimeout(touchFinished);
  7164. var now = +new Date;
  7165. d.activeTouch = {start: now, moved: false,
  7166. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7167. if (e.touches.length == 1) {
  7168. d.activeTouch.left = e.touches[0].pageX;
  7169. d.activeTouch.top = e.touches[0].pageY;
  7170. }
  7171. }
  7172. });
  7173. on(d.scroller, "touchmove", function () {
  7174. if (d.activeTouch) { d.activeTouch.moved = true; }
  7175. });
  7176. on(d.scroller, "touchend", function (e) {
  7177. var touch = d.activeTouch;
  7178. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7179. !touch.moved && new Date - touch.start < 300) {
  7180. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7181. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7182. { range = new Range(pos, pos); }
  7183. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7184. { range = cm.findWordAt(pos); }
  7185. else // Triple tap
  7186. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7187. cm.setSelection(range.anchor, range.head);
  7188. cm.focus();
  7189. e_preventDefault(e);
  7190. }
  7191. finishTouch();
  7192. });
  7193. on(d.scroller, "touchcancel", finishTouch);
  7194. // Sync scrolling between fake scrollbars and real scrollable
  7195. // area, ensure viewport is updated when scrolling.
  7196. on(d.scroller, "scroll", function () {
  7197. if (d.scroller.clientHeight) {
  7198. updateScrollTop(cm, d.scroller.scrollTop);
  7199. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7200. signal(cm, "scroll", cm);
  7201. }
  7202. });
  7203. // Listen to wheel events in order to try and update the viewport on time.
  7204. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7205. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7206. // Prevent wrapper from ever scrolling
  7207. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7208. d.dragFunctions = {
  7209. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7210. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7211. start: function (e) { return onDragStart(cm, e); },
  7212. drop: operation(cm, onDrop),
  7213. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7214. };
  7215. var inp = d.input.getField();
  7216. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7217. on(inp, "keydown", operation(cm, onKeyDown));
  7218. on(inp, "keypress", operation(cm, onKeyPress));
  7219. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7220. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7221. }
  7222. var initHooks = [];
  7223. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7224. // Indent the given line. The how parameter can be "smart",
  7225. // "add"/null, "subtract", or "prev". When aggressive is false
  7226. // (typically set to true for forced single-line indents), empty
  7227. // lines are not indented, and places where the mode returns Pass
  7228. // are left alone.
  7229. function indentLine(cm, n, how, aggressive) {
  7230. var doc = cm.doc, state;
  7231. if (how == null) { how = "add"; }
  7232. if (how == "smart") {
  7233. // Fall back to "prev" when the mode doesn't have an indentation
  7234. // method.
  7235. if (!doc.mode.indent) { how = "prev"; }
  7236. else { state = getContextBefore(cm, n).state; }
  7237. }
  7238. var tabSize = cm.options.tabSize;
  7239. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7240. if (line.stateAfter) { line.stateAfter = null; }
  7241. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7242. if (!aggressive && !/\S/.test(line.text)) {
  7243. indentation = 0;
  7244. how = "not";
  7245. } else if (how == "smart") {
  7246. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7247. if (indentation == Pass || indentation > 150) {
  7248. if (!aggressive) { return }
  7249. how = "prev";
  7250. }
  7251. }
  7252. if (how == "prev") {
  7253. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7254. else { indentation = 0; }
  7255. } else if (how == "add") {
  7256. indentation = curSpace + cm.options.indentUnit;
  7257. } else if (how == "subtract") {
  7258. indentation = curSpace - cm.options.indentUnit;
  7259. } else if (typeof how == "number") {
  7260. indentation = curSpace + how;
  7261. }
  7262. indentation = Math.max(0, indentation);
  7263. var indentString = "", pos = 0;
  7264. if (cm.options.indentWithTabs)
  7265. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7266. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7267. if (indentString != curSpaceString) {
  7268. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7269. line.stateAfter = null;
  7270. return true
  7271. } else {
  7272. // Ensure that, if the cursor was in the whitespace at the start
  7273. // of the line, it is moved to the end of that space.
  7274. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7275. var range = doc.sel.ranges[i$1];
  7276. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7277. var pos$1 = Pos(n, curSpaceString.length);
  7278. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7279. break
  7280. }
  7281. }
  7282. }
  7283. }
  7284. // This will be set to a {lineWise: bool, text: [string]} object, so
  7285. // that, when pasting, we know what kind of selections the copied
  7286. // text was made out of.
  7287. var lastCopied = null;
  7288. function setLastCopied(newLastCopied) {
  7289. lastCopied = newLastCopied;
  7290. }
  7291. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7292. var doc = cm.doc;
  7293. cm.display.shift = false;
  7294. if (!sel) { sel = doc.sel; }
  7295. var recent = +new Date - 200;
  7296. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7297. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7298. // When pasting N lines into N selections, insert one line per selection
  7299. if (paste && sel.ranges.length > 1) {
  7300. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7301. if (sel.ranges.length % lastCopied.text.length == 0) {
  7302. multiPaste = [];
  7303. for (var i = 0; i < lastCopied.text.length; i++)
  7304. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7305. }
  7306. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7307. multiPaste = map(textLines, function (l) { return [l]; });
  7308. }
  7309. }
  7310. var updateInput = cm.curOp.updateInput;
  7311. // Normal behavior is to insert the new text into every selection
  7312. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7313. var range$$1 = sel.ranges[i$1];
  7314. var from = range$$1.from(), to = range$$1.to();
  7315. if (range$$1.empty()) {
  7316. if (deleted && deleted > 0) // Handle deletion
  7317. { from = Pos(from.line, from.ch - deleted); }
  7318. else if (cm.state.overwrite && !paste) // Handle overwrite
  7319. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7320. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  7321. { from = to = Pos(from.line, 0); }
  7322. }
  7323. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7324. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  7325. makeChange(cm.doc, changeEvent);
  7326. signalLater(cm, "inputRead", cm, changeEvent);
  7327. }
  7328. if (inserted && !paste)
  7329. { triggerElectric(cm, inserted); }
  7330. ensureCursorVisible(cm);
  7331. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7332. cm.curOp.typing = true;
  7333. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7334. }
  7335. function handlePaste(e, cm) {
  7336. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7337. if (pasted) {
  7338. e.preventDefault();
  7339. if (!cm.isReadOnly() && !cm.options.disableInput)
  7340. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7341. return true
  7342. }
  7343. }
  7344. function triggerElectric(cm, inserted) {
  7345. // When an 'electric' character is inserted, immediately trigger a reindent
  7346. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7347. var sel = cm.doc.sel;
  7348. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7349. var range$$1 = sel.ranges[i];
  7350. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  7351. var mode = cm.getModeAt(range$$1.head);
  7352. var indented = false;
  7353. if (mode.electricChars) {
  7354. for (var j = 0; j < mode.electricChars.length; j++)
  7355. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7356. indented = indentLine(cm, range$$1.head.line, "smart");
  7357. break
  7358. } }
  7359. } else if (mode.electricInput) {
  7360. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  7361. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  7362. }
  7363. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  7364. }
  7365. }
  7366. function copyableRanges(cm) {
  7367. var text = [], ranges = [];
  7368. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7369. var line = cm.doc.sel.ranges[i].head.line;
  7370. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7371. ranges.push(lineRange);
  7372. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7373. }
  7374. return {text: text, ranges: ranges}
  7375. }
  7376. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7377. field.setAttribute("autocorrect", !!autocorrect);
  7378. field.setAttribute("autocapitalize", !!autocapitalize);
  7379. field.setAttribute("spellcheck", !!spellcheck);
  7380. }
  7381. function hiddenTextarea() {
  7382. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  7383. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7384. // The textarea is kept positioned near the cursor to prevent the
  7385. // fact that it'll be scrolled into view on input from scrolling
  7386. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7387. // very slow. So make the area wide instead.
  7388. if (webkit) { te.style.width = "1000px"; }
  7389. else { te.setAttribute("wrap", "off"); }
  7390. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7391. if (ios) { te.style.border = "1px solid black"; }
  7392. disableBrowserMagic(te);
  7393. return div
  7394. }
  7395. // The publicly visible API. Note that methodOp(f) means
  7396. // 'wrap f in an operation, performed on its `this` parameter'.
  7397. // This is not the complete set of editor methods. Most of the
  7398. // methods defined on the Doc type are also injected into
  7399. // CodeMirror.prototype, for backwards compatibility and
  7400. // convenience.
  7401. function addEditorMethods(CodeMirror) {
  7402. var optionHandlers = CodeMirror.optionHandlers;
  7403. var helpers = CodeMirror.helpers = {};
  7404. CodeMirror.prototype = {
  7405. constructor: CodeMirror,
  7406. focus: function(){window.focus(); this.display.input.focus();},
  7407. setOption: function(option, value) {
  7408. var options = this.options, old = options[option];
  7409. if (options[option] == value && option != "mode") { return }
  7410. options[option] = value;
  7411. if (optionHandlers.hasOwnProperty(option))
  7412. { operation(this, optionHandlers[option])(this, value, old); }
  7413. signal(this, "optionChange", this, option);
  7414. },
  7415. getOption: function(option) {return this.options[option]},
  7416. getDoc: function() {return this.doc},
  7417. addKeyMap: function(map$$1, bottom) {
  7418. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  7419. },
  7420. removeKeyMap: function(map$$1) {
  7421. var maps = this.state.keyMaps;
  7422. for (var i = 0; i < maps.length; ++i)
  7423. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  7424. maps.splice(i, 1);
  7425. return true
  7426. } }
  7427. },
  7428. addOverlay: methodOp(function(spec, options) {
  7429. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7430. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7431. insertSorted(this.state.overlays,
  7432. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7433. priority: (options && options.priority) || 0},
  7434. function (overlay) { return overlay.priority; });
  7435. this.state.modeGen++;
  7436. regChange(this);
  7437. }),
  7438. removeOverlay: methodOp(function(spec) {
  7439. var this$1 = this;
  7440. var overlays = this.state.overlays;
  7441. for (var i = 0; i < overlays.length; ++i) {
  7442. var cur = overlays[i].modeSpec;
  7443. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7444. overlays.splice(i, 1);
  7445. this$1.state.modeGen++;
  7446. regChange(this$1);
  7447. return
  7448. }
  7449. }
  7450. }),
  7451. indentLine: methodOp(function(n, dir, aggressive) {
  7452. if (typeof dir != "string" && typeof dir != "number") {
  7453. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7454. else { dir = dir ? "add" : "subtract"; }
  7455. }
  7456. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7457. }),
  7458. indentSelection: methodOp(function(how) {
  7459. var this$1 = this;
  7460. var ranges = this.doc.sel.ranges, end = -1;
  7461. for (var i = 0; i < ranges.length; i++) {
  7462. var range$$1 = ranges[i];
  7463. if (!range$$1.empty()) {
  7464. var from = range$$1.from(), to = range$$1.to();
  7465. var start = Math.max(end, from.line);
  7466. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7467. for (var j = start; j < end; ++j)
  7468. { indentLine(this$1, j, how); }
  7469. var newRanges = this$1.doc.sel.ranges;
  7470. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7471. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7472. } else if (range$$1.head.line > end) {
  7473. indentLine(this$1, range$$1.head.line, how, true);
  7474. end = range$$1.head.line;
  7475. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  7476. }
  7477. }
  7478. }),
  7479. // Fetch the parser token for a given character. Useful for hacks
  7480. // that want to inspect the mode state (say, for completion).
  7481. getTokenAt: function(pos, precise) {
  7482. return takeToken(this, pos, precise)
  7483. },
  7484. getLineTokens: function(line, precise) {
  7485. return takeToken(this, Pos(line), precise, true)
  7486. },
  7487. getTokenTypeAt: function(pos) {
  7488. pos = clipPos(this.doc, pos);
  7489. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7490. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7491. var type;
  7492. if (ch == 0) { type = styles[2]; }
  7493. else { for (;;) {
  7494. var mid = (before + after) >> 1;
  7495. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7496. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7497. else { type = styles[mid * 2 + 2]; break }
  7498. } }
  7499. var cut = type ? type.indexOf("overlay ") : -1;
  7500. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7501. },
  7502. getModeAt: function(pos) {
  7503. var mode = this.doc.mode;
  7504. if (!mode.innerMode) { return mode }
  7505. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7506. },
  7507. getHelper: function(pos, type) {
  7508. return this.getHelpers(pos, type)[0]
  7509. },
  7510. getHelpers: function(pos, type) {
  7511. var this$1 = this;
  7512. var found = [];
  7513. if (!helpers.hasOwnProperty(type)) { return found }
  7514. var help = helpers[type], mode = this.getModeAt(pos);
  7515. if (typeof mode[type] == "string") {
  7516. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7517. } else if (mode[type]) {
  7518. for (var i = 0; i < mode[type].length; i++) {
  7519. var val = help[mode[type][i]];
  7520. if (val) { found.push(val); }
  7521. }
  7522. } else if (mode.helperType && help[mode.helperType]) {
  7523. found.push(help[mode.helperType]);
  7524. } else if (help[mode.name]) {
  7525. found.push(help[mode.name]);
  7526. }
  7527. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7528. var cur = help._global[i$1];
  7529. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7530. { found.push(cur.val); }
  7531. }
  7532. return found
  7533. },
  7534. getStateAfter: function(line, precise) {
  7535. var doc = this.doc;
  7536. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7537. return getContextBefore(this, line + 1, precise).state
  7538. },
  7539. cursorCoords: function(start, mode) {
  7540. var pos, range$$1 = this.doc.sel.primary();
  7541. if (start == null) { pos = range$$1.head; }
  7542. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7543. else { pos = start ? range$$1.from() : range$$1.to(); }
  7544. return cursorCoords(this, pos, mode || "page")
  7545. },
  7546. charCoords: function(pos, mode) {
  7547. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7548. },
  7549. coordsChar: function(coords, mode) {
  7550. coords = fromCoordSystem(this, coords, mode || "page");
  7551. return coordsChar(this, coords.left, coords.top)
  7552. },
  7553. lineAtHeight: function(height, mode) {
  7554. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7555. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7556. },
  7557. heightAtLine: function(line, mode, includeWidgets) {
  7558. var end = false, lineObj;
  7559. if (typeof line == "number") {
  7560. var last = this.doc.first + this.doc.size - 1;
  7561. if (line < this.doc.first) { line = this.doc.first; }
  7562. else if (line > last) { line = last; end = true; }
  7563. lineObj = getLine(this.doc, line);
  7564. } else {
  7565. lineObj = line;
  7566. }
  7567. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7568. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7569. },
  7570. defaultTextHeight: function() { return textHeight(this.display) },
  7571. defaultCharWidth: function() { return charWidth(this.display) },
  7572. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7573. addWidget: function(pos, node, scroll, vert, horiz) {
  7574. var display = this.display;
  7575. pos = cursorCoords(this, clipPos(this.doc, pos));
  7576. var top = pos.bottom, left = pos.left;
  7577. node.style.position = "absolute";
  7578. node.setAttribute("cm-ignore-events", "true");
  7579. this.display.input.setUneditable(node);
  7580. display.sizer.appendChild(node);
  7581. if (vert == "over") {
  7582. top = pos.top;
  7583. } else if (vert == "above" || vert == "near") {
  7584. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7585. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7586. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7587. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7588. { top = pos.top - node.offsetHeight; }
  7589. else if (pos.bottom + node.offsetHeight <= vspace)
  7590. { top = pos.bottom; }
  7591. if (left + node.offsetWidth > hspace)
  7592. { left = hspace - node.offsetWidth; }
  7593. }
  7594. node.style.top = top + "px";
  7595. node.style.left = node.style.right = "";
  7596. if (horiz == "right") {
  7597. left = display.sizer.clientWidth - node.offsetWidth;
  7598. node.style.right = "0px";
  7599. } else {
  7600. if (horiz == "left") { left = 0; }
  7601. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7602. node.style.left = left + "px";
  7603. }
  7604. if (scroll)
  7605. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7606. },
  7607. triggerOnKeyDown: methodOp(onKeyDown),
  7608. triggerOnKeyPress: methodOp(onKeyPress),
  7609. triggerOnKeyUp: onKeyUp,
  7610. triggerOnMouseDown: methodOp(onMouseDown),
  7611. execCommand: function(cmd) {
  7612. if (commands.hasOwnProperty(cmd))
  7613. { return commands[cmd].call(null, this) }
  7614. },
  7615. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7616. findPosH: function(from, amount, unit, visually) {
  7617. var this$1 = this;
  7618. var dir = 1;
  7619. if (amount < 0) { dir = -1; amount = -amount; }
  7620. var cur = clipPos(this.doc, from);
  7621. for (var i = 0; i < amount; ++i) {
  7622. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  7623. if (cur.hitSide) { break }
  7624. }
  7625. return cur
  7626. },
  7627. moveH: methodOp(function(dir, unit) {
  7628. var this$1 = this;
  7629. this.extendSelectionsBy(function (range$$1) {
  7630. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  7631. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  7632. else
  7633. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7634. }, sel_move);
  7635. }),
  7636. deleteH: methodOp(function(dir, unit) {
  7637. var sel = this.doc.sel, doc = this.doc;
  7638. if (sel.somethingSelected())
  7639. { doc.replaceSelection("", null, "+delete"); }
  7640. else
  7641. { deleteNearSelection(this, function (range$$1) {
  7642. var other = findPosH(doc, range$$1.head, dir, unit, false);
  7643. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  7644. }); }
  7645. }),
  7646. findPosV: function(from, amount, unit, goalColumn) {
  7647. var this$1 = this;
  7648. var dir = 1, x = goalColumn;
  7649. if (amount < 0) { dir = -1; amount = -amount; }
  7650. var cur = clipPos(this.doc, from);
  7651. for (var i = 0; i < amount; ++i) {
  7652. var coords = cursorCoords(this$1, cur, "div");
  7653. if (x == null) { x = coords.left; }
  7654. else { coords.left = x; }
  7655. cur = findPosV(this$1, coords, dir, unit);
  7656. if (cur.hitSide) { break }
  7657. }
  7658. return cur
  7659. },
  7660. moveV: methodOp(function(dir, unit) {
  7661. var this$1 = this;
  7662. var doc = this.doc, goals = [];
  7663. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7664. doc.extendSelectionsBy(function (range$$1) {
  7665. if (collapse)
  7666. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7667. var headPos = cursorCoords(this$1, range$$1.head, "div");
  7668. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  7669. goals.push(headPos.left);
  7670. var pos = findPosV(this$1, headPos, dir, unit);
  7671. if (unit == "page" && range$$1 == doc.sel.primary())
  7672. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7673. return pos
  7674. }, sel_move);
  7675. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7676. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7677. }),
  7678. // Find the word at the given position (as returned by coordsChar).
  7679. findWordAt: function(pos) {
  7680. var doc = this.doc, line = getLine(doc, pos.line).text;
  7681. var start = pos.ch, end = pos.ch;
  7682. if (line) {
  7683. var helper = this.getHelper(pos, "wordChars");
  7684. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7685. var startChar = line.charAt(start);
  7686. var check = isWordChar(startChar, helper)
  7687. ? function (ch) { return isWordChar(ch, helper); }
  7688. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7689. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7690. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7691. while (end < line.length && check(line.charAt(end))) { ++end; }
  7692. }
  7693. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7694. },
  7695. toggleOverwrite: function(value) {
  7696. if (value != null && value == this.state.overwrite) { return }
  7697. if (this.state.overwrite = !this.state.overwrite)
  7698. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7699. else
  7700. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7701. signal(this, "overwriteToggle", this, this.state.overwrite);
  7702. },
  7703. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7704. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7705. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7706. getScrollInfo: function() {
  7707. var scroller = this.display.scroller;
  7708. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7709. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7710. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7711. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7712. },
  7713. scrollIntoView: methodOp(function(range$$1, margin) {
  7714. if (range$$1 == null) {
  7715. range$$1 = {from: this.doc.sel.primary().head, to: null};
  7716. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7717. } else if (typeof range$$1 == "number") {
  7718. range$$1 = {from: Pos(range$$1, 0), to: null};
  7719. } else if (range$$1.from == null) {
  7720. range$$1 = {from: range$$1, to: null};
  7721. }
  7722. if (!range$$1.to) { range$$1.to = range$$1.from; }
  7723. range$$1.margin = margin || 0;
  7724. if (range$$1.from.line != null) {
  7725. scrollToRange(this, range$$1);
  7726. } else {
  7727. scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
  7728. }
  7729. }),
  7730. setSize: methodOp(function(width, height) {
  7731. var this$1 = this;
  7732. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7733. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7734. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7735. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7736. var lineNo$$1 = this.display.viewFrom;
  7737. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  7738. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7739. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  7740. ++lineNo$$1;
  7741. });
  7742. this.curOp.forceUpdate = true;
  7743. signal(this, "refresh", this);
  7744. }),
  7745. operation: function(f){return runInOp(this, f)},
  7746. startOperation: function(){return startOperation(this)},
  7747. endOperation: function(){return endOperation(this)},
  7748. refresh: methodOp(function() {
  7749. var oldHeight = this.display.cachedTextHeight;
  7750. regChange(this);
  7751. this.curOp.forceUpdate = true;
  7752. clearCaches(this);
  7753. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7754. updateGutterSpace(this.display);
  7755. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7756. { estimateLineHeights(this); }
  7757. signal(this, "refresh", this);
  7758. }),
  7759. swapDoc: methodOp(function(doc) {
  7760. var old = this.doc;
  7761. old.cm = null;
  7762. // Cancel the current text selection if any (#5821)
  7763. if (this.state.selectingText) { this.state.selectingText(); }
  7764. attachDoc(this, doc);
  7765. clearCaches(this);
  7766. this.display.input.reset();
  7767. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7768. this.curOp.forceScroll = true;
  7769. signalLater(this, "swapDoc", this, old);
  7770. return old
  7771. }),
  7772. phrase: function(phraseText) {
  7773. var phrases = this.options.phrases;
  7774. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7775. },
  7776. getInputField: function(){return this.display.input.getField()},
  7777. getWrapperElement: function(){return this.display.wrapper},
  7778. getScrollerElement: function(){return this.display.scroller},
  7779. getGutterElement: function(){return this.display.gutters}
  7780. };
  7781. eventMixin(CodeMirror);
  7782. CodeMirror.registerHelper = function(type, name, value) {
  7783. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7784. helpers[type][name] = value;
  7785. };
  7786. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7787. CodeMirror.registerHelper(type, name, value);
  7788. helpers[type]._global.push({pred: predicate, val: value});
  7789. };
  7790. }
  7791. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7792. // right), unit can be "char", "column" (like char, but doesn't
  7793. // cross line boundaries), "word" (across next word), or "group" (to
  7794. // the start of next group of word or non-word-non-whitespace
  7795. // chars). The visually param controls whether, in right-to-left
  7796. // text, direction 1 means to move towards the next index in the
  7797. // string, or towards the character to the right of the current
  7798. // position. The resulting position will have a hitSide=true
  7799. // property if it reached the end of the document.
  7800. function findPosH(doc, pos, dir, unit, visually) {
  7801. var oldPos = pos;
  7802. var origDir = dir;
  7803. var lineObj = getLine(doc, pos.line);
  7804. function findNextLine() {
  7805. var l = pos.line + dir;
  7806. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7807. pos = new Pos(l, pos.ch, pos.sticky);
  7808. return lineObj = getLine(doc, l)
  7809. }
  7810. function moveOnce(boundToLine) {
  7811. var next;
  7812. if (visually) {
  7813. next = moveVisually(doc.cm, lineObj, pos, dir);
  7814. } else {
  7815. next = moveLogically(lineObj, pos, dir);
  7816. }
  7817. if (next == null) {
  7818. if (!boundToLine && findNextLine())
  7819. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  7820. else
  7821. { return false }
  7822. } else {
  7823. pos = next;
  7824. }
  7825. return true
  7826. }
  7827. if (unit == "char") {
  7828. moveOnce();
  7829. } else if (unit == "column") {
  7830. moveOnce(true);
  7831. } else if (unit == "word" || unit == "group") {
  7832. var sawType = null, group = unit == "group";
  7833. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7834. for (var first = true;; first = false) {
  7835. if (dir < 0 && !moveOnce(!first)) { break }
  7836. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7837. var type = isWordChar(cur, helper) ? "w"
  7838. : group && cur == "\n" ? "n"
  7839. : !group || /\s/.test(cur) ? null
  7840. : "p";
  7841. if (group && !first && !type) { type = "s"; }
  7842. if (sawType && sawType != type) {
  7843. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7844. break
  7845. }
  7846. if (type) { sawType = type; }
  7847. if (dir > 0 && !moveOnce(!first)) { break }
  7848. }
  7849. }
  7850. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7851. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7852. return result
  7853. }
  7854. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7855. // "page" or "line". The resulting position will have a hitSide=true
  7856. // property if it reached the end of the document.
  7857. function findPosV(cm, pos, dir, unit) {
  7858. var doc = cm.doc, x = pos.left, y;
  7859. if (unit == "page") {
  7860. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  7861. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7862. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7863. } else if (unit == "line") {
  7864. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7865. }
  7866. var target;
  7867. for (;;) {
  7868. target = coordsChar(cm, x, y);
  7869. if (!target.outside) { break }
  7870. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7871. y += dir * 5;
  7872. }
  7873. return target
  7874. }
  7875. // CONTENTEDITABLE INPUT STYLE
  7876. var ContentEditableInput = function(cm) {
  7877. this.cm = cm;
  7878. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7879. this.polling = new Delayed();
  7880. this.composing = null;
  7881. this.gracePeriod = false;
  7882. this.readDOMTimeout = null;
  7883. };
  7884. ContentEditableInput.prototype.init = function (display) {
  7885. var this$1 = this;
  7886. var input = this, cm = input.cm;
  7887. var div = input.div = display.lineDiv;
  7888. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  7889. on(div, "paste", function (e) {
  7890. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7891. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7892. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  7893. });
  7894. on(div, "compositionstart", function (e) {
  7895. this$1.composing = {data: e.data, done: false};
  7896. });
  7897. on(div, "compositionupdate", function (e) {
  7898. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  7899. });
  7900. on(div, "compositionend", function (e) {
  7901. if (this$1.composing) {
  7902. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  7903. this$1.composing.done = true;
  7904. }
  7905. });
  7906. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  7907. on(div, "input", function () {
  7908. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  7909. });
  7910. function onCopyCut(e) {
  7911. if (signalDOMEvent(cm, e)) { return }
  7912. if (cm.somethingSelected()) {
  7913. setLastCopied({lineWise: false, text: cm.getSelections()});
  7914. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  7915. } else if (!cm.options.lineWiseCopyCut) {
  7916. return
  7917. } else {
  7918. var ranges = copyableRanges(cm);
  7919. setLastCopied({lineWise: true, text: ranges.text});
  7920. if (e.type == "cut") {
  7921. cm.operation(function () {
  7922. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  7923. cm.replaceSelection("", null, "cut");
  7924. });
  7925. }
  7926. }
  7927. if (e.clipboardData) {
  7928. e.clipboardData.clearData();
  7929. var content = lastCopied.text.join("\n");
  7930. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7931. e.clipboardData.setData("Text", content);
  7932. if (e.clipboardData.getData("Text") == content) {
  7933. e.preventDefault();
  7934. return
  7935. }
  7936. }
  7937. // Old-fashioned briefly-focus-a-textarea hack
  7938. var kludge = hiddenTextarea(), te = kludge.firstChild;
  7939. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  7940. te.value = lastCopied.text.join("\n");
  7941. var hadFocus = document.activeElement;
  7942. selectInput(te);
  7943. setTimeout(function () {
  7944. cm.display.lineSpace.removeChild(kludge);
  7945. hadFocus.focus();
  7946. if (hadFocus == div) { input.showPrimarySelection(); }
  7947. }, 50);
  7948. }
  7949. on(div, "copy", onCopyCut);
  7950. on(div, "cut", onCopyCut);
  7951. };
  7952. ContentEditableInput.prototype.prepareSelection = function () {
  7953. var result = prepareSelection(this.cm, false);
  7954. result.focus = this.cm.state.focused;
  7955. return result
  7956. };
  7957. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7958. if (!info || !this.cm.display.view.length) { return }
  7959. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  7960. this.showMultipleSelections(info);
  7961. };
  7962. ContentEditableInput.prototype.getSelection = function () {
  7963. return this.cm.display.wrapper.ownerDocument.getSelection()
  7964. };
  7965. ContentEditableInput.prototype.showPrimarySelection = function () {
  7966. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  7967. var from = prim.from(), to = prim.to();
  7968. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7969. sel.removeAllRanges();
  7970. return
  7971. }
  7972. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  7973. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  7974. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7975. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7976. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7977. { return }
  7978. var view = cm.display.view;
  7979. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7980. {node: view[0].measure.map[2], offset: 0};
  7981. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  7982. if (!end) {
  7983. var measure = view[view.length - 1].measure;
  7984. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  7985. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  7986. }
  7987. if (!start || !end) {
  7988. sel.removeAllRanges();
  7989. return
  7990. }
  7991. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  7992. try { rng = range(start.node, start.offset, end.offset, end.node); }
  7993. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7994. if (rng) {
  7995. if (!gecko && cm.state.focused) {
  7996. sel.collapse(start.node, start.offset);
  7997. if (!rng.collapsed) {
  7998. sel.removeAllRanges();
  7999. sel.addRange(rng);
  8000. }
  8001. } else {
  8002. sel.removeAllRanges();
  8003. sel.addRange(rng);
  8004. }
  8005. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8006. else if (gecko) { this.startGracePeriod(); }
  8007. }
  8008. this.rememberSelection();
  8009. };
  8010. ContentEditableInput.prototype.startGracePeriod = function () {
  8011. var this$1 = this;
  8012. clearTimeout(this.gracePeriod);
  8013. this.gracePeriod = setTimeout(function () {
  8014. this$1.gracePeriod = false;
  8015. if (this$1.selectionChanged())
  8016. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8017. }, 20);
  8018. };
  8019. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8020. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8021. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8022. };
  8023. ContentEditableInput.prototype.rememberSelection = function () {
  8024. var sel = this.getSelection();
  8025. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8026. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8027. };
  8028. ContentEditableInput.prototype.selectionInEditor = function () {
  8029. var sel = this.getSelection();
  8030. if (!sel.rangeCount) { return false }
  8031. var node = sel.getRangeAt(0).commonAncestorContainer;
  8032. return contains(this.div, node)
  8033. };
  8034. ContentEditableInput.prototype.focus = function () {
  8035. if (this.cm.options.readOnly != "nocursor") {
  8036. if (!this.selectionInEditor())
  8037. { this.showSelection(this.prepareSelection(), true); }
  8038. this.div.focus();
  8039. }
  8040. };
  8041. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8042. ContentEditableInput.prototype.getField = function () { return this.div };
  8043. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8044. ContentEditableInput.prototype.receivedFocus = function () {
  8045. var input = this;
  8046. if (this.selectionInEditor())
  8047. { this.pollSelection(); }
  8048. else
  8049. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8050. function poll() {
  8051. if (input.cm.state.focused) {
  8052. input.pollSelection();
  8053. input.polling.set(input.cm.options.pollInterval, poll);
  8054. }
  8055. }
  8056. this.polling.set(this.cm.options.pollInterval, poll);
  8057. };
  8058. ContentEditableInput.prototype.selectionChanged = function () {
  8059. var sel = this.getSelection();
  8060. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8061. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8062. };
  8063. ContentEditableInput.prototype.pollSelection = function () {
  8064. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8065. var sel = this.getSelection(), cm = this.cm;
  8066. // On Android Chrome (version 56, at least), backspacing into an
  8067. // uneditable block element will put the cursor in that element,
  8068. // and then, because it's not editable, hide the virtual keyboard.
  8069. // Because Android doesn't allow us to actually detect backspace
  8070. // presses in a sane way, this code checks for when that happens
  8071. // and simulates a backspace press in this case.
  8072. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8073. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8074. this.blur();
  8075. this.focus();
  8076. return
  8077. }
  8078. if (this.composing) { return }
  8079. this.rememberSelection();
  8080. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8081. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8082. if (anchor && head) { runInOp(cm, function () {
  8083. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8084. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8085. }); }
  8086. };
  8087. ContentEditableInput.prototype.pollContent = function () {
  8088. if (this.readDOMTimeout != null) {
  8089. clearTimeout(this.readDOMTimeout);
  8090. this.readDOMTimeout = null;
  8091. }
  8092. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8093. var from = sel.from(), to = sel.to();
  8094. if (from.ch == 0 && from.line > cm.firstLine())
  8095. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8096. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8097. { to = Pos(to.line + 1, 0); }
  8098. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8099. var fromIndex, fromLine, fromNode;
  8100. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8101. fromLine = lineNo(display.view[0].line);
  8102. fromNode = display.view[0].node;
  8103. } else {
  8104. fromLine = lineNo(display.view[fromIndex].line);
  8105. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8106. }
  8107. var toIndex = findViewIndex(cm, to.line);
  8108. var toLine, toNode;
  8109. if (toIndex == display.view.length - 1) {
  8110. toLine = display.viewTo - 1;
  8111. toNode = display.lineDiv.lastChild;
  8112. } else {
  8113. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8114. toNode = display.view[toIndex + 1].node.previousSibling;
  8115. }
  8116. if (!fromNode) { return false }
  8117. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8118. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8119. while (newText.length > 1 && oldText.length > 1) {
  8120. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8121. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8122. else { break }
  8123. }
  8124. var cutFront = 0, cutEnd = 0;
  8125. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8126. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8127. { ++cutFront; }
  8128. var newBot = lst(newText), oldBot = lst(oldText);
  8129. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8130. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8131. while (cutEnd < maxCutEnd &&
  8132. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8133. { ++cutEnd; }
  8134. // Try to move start of change to start of selection if ambiguous
  8135. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8136. while (cutFront && cutFront > from.ch &&
  8137. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8138. cutFront--;
  8139. cutEnd++;
  8140. }
  8141. }
  8142. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8143. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8144. var chFrom = Pos(fromLine, cutFront);
  8145. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8146. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8147. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8148. return true
  8149. }
  8150. };
  8151. ContentEditableInput.prototype.ensurePolled = function () {
  8152. this.forceCompositionEnd();
  8153. };
  8154. ContentEditableInput.prototype.reset = function () {
  8155. this.forceCompositionEnd();
  8156. };
  8157. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8158. if (!this.composing) { return }
  8159. clearTimeout(this.readDOMTimeout);
  8160. this.composing = null;
  8161. this.updateFromDOM();
  8162. this.div.blur();
  8163. this.div.focus();
  8164. };
  8165. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8166. var this$1 = this;
  8167. if (this.readDOMTimeout != null) { return }
  8168. this.readDOMTimeout = setTimeout(function () {
  8169. this$1.readDOMTimeout = null;
  8170. if (this$1.composing) {
  8171. if (this$1.composing.done) { this$1.composing = null; }
  8172. else { return }
  8173. }
  8174. this$1.updateFromDOM();
  8175. }, 80);
  8176. };
  8177. ContentEditableInput.prototype.updateFromDOM = function () {
  8178. var this$1 = this;
  8179. if (this.cm.isReadOnly() || !this.pollContent())
  8180. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8181. };
  8182. ContentEditableInput.prototype.setUneditable = function (node) {
  8183. node.contentEditable = "false";
  8184. };
  8185. ContentEditableInput.prototype.onKeyPress = function (e) {
  8186. if (e.charCode == 0 || this.composing) { return }
  8187. e.preventDefault();
  8188. if (!this.cm.isReadOnly())
  8189. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8190. };
  8191. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8192. this.div.contentEditable = String(val != "nocursor");
  8193. };
  8194. ContentEditableInput.prototype.onContextMenu = function () {};
  8195. ContentEditableInput.prototype.resetPosition = function () {};
  8196. ContentEditableInput.prototype.needsContentAttribute = true;
  8197. function posToDOM(cm, pos) {
  8198. var view = findViewForLine(cm, pos.line);
  8199. if (!view || view.hidden) { return null }
  8200. var line = getLine(cm.doc, pos.line);
  8201. var info = mapFromLineView(view, line, pos.line);
  8202. var order = getOrder(line, cm.doc.direction), side = "left";
  8203. if (order) {
  8204. var partPos = getBidiPartAt(order, pos.ch);
  8205. side = partPos % 2 ? "right" : "left";
  8206. }
  8207. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8208. result.offset = result.collapse == "right" ? result.end : result.start;
  8209. return result
  8210. }
  8211. function isInGutter(node) {
  8212. for (var scan = node; scan; scan = scan.parentNode)
  8213. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8214. return false
  8215. }
  8216. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8217. function domTextBetween(cm, from, to, fromLine, toLine) {
  8218. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8219. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8220. function close() {
  8221. if (closing) {
  8222. text += lineSep;
  8223. if (extraLinebreak) { text += lineSep; }
  8224. closing = extraLinebreak = false;
  8225. }
  8226. }
  8227. function addText(str) {
  8228. if (str) {
  8229. close();
  8230. text += str;
  8231. }
  8232. }
  8233. function walk(node) {
  8234. if (node.nodeType == 1) {
  8235. var cmText = node.getAttribute("cm-text");
  8236. if (cmText) {
  8237. addText(cmText);
  8238. return
  8239. }
  8240. var markerID = node.getAttribute("cm-marker"), range$$1;
  8241. if (markerID) {
  8242. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8243. if (found.length && (range$$1 = found[0].find(0)))
  8244. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  8245. return
  8246. }
  8247. if (node.getAttribute("contenteditable") == "false") { return }
  8248. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8249. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8250. if (isBlock) { close(); }
  8251. for (var i = 0; i < node.childNodes.length; i++)
  8252. { walk(node.childNodes[i]); }
  8253. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8254. if (isBlock) { closing = true; }
  8255. } else if (node.nodeType == 3) {
  8256. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8257. }
  8258. }
  8259. for (;;) {
  8260. walk(from);
  8261. if (from == to) { break }
  8262. from = from.nextSibling;
  8263. extraLinebreak = false;
  8264. }
  8265. return text
  8266. }
  8267. function domToPos(cm, node, offset) {
  8268. var lineNode;
  8269. if (node == cm.display.lineDiv) {
  8270. lineNode = cm.display.lineDiv.childNodes[offset];
  8271. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8272. node = null; offset = 0;
  8273. } else {
  8274. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8275. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8276. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8277. }
  8278. }
  8279. for (var i = 0; i < cm.display.view.length; i++) {
  8280. var lineView = cm.display.view[i];
  8281. if (lineView.node == lineNode)
  8282. { return locateNodeInLineView(lineView, node, offset) }
  8283. }
  8284. }
  8285. function locateNodeInLineView(lineView, node, offset) {
  8286. var wrapper = lineView.text.firstChild, bad = false;
  8287. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8288. if (node == wrapper) {
  8289. bad = true;
  8290. node = wrapper.childNodes[offset];
  8291. offset = 0;
  8292. if (!node) {
  8293. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8294. return badPos(Pos(lineNo(line), line.text.length), bad)
  8295. }
  8296. }
  8297. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8298. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8299. textNode = node.firstChild;
  8300. if (offset) { offset = textNode.nodeValue.length; }
  8301. }
  8302. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8303. var measure = lineView.measure, maps = measure.maps;
  8304. function find(textNode, topNode, offset) {
  8305. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8306. var map$$1 = i < 0 ? measure.map : maps[i];
  8307. for (var j = 0; j < map$$1.length; j += 3) {
  8308. var curNode = map$$1[j + 2];
  8309. if (curNode == textNode || curNode == topNode) {
  8310. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8311. var ch = map$$1[j] + offset;
  8312. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  8313. return Pos(line, ch)
  8314. }
  8315. }
  8316. }
  8317. }
  8318. var found = find(textNode, topNode, offset);
  8319. if (found) { return badPos(found, bad) }
  8320. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8321. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8322. found = find(after, after.firstChild, 0);
  8323. if (found)
  8324. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8325. else
  8326. { dist += after.textContent.length; }
  8327. }
  8328. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8329. found = find(before, before.firstChild, -1);
  8330. if (found)
  8331. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8332. else
  8333. { dist$1 += before.textContent.length; }
  8334. }
  8335. }
  8336. // TEXTAREA INPUT STYLE
  8337. var TextareaInput = function(cm) {
  8338. this.cm = cm;
  8339. // See input.poll and input.reset
  8340. this.prevInput = "";
  8341. // Flag that indicates whether we expect input to appear real soon
  8342. // now (after some event like 'keypress' or 'input') and are
  8343. // polling intensively.
  8344. this.pollingFast = false;
  8345. // Self-resetting timeout for the poller
  8346. this.polling = new Delayed();
  8347. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8348. this.hasSelection = false;
  8349. this.composing = null;
  8350. };
  8351. TextareaInput.prototype.init = function (display) {
  8352. var this$1 = this;
  8353. var input = this, cm = this.cm;
  8354. this.createField(display);
  8355. var te = this.textarea;
  8356. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8357. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8358. if (ios) { te.style.width = "0px"; }
  8359. on(te, "input", function () {
  8360. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8361. input.poll();
  8362. });
  8363. on(te, "paste", function (e) {
  8364. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8365. cm.state.pasteIncoming = +new Date;
  8366. input.fastPoll();
  8367. });
  8368. function prepareCopyCut(e) {
  8369. if (signalDOMEvent(cm, e)) { return }
  8370. if (cm.somethingSelected()) {
  8371. setLastCopied({lineWise: false, text: cm.getSelections()});
  8372. } else if (!cm.options.lineWiseCopyCut) {
  8373. return
  8374. } else {
  8375. var ranges = copyableRanges(cm);
  8376. setLastCopied({lineWise: true, text: ranges.text});
  8377. if (e.type == "cut") {
  8378. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8379. } else {
  8380. input.prevInput = "";
  8381. te.value = ranges.text.join("\n");
  8382. selectInput(te);
  8383. }
  8384. }
  8385. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8386. }
  8387. on(te, "cut", prepareCopyCut);
  8388. on(te, "copy", prepareCopyCut);
  8389. on(display.scroller, "paste", function (e) {
  8390. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8391. if (!te.dispatchEvent) {
  8392. cm.state.pasteIncoming = +new Date;
  8393. input.focus();
  8394. return
  8395. }
  8396. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8397. var event = new Event("paste");
  8398. event.clipboardData = e.clipboardData;
  8399. te.dispatchEvent(event);
  8400. });
  8401. // Prevent normal selection in the editor (we handle our own)
  8402. on(display.lineSpace, "selectstart", function (e) {
  8403. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8404. });
  8405. on(te, "compositionstart", function () {
  8406. var start = cm.getCursor("from");
  8407. if (input.composing) { input.composing.range.clear(); }
  8408. input.composing = {
  8409. start: start,
  8410. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8411. };
  8412. });
  8413. on(te, "compositionend", function () {
  8414. if (input.composing) {
  8415. input.poll();
  8416. input.composing.range.clear();
  8417. input.composing = null;
  8418. }
  8419. });
  8420. };
  8421. TextareaInput.prototype.createField = function (_display) {
  8422. // Wraps and hides input textarea
  8423. this.wrapper = hiddenTextarea();
  8424. // The semihidden textarea that is focused when the editor is
  8425. // focused, and receives input.
  8426. this.textarea = this.wrapper.firstChild;
  8427. };
  8428. TextareaInput.prototype.prepareSelection = function () {
  8429. // Redraw the selection and/or cursor
  8430. var cm = this.cm, display = cm.display, doc = cm.doc;
  8431. var result = prepareSelection(cm);
  8432. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8433. if (cm.options.moveInputWithCursor) {
  8434. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8435. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8436. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8437. headPos.top + lineOff.top - wrapOff.top));
  8438. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8439. headPos.left + lineOff.left - wrapOff.left));
  8440. }
  8441. return result
  8442. };
  8443. TextareaInput.prototype.showSelection = function (drawn) {
  8444. var cm = this.cm, display = cm.display;
  8445. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8446. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8447. if (drawn.teTop != null) {
  8448. this.wrapper.style.top = drawn.teTop + "px";
  8449. this.wrapper.style.left = drawn.teLeft + "px";
  8450. }
  8451. };
  8452. // Reset the input to correspond to the selection (or to be empty,
  8453. // when not typing and nothing is selected)
  8454. TextareaInput.prototype.reset = function (typing) {
  8455. if (this.contextMenuPending || this.composing) { return }
  8456. var cm = this.cm;
  8457. if (cm.somethingSelected()) {
  8458. this.prevInput = "";
  8459. var content = cm.getSelection();
  8460. this.textarea.value = content;
  8461. if (cm.state.focused) { selectInput(this.textarea); }
  8462. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8463. } else if (!typing) {
  8464. this.prevInput = this.textarea.value = "";
  8465. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8466. }
  8467. };
  8468. TextareaInput.prototype.getField = function () { return this.textarea };
  8469. TextareaInput.prototype.supportsTouch = function () { return false };
  8470. TextareaInput.prototype.focus = function () {
  8471. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8472. try { this.textarea.focus(); }
  8473. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8474. }
  8475. };
  8476. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8477. TextareaInput.prototype.resetPosition = function () {
  8478. this.wrapper.style.top = this.wrapper.style.left = 0;
  8479. };
  8480. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8481. // Poll for input changes, using the normal rate of polling. This
  8482. // runs as long as the editor is focused.
  8483. TextareaInput.prototype.slowPoll = function () {
  8484. var this$1 = this;
  8485. if (this.pollingFast) { return }
  8486. this.polling.set(this.cm.options.pollInterval, function () {
  8487. this$1.poll();
  8488. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8489. });
  8490. };
  8491. // When an event has just come in that is likely to add or change
  8492. // something in the input textarea, we poll faster, to ensure that
  8493. // the change appears on the screen quickly.
  8494. TextareaInput.prototype.fastPoll = function () {
  8495. var missed = false, input = this;
  8496. input.pollingFast = true;
  8497. function p() {
  8498. var changed = input.poll();
  8499. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8500. else {input.pollingFast = false; input.slowPoll();}
  8501. }
  8502. input.polling.set(20, p);
  8503. };
  8504. // Read input from the textarea, and update the document to match.
  8505. // When something is selected, it is present in the textarea, and
  8506. // selected (unless it is huge, in which case a placeholder is
  8507. // used). When nothing is selected, the cursor sits after previously
  8508. // seen text (can be empty), which is stored in prevInput (we must
  8509. // not reset the textarea when typing, because that breaks IME).
  8510. TextareaInput.prototype.poll = function () {
  8511. var this$1 = this;
  8512. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8513. // Since this is called a *lot*, try to bail out as cheaply as
  8514. // possible when it is clear that nothing happened. hasSelection
  8515. // will be the case when there is a lot of text in the textarea,
  8516. // in which case reading its value would be expensive.
  8517. if (this.contextMenuPending || !cm.state.focused ||
  8518. (hasSelection(input) && !prevInput && !this.composing) ||
  8519. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8520. { return false }
  8521. var text = input.value;
  8522. // If nothing changed, bail.
  8523. if (text == prevInput && !cm.somethingSelected()) { return false }
  8524. // Work around nonsensical selection resetting in IE9/10, and
  8525. // inexplicable appearance of private area unicode characters on
  8526. // some key combos in Mac (#2689).
  8527. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8528. mac && /[\uf700-\uf7ff]/.test(text)) {
  8529. cm.display.input.reset();
  8530. return false
  8531. }
  8532. if (cm.doc.sel == cm.display.selForContextMenu) {
  8533. var first = text.charCodeAt(0);
  8534. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8535. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8536. }
  8537. // Find the part of the input that is actually new
  8538. var same = 0, l = Math.min(prevInput.length, text.length);
  8539. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8540. runInOp(cm, function () {
  8541. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8542. null, this$1.composing ? "*compose" : null);
  8543. // Don't leave long text in the textarea, since it makes further polling slow
  8544. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8545. else { this$1.prevInput = text; }
  8546. if (this$1.composing) {
  8547. this$1.composing.range.clear();
  8548. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8549. {className: "CodeMirror-composing"});
  8550. }
  8551. });
  8552. return true
  8553. };
  8554. TextareaInput.prototype.ensurePolled = function () {
  8555. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8556. };
  8557. TextareaInput.prototype.onKeyPress = function () {
  8558. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8559. this.fastPoll();
  8560. };
  8561. TextareaInput.prototype.onContextMenu = function (e) {
  8562. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8563. if (input.contextMenuPending) { input.contextMenuPending(); }
  8564. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8565. if (!pos || presto) { return } // Opera is difficult.
  8566. // Reset the current text selection only if the click is done outside of the selection
  8567. // and 'resetSelectionOnContextMenu' option is true.
  8568. var reset = cm.options.resetSelectionOnContextMenu;
  8569. if (reset && cm.doc.sel.contains(pos) == -1)
  8570. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8571. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8572. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8573. input.wrapper.style.cssText = "position: static";
  8574. 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);";
  8575. var oldScrollY;
  8576. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  8577. display.input.focus();
  8578. if (webkit) { window.scrollTo(null, oldScrollY); }
  8579. display.input.reset();
  8580. // Adds "Select all" to context menu in FF
  8581. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8582. input.contextMenuPending = rehide;
  8583. display.selForContextMenu = cm.doc.sel;
  8584. clearTimeout(display.detectingSelectAll);
  8585. // Select-all will be greyed out if there's nothing to select, so
  8586. // this adds a zero-width space so that we can later check whether
  8587. // it got selected.
  8588. function prepareSelectAllHack() {
  8589. if (te.selectionStart != null) {
  8590. var selected = cm.somethingSelected();
  8591. var extval = "\u200b" + (selected ? te.value : "");
  8592. te.value = "\u21da"; // Used to catch context-menu undo
  8593. te.value = extval;
  8594. input.prevInput = selected ? "" : "\u200b";
  8595. te.selectionStart = 1; te.selectionEnd = extval.length;
  8596. // Re-set this, in case some other handler touched the
  8597. // selection in the meantime.
  8598. display.selForContextMenu = cm.doc.sel;
  8599. }
  8600. }
  8601. function rehide() {
  8602. if (input.contextMenuPending != rehide) { return }
  8603. input.contextMenuPending = false;
  8604. input.wrapper.style.cssText = oldWrapperCSS;
  8605. te.style.cssText = oldCSS;
  8606. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8607. // Try to detect the user choosing select-all
  8608. if (te.selectionStart != null) {
  8609. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8610. var i = 0, poll = function () {
  8611. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8612. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8613. operation(cm, selectAll)(cm);
  8614. } else if (i++ < 10) {
  8615. display.detectingSelectAll = setTimeout(poll, 500);
  8616. } else {
  8617. display.selForContextMenu = null;
  8618. display.input.reset();
  8619. }
  8620. };
  8621. display.detectingSelectAll = setTimeout(poll, 200);
  8622. }
  8623. }
  8624. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8625. if (captureRightClick) {
  8626. e_stop(e);
  8627. var mouseup = function () {
  8628. off(window, "mouseup", mouseup);
  8629. setTimeout(rehide, 20);
  8630. };
  8631. on(window, "mouseup", mouseup);
  8632. } else {
  8633. setTimeout(rehide, 50);
  8634. }
  8635. };
  8636. TextareaInput.prototype.readOnlyChanged = function (val) {
  8637. if (!val) { this.reset(); }
  8638. this.textarea.disabled = val == "nocursor";
  8639. };
  8640. TextareaInput.prototype.setUneditable = function () {};
  8641. TextareaInput.prototype.needsContentAttribute = false;
  8642. function fromTextArea(textarea, options) {
  8643. options = options ? copyObj(options) : {};
  8644. options.value = textarea.value;
  8645. if (!options.tabindex && textarea.tabIndex)
  8646. { options.tabindex = textarea.tabIndex; }
  8647. if (!options.placeholder && textarea.placeholder)
  8648. { options.placeholder = textarea.placeholder; }
  8649. // Set autofocus to true if this textarea is focused, or if it has
  8650. // autofocus and no other element is focused.
  8651. if (options.autofocus == null) {
  8652. var hasFocus = activeElt();
  8653. options.autofocus = hasFocus == textarea ||
  8654. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8655. }
  8656. function save() {textarea.value = cm.getValue();}
  8657. var realSubmit;
  8658. if (textarea.form) {
  8659. on(textarea.form, "submit", save);
  8660. // Deplorable hack to make the submit method do the right thing.
  8661. if (!options.leaveSubmitMethodAlone) {
  8662. var form = textarea.form;
  8663. realSubmit = form.submit;
  8664. try {
  8665. var wrappedSubmit = form.submit = function () {
  8666. save();
  8667. form.submit = realSubmit;
  8668. form.submit();
  8669. form.submit = wrappedSubmit;
  8670. };
  8671. } catch(e) {}
  8672. }
  8673. }
  8674. options.finishInit = function (cm) {
  8675. cm.save = save;
  8676. cm.getTextArea = function () { return textarea; };
  8677. cm.toTextArea = function () {
  8678. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8679. save();
  8680. textarea.parentNode.removeChild(cm.getWrapperElement());
  8681. textarea.style.display = "";
  8682. if (textarea.form) {
  8683. off(textarea.form, "submit", save);
  8684. if (typeof textarea.form.submit == "function")
  8685. { textarea.form.submit = realSubmit; }
  8686. }
  8687. };
  8688. };
  8689. textarea.style.display = "none";
  8690. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8691. options);
  8692. return cm
  8693. }
  8694. function addLegacyProps(CodeMirror) {
  8695. CodeMirror.off = off;
  8696. CodeMirror.on = on;
  8697. CodeMirror.wheelEventPixels = wheelEventPixels;
  8698. CodeMirror.Doc = Doc;
  8699. CodeMirror.splitLines = splitLinesAuto;
  8700. CodeMirror.countColumn = countColumn;
  8701. CodeMirror.findColumn = findColumn;
  8702. CodeMirror.isWordChar = isWordCharBasic;
  8703. CodeMirror.Pass = Pass;
  8704. CodeMirror.signal = signal;
  8705. CodeMirror.Line = Line;
  8706. CodeMirror.changeEnd = changeEnd;
  8707. CodeMirror.scrollbarModel = scrollbarModel;
  8708. CodeMirror.Pos = Pos;
  8709. CodeMirror.cmpPos = cmp;
  8710. CodeMirror.modes = modes;
  8711. CodeMirror.mimeModes = mimeModes;
  8712. CodeMirror.resolveMode = resolveMode;
  8713. CodeMirror.getMode = getMode;
  8714. CodeMirror.modeExtensions = modeExtensions;
  8715. CodeMirror.extendMode = extendMode;
  8716. CodeMirror.copyState = copyState;
  8717. CodeMirror.startState = startState;
  8718. CodeMirror.innerMode = innerMode;
  8719. CodeMirror.commands = commands;
  8720. CodeMirror.keyMap = keyMap;
  8721. CodeMirror.keyName = keyName;
  8722. CodeMirror.isModifierKey = isModifierKey;
  8723. CodeMirror.lookupKey = lookupKey;
  8724. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8725. CodeMirror.StringStream = StringStream;
  8726. CodeMirror.SharedTextMarker = SharedTextMarker;
  8727. CodeMirror.TextMarker = TextMarker;
  8728. CodeMirror.LineWidget = LineWidget;
  8729. CodeMirror.e_preventDefault = e_preventDefault;
  8730. CodeMirror.e_stopPropagation = e_stopPropagation;
  8731. CodeMirror.e_stop = e_stop;
  8732. CodeMirror.addClass = addClass;
  8733. CodeMirror.contains = contains;
  8734. CodeMirror.rmClass = rmClass;
  8735. CodeMirror.keyNames = keyNames;
  8736. }
  8737. // EDITOR CONSTRUCTOR
  8738. defineOptions(CodeMirror);
  8739. addEditorMethods(CodeMirror);
  8740. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8741. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8742. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8743. { CodeMirror.prototype[prop] = (function(method) {
  8744. return function() {return method.apply(this.doc, arguments)}
  8745. })(Doc.prototype[prop]); } }
  8746. eventMixin(Doc);
  8747. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8748. // Extra arguments are stored as the mode's dependencies, which is
  8749. // used by (legacy) mechanisms like loadmode.js to automatically
  8750. // load a mode. (Preferred mechanism is the require/define calls.)
  8751. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8752. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  8753. defineMode.apply(this, arguments);
  8754. };
  8755. CodeMirror.defineMIME = defineMIME;
  8756. // Minimal default mode.
  8757. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8758. CodeMirror.defineMIME("text/plain", "null");
  8759. // EXTENSIONS
  8760. CodeMirror.defineExtension = function (name, func) {
  8761. CodeMirror.prototype[name] = func;
  8762. };
  8763. CodeMirror.defineDocExtension = function (name, func) {
  8764. Doc.prototype[name] = func;
  8765. };
  8766. CodeMirror.fromTextArea = fromTextArea;
  8767. addLegacyProps(CodeMirror);
  8768. CodeMirror.version = "5.45.1";
  8769. return CodeMirror;
  8770. })));