codemirror.js 389 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800
  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 = global || self, 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 = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  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() {
  157. this.id = null;
  158. this.f = null;
  159. this.time = 0;
  160. this.handler = bind(this.onTimeout, this);
  161. };
  162. Delayed.prototype.onTimeout = function (self) {
  163. self.id = 0;
  164. if (self.time <= +new Date) {
  165. self.f();
  166. } else {
  167. setTimeout(self.handler, self.time - +new Date);
  168. }
  169. };
  170. Delayed.prototype.set = function (ms, f) {
  171. this.f = f;
  172. var time = +new Date + ms;
  173. if (!this.id || time < this.time) {
  174. clearTimeout(this.id);
  175. this.id = setTimeout(this.handler, ms);
  176. this.time = time;
  177. }
  178. };
  179. function indexOf(array, elt) {
  180. for (var i = 0; i < array.length; ++i)
  181. { if (array[i] == elt) { return i } }
  182. return -1
  183. }
  184. // Number of pixels added to scroller and sizer to hide scrollbar
  185. var scrollerGap = 50;
  186. // Returned or thrown by various protocols to signal 'I'm not
  187. // handling this'.
  188. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  189. // Reused option objects for setSelection & friends
  190. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  191. // The inverse of countColumn -- find the offset that corresponds to
  192. // a particular column.
  193. function findColumn(string, goal, tabSize) {
  194. for (var pos = 0, col = 0;;) {
  195. var nextTab = string.indexOf("\t", pos);
  196. if (nextTab == -1) { nextTab = string.length; }
  197. var skipped = nextTab - pos;
  198. if (nextTab == string.length || col + skipped >= goal)
  199. { return pos + Math.min(skipped, goal - col) }
  200. col += nextTab - pos;
  201. col += tabSize - (col % tabSize);
  202. pos = nextTab + 1;
  203. if (col >= goal) { return pos }
  204. }
  205. }
  206. var spaceStrs = [""];
  207. function spaceStr(n) {
  208. while (spaceStrs.length <= n)
  209. { spaceStrs.push(lst(spaceStrs) + " "); }
  210. return spaceStrs[n]
  211. }
  212. function lst(arr) { return arr[arr.length-1] }
  213. function map(array, f) {
  214. var out = [];
  215. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  216. return out
  217. }
  218. function insertSorted(array, value, score) {
  219. var pos = 0, priority = score(value);
  220. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  221. array.splice(pos, 0, value);
  222. }
  223. function nothing() {}
  224. function createObj(base, props) {
  225. var inst;
  226. if (Object.create) {
  227. inst = Object.create(base);
  228. } else {
  229. nothing.prototype = base;
  230. inst = new nothing();
  231. }
  232. if (props) { copyObj(props, inst); }
  233. return inst
  234. }
  235. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  236. function isWordCharBasic(ch) {
  237. return /\w/.test(ch) || ch > "\x80" &&
  238. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  239. }
  240. function isWordChar(ch, helper) {
  241. if (!helper) { return isWordCharBasic(ch) }
  242. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  243. return helper.test(ch)
  244. }
  245. function isEmpty(obj) {
  246. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  247. return true
  248. }
  249. // Extending unicode characters. A series of a non-extending char +
  250. // any number of extending chars is treated as a single unit as far
  251. // as editing and measuring is concerned. This is not fully correct,
  252. // since some scripts/fonts/browsers also treat other configurations
  253. // of code points as a group.
  254. 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]/;
  255. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  256. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  257. function skipExtendingChars(str, pos, dir) {
  258. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  259. return pos
  260. }
  261. // Returns the value from the range [`from`; `to`] that satisfies
  262. // `pred` and is closest to `from`. Assumes that at least `to`
  263. // satisfies `pred`. Supports `from` being greater than `to`.
  264. function findFirst(pred, from, to) {
  265. // At any point we are certain `to` satisfies `pred`, don't know
  266. // whether `from` does.
  267. var dir = from > to ? -1 : 1;
  268. for (;;) {
  269. if (from == to) { return from }
  270. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  271. if (mid == from) { return pred(mid) ? from : to }
  272. if (pred(mid)) { to = mid; }
  273. else { from = mid + dir; }
  274. }
  275. }
  276. // BIDI HELPERS
  277. function iterateBidiSections(order, from, to, f) {
  278. if (!order) { return f(from, to, "ltr", 0) }
  279. var found = false;
  280. for (var i = 0; i < order.length; ++i) {
  281. var part = order[i];
  282. if (part.from < to && part.to > from || from == to && part.to == from) {
  283. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  284. found = true;
  285. }
  286. }
  287. if (!found) { f(from, to, "ltr"); }
  288. }
  289. var bidiOther = null;
  290. function getBidiPartAt(order, ch, sticky) {
  291. var found;
  292. bidiOther = null;
  293. for (var i = 0; i < order.length; ++i) {
  294. var cur = order[i];
  295. if (cur.from < ch && cur.to > ch) { return i }
  296. if (cur.to == ch) {
  297. if (cur.from != cur.to && sticky == "before") { found = i; }
  298. else { bidiOther = i; }
  299. }
  300. if (cur.from == ch) {
  301. if (cur.from != cur.to && sticky != "before") { found = i; }
  302. else { bidiOther = i; }
  303. }
  304. }
  305. return found != null ? found : bidiOther
  306. }
  307. // Bidirectional ordering algorithm
  308. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  309. // that this (partially) implements.
  310. // One-char codes used for character types:
  311. // L (L): Left-to-Right
  312. // R (R): Right-to-Left
  313. // r (AL): Right-to-Left Arabic
  314. // 1 (EN): European Number
  315. // + (ES): European Number Separator
  316. // % (ET): European Number Terminator
  317. // n (AN): Arabic Number
  318. // , (CS): Common Number Separator
  319. // m (NSM): Non-Spacing Mark
  320. // b (BN): Boundary Neutral
  321. // s (B): Paragraph Separator
  322. // t (S): Segment Separator
  323. // w (WS): Whitespace
  324. // N (ON): Other Neutrals
  325. // Returns null if characters are ordered as they appear
  326. // (left-to-right), or an array of sections ({from, to, level}
  327. // objects) in the order in which they occur visually.
  328. var bidiOrdering = (function() {
  329. // Character types for codepoints 0 to 0xff
  330. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  331. // Character types for codepoints 0x600 to 0x6f9
  332. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  333. function charType(code) {
  334. if (code <= 0xf7) { return lowTypes.charAt(code) }
  335. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  336. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  337. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  338. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  339. else if (code == 0x200c) { return "b" }
  340. else { return "L" }
  341. }
  342. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  343. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  344. function BidiSpan(level, from, to) {
  345. this.level = level;
  346. this.from = from; this.to = to;
  347. }
  348. return function(str, direction) {
  349. var outerType = direction == "ltr" ? "L" : "R";
  350. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  351. var len = str.length, types = [];
  352. for (var i = 0; i < len; ++i)
  353. { types.push(charType(str.charCodeAt(i))); }
  354. // W1. Examine each non-spacing mark (NSM) in the level run, and
  355. // change the type of the NSM to the type of the previous
  356. // character. If the NSM is at the start of the level run, it will
  357. // get the type of sor.
  358. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  359. var type = types[i$1];
  360. if (type == "m") { types[i$1] = prev; }
  361. else { prev = type; }
  362. }
  363. // W2. Search backwards from each instance of a European number
  364. // until the first strong type (R, L, AL, or sor) is found. If an
  365. // AL is found, change the type of the European number to Arabic
  366. // number.
  367. // W3. Change all ALs to R.
  368. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  369. var type$1 = types[i$2];
  370. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  371. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  372. }
  373. // W4. A single European separator between two European numbers
  374. // changes to a European number. A single common separator between
  375. // two numbers of the same type changes to that type.
  376. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  377. var type$2 = types[i$3];
  378. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  379. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  380. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  381. prev$1 = type$2;
  382. }
  383. // W5. A sequence of European terminators adjacent to European
  384. // numbers changes to all European numbers.
  385. // W6. Otherwise, separators and terminators change to Other
  386. // Neutral.
  387. for (var i$4 = 0; i$4 < len; ++i$4) {
  388. var type$3 = types[i$4];
  389. if (type$3 == ",") { types[i$4] = "N"; }
  390. else if (type$3 == "%") {
  391. var end = (void 0);
  392. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  393. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  394. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  395. i$4 = end - 1;
  396. }
  397. }
  398. // W7. Search backwards from each instance of a European number
  399. // until the first strong type (R, L, or sor) is found. If an L is
  400. // found, then change the type of the European number to L.
  401. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  402. var type$4 = types[i$5];
  403. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  404. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  405. }
  406. // N1. A sequence of neutrals takes the direction of the
  407. // surrounding strong text if the text on both sides has the same
  408. // direction. European and Arabic numbers act as if they were R in
  409. // terms of their influence on neutrals. Start-of-level-run (sor)
  410. // and end-of-level-run (eor) are used at level run boundaries.
  411. // N2. Any remaining neutrals take the embedding direction.
  412. for (var i$6 = 0; i$6 < len; ++i$6) {
  413. if (isNeutral.test(types[i$6])) {
  414. var end$1 = (void 0);
  415. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  416. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  417. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  418. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  419. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  420. i$6 = end$1 - 1;
  421. }
  422. }
  423. // Here we depart from the documented algorithm, in order to avoid
  424. // building up an actual levels array. Since there are only three
  425. // levels (0, 1, 2) in an implementation that doesn't take
  426. // explicit embedding into account, we can build up the order on
  427. // the fly, without following the level-based algorithm.
  428. var order = [], m;
  429. for (var i$7 = 0; i$7 < len;) {
  430. if (countsAsLeft.test(types[i$7])) {
  431. var start = i$7;
  432. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  433. order.push(new BidiSpan(0, start, i$7));
  434. } else {
  435. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  436. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  437. for (var j$2 = pos; j$2 < i$7;) {
  438. if (countsAsNum.test(types[j$2])) {
  439. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  440. var nstart = j$2;
  441. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  442. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  443. at += isRTL;
  444. pos = j$2;
  445. } else { ++j$2; }
  446. }
  447. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  448. }
  449. }
  450. if (direction == "ltr") {
  451. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  452. order[0].from = m[0].length;
  453. order.unshift(new BidiSpan(0, 0, m[0].length));
  454. }
  455. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  456. lst(order).to -= m[0].length;
  457. order.push(new BidiSpan(0, len - m[0].length, len));
  458. }
  459. }
  460. return direction == "rtl" ? order.reverse() : order
  461. }
  462. })();
  463. // Get the bidi ordering for the given line (and cache it). Returns
  464. // false for lines that are fully left-to-right, and an array of
  465. // BidiSpan objects otherwise.
  466. function getOrder(line, direction) {
  467. var order = line.order;
  468. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  469. return order
  470. }
  471. // EVENT HANDLING
  472. // Lightweight event framework. on/off also work on DOM nodes,
  473. // registering native DOM handlers.
  474. var noHandlers = [];
  475. var on = function(emitter, type, f) {
  476. if (emitter.addEventListener) {
  477. emitter.addEventListener(type, f, false);
  478. } else if (emitter.attachEvent) {
  479. emitter.attachEvent("on" + type, f);
  480. } else {
  481. var map = emitter._handlers || (emitter._handlers = {});
  482. map[type] = (map[type] || noHandlers).concat(f);
  483. }
  484. };
  485. function getHandlers(emitter, type) {
  486. return emitter._handlers && emitter._handlers[type] || noHandlers
  487. }
  488. function off(emitter, type, f) {
  489. if (emitter.removeEventListener) {
  490. emitter.removeEventListener(type, f, false);
  491. } else if (emitter.detachEvent) {
  492. emitter.detachEvent("on" + type, f);
  493. } else {
  494. var map = emitter._handlers, arr = map && map[type];
  495. if (arr) {
  496. var index = indexOf(arr, f);
  497. if (index > -1)
  498. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  499. }
  500. }
  501. }
  502. function signal(emitter, type /*, values...*/) {
  503. var handlers = getHandlers(emitter, type);
  504. if (!handlers.length) { return }
  505. var args = Array.prototype.slice.call(arguments, 2);
  506. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  507. }
  508. // The DOM events that CodeMirror handles can be overridden by
  509. // registering a (non-DOM) handler on the editor for the event name,
  510. // and preventDefault-ing the event in that handler.
  511. function signalDOMEvent(cm, e, override) {
  512. if (typeof e == "string")
  513. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  514. signal(cm, override || e.type, cm, e);
  515. return e_defaultPrevented(e) || e.codemirrorIgnore
  516. }
  517. function signalCursorActivity(cm) {
  518. var arr = cm._handlers && cm._handlers.cursorActivity;
  519. if (!arr) { return }
  520. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  521. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  522. { set.push(arr[i]); } }
  523. }
  524. function hasHandler(emitter, type) {
  525. return getHandlers(emitter, type).length > 0
  526. }
  527. // Add on and off methods to a constructor's prototype, to make
  528. // registering events on such objects more convenient.
  529. function eventMixin(ctor) {
  530. ctor.prototype.on = function(type, f) {on(this, type, f);};
  531. ctor.prototype.off = function(type, f) {off(this, type, f);};
  532. }
  533. // Due to the fact that we still support jurassic IE versions, some
  534. // compatibility wrappers are needed.
  535. function e_preventDefault(e) {
  536. if (e.preventDefault) { e.preventDefault(); }
  537. else { e.returnValue = false; }
  538. }
  539. function e_stopPropagation(e) {
  540. if (e.stopPropagation) { e.stopPropagation(); }
  541. else { e.cancelBubble = true; }
  542. }
  543. function e_defaultPrevented(e) {
  544. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  545. }
  546. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  547. function e_target(e) {return e.target || e.srcElement}
  548. function e_button(e) {
  549. var b = e.which;
  550. if (b == null) {
  551. if (e.button & 1) { b = 1; }
  552. else if (e.button & 2) { b = 3; }
  553. else if (e.button & 4) { b = 2; }
  554. }
  555. if (mac && e.ctrlKey && b == 1) { b = 3; }
  556. return b
  557. }
  558. // Detect drag-and-drop
  559. var dragAndDrop = function() {
  560. // There is *some* kind of drag-and-drop support in IE6-8, but I
  561. // couldn't get it to work yet.
  562. if (ie && ie_version < 9) { return false }
  563. var div = elt('div');
  564. return "draggable" in div || "dragDrop" in div
  565. }();
  566. var zwspSupported;
  567. function zeroWidthElement(measure) {
  568. if (zwspSupported == null) {
  569. var test = elt("span", "\u200b");
  570. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  571. if (measure.firstChild.offsetHeight != 0)
  572. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  573. }
  574. var node = zwspSupported ? elt("span", "\u200b") :
  575. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  576. node.setAttribute("cm-text", "");
  577. return node
  578. }
  579. // Feature-detect IE's crummy client rect reporting for bidi text
  580. var badBidiRects;
  581. function hasBadBidiRects(measure) {
  582. if (badBidiRects != null) { return badBidiRects }
  583. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  584. var r0 = range(txt, 0, 1).getBoundingClientRect();
  585. var r1 = range(txt, 1, 2).getBoundingClientRect();
  586. removeChildren(measure);
  587. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  588. return badBidiRects = (r1.right - r0.right < 3)
  589. }
  590. // See if "".split is the broken IE version, if so, provide an
  591. // alternative way to split lines.
  592. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  593. var pos = 0, result = [], l = string.length;
  594. while (pos <= l) {
  595. var nl = string.indexOf("\n", pos);
  596. if (nl == -1) { nl = string.length; }
  597. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  598. var rt = line.indexOf("\r");
  599. if (rt != -1) {
  600. result.push(line.slice(0, rt));
  601. pos += rt + 1;
  602. } else {
  603. result.push(line);
  604. pos = nl + 1;
  605. }
  606. }
  607. return result
  608. } : function (string) { return string.split(/\r\n?|\n/); };
  609. var hasSelection = window.getSelection ? function (te) {
  610. try { return te.selectionStart != te.selectionEnd }
  611. catch(e) { return false }
  612. } : function (te) {
  613. var range;
  614. try {range = te.ownerDocument.selection.createRange();}
  615. catch(e) {}
  616. if (!range || range.parentElement() != te) { return false }
  617. return range.compareEndPoints("StartToEnd", range) != 0
  618. };
  619. var hasCopyEvent = (function () {
  620. var e = elt("div");
  621. if ("oncopy" in e) { return true }
  622. e.setAttribute("oncopy", "return;");
  623. return typeof e.oncopy == "function"
  624. })();
  625. var badZoomedRects = null;
  626. function hasBadZoomedRects(measure) {
  627. if (badZoomedRects != null) { return badZoomedRects }
  628. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  629. var normal = node.getBoundingClientRect();
  630. var fromRange = range(node, 0, 1).getBoundingClientRect();
  631. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  632. }
  633. // Known modes, by name and by MIME
  634. var modes = {}, mimeModes = {};
  635. // Extra arguments are stored as the mode's dependencies, which is
  636. // used by (legacy) mechanisms like loadmode.js to automatically
  637. // load a mode. (Preferred mechanism is the require/define calls.)
  638. function defineMode(name, mode) {
  639. if (arguments.length > 2)
  640. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  641. modes[name] = mode;
  642. }
  643. function defineMIME(mime, spec) {
  644. mimeModes[mime] = spec;
  645. }
  646. // Given a MIME type, a {name, ...options} config object, or a name
  647. // string, return a mode config object.
  648. function resolveMode(spec) {
  649. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  650. spec = mimeModes[spec];
  651. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  652. var found = mimeModes[spec.name];
  653. if (typeof found == "string") { found = {name: found}; }
  654. spec = createObj(found, spec);
  655. spec.name = found.name;
  656. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  657. return resolveMode("application/xml")
  658. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  659. return resolveMode("application/json")
  660. }
  661. if (typeof spec == "string") { return {name: spec} }
  662. else { return spec || {name: "null"} }
  663. }
  664. // Given a mode spec (anything that resolveMode accepts), find and
  665. // initialize an actual mode object.
  666. function getMode(options, spec) {
  667. spec = resolveMode(spec);
  668. var mfactory = modes[spec.name];
  669. if (!mfactory) { return getMode(options, "text/plain") }
  670. var modeObj = mfactory(options, spec);
  671. if (modeExtensions.hasOwnProperty(spec.name)) {
  672. var exts = modeExtensions[spec.name];
  673. for (var prop in exts) {
  674. if (!exts.hasOwnProperty(prop)) { continue }
  675. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  676. modeObj[prop] = exts[prop];
  677. }
  678. }
  679. modeObj.name = spec.name;
  680. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  681. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  682. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  683. return modeObj
  684. }
  685. // This can be used to attach properties to mode objects from
  686. // outside the actual mode definition.
  687. var modeExtensions = {};
  688. function extendMode(mode, properties) {
  689. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  690. copyObj(properties, exts);
  691. }
  692. function copyState(mode, state) {
  693. if (state === true) { return state }
  694. if (mode.copyState) { return mode.copyState(state) }
  695. var nstate = {};
  696. for (var n in state) {
  697. var val = state[n];
  698. if (val instanceof Array) { val = val.concat([]); }
  699. nstate[n] = val;
  700. }
  701. return nstate
  702. }
  703. // Given a mode and a state (for that mode), find the inner mode and
  704. // state at the position that the state refers to.
  705. function innerMode(mode, state) {
  706. var info;
  707. while (mode.innerMode) {
  708. info = mode.innerMode(state);
  709. if (!info || info.mode == mode) { break }
  710. state = info.state;
  711. mode = info.mode;
  712. }
  713. return info || {mode: mode, state: state}
  714. }
  715. function startState(mode, a1, a2) {
  716. return mode.startState ? mode.startState(a1, a2) : true
  717. }
  718. // STRING STREAM
  719. // Fed to the mode parsers, provides helper functions to make
  720. // parsers more succinct.
  721. var StringStream = function(string, tabSize, lineOracle) {
  722. this.pos = this.start = 0;
  723. this.string = string;
  724. this.tabSize = tabSize || 8;
  725. this.lastColumnPos = this.lastColumnValue = 0;
  726. this.lineStart = 0;
  727. this.lineOracle = lineOracle;
  728. };
  729. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  730. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  731. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  732. StringStream.prototype.next = function () {
  733. if (this.pos < this.string.length)
  734. { return this.string.charAt(this.pos++) }
  735. };
  736. StringStream.prototype.eat = function (match) {
  737. var ch = this.string.charAt(this.pos);
  738. var ok;
  739. if (typeof match == "string") { ok = ch == match; }
  740. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  741. if (ok) {++this.pos; return ch}
  742. };
  743. StringStream.prototype.eatWhile = function (match) {
  744. var start = this.pos;
  745. while (this.eat(match)){}
  746. return this.pos > start
  747. };
  748. StringStream.prototype.eatSpace = function () {
  749. var start = this.pos;
  750. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  751. return this.pos > start
  752. };
  753. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  754. StringStream.prototype.skipTo = function (ch) {
  755. var found = this.string.indexOf(ch, this.pos);
  756. if (found > -1) {this.pos = found; return true}
  757. };
  758. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  759. StringStream.prototype.column = function () {
  760. if (this.lastColumnPos < this.start) {
  761. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  762. this.lastColumnPos = this.start;
  763. }
  764. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  765. };
  766. StringStream.prototype.indentation = function () {
  767. return countColumn(this.string, null, this.tabSize) -
  768. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  769. };
  770. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  771. if (typeof pattern == "string") {
  772. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  773. var substr = this.string.substr(this.pos, pattern.length);
  774. if (cased(substr) == cased(pattern)) {
  775. if (consume !== false) { this.pos += pattern.length; }
  776. return true
  777. }
  778. } else {
  779. var match = this.string.slice(this.pos).match(pattern);
  780. if (match && match.index > 0) { return null }
  781. if (match && consume !== false) { this.pos += match[0].length; }
  782. return match
  783. }
  784. };
  785. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  786. StringStream.prototype.hideFirstChars = function (n, inner) {
  787. this.lineStart += n;
  788. try { return inner() }
  789. finally { this.lineStart -= n; }
  790. };
  791. StringStream.prototype.lookAhead = function (n) {
  792. var oracle = this.lineOracle;
  793. return oracle && oracle.lookAhead(n)
  794. };
  795. StringStream.prototype.baseToken = function () {
  796. var oracle = this.lineOracle;
  797. return oracle && oracle.baseToken(this.pos)
  798. };
  799. // Find the line object corresponding to the given line number.
  800. function getLine(doc, n) {
  801. n -= doc.first;
  802. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  803. var chunk = doc;
  804. while (!chunk.lines) {
  805. for (var i = 0;; ++i) {
  806. var child = chunk.children[i], sz = child.chunkSize();
  807. if (n < sz) { chunk = child; break }
  808. n -= sz;
  809. }
  810. }
  811. return chunk.lines[n]
  812. }
  813. // Get the part of a document between two positions, as an array of
  814. // strings.
  815. function getBetween(doc, start, end) {
  816. var out = [], n = start.line;
  817. doc.iter(start.line, end.line + 1, function (line) {
  818. var text = line.text;
  819. if (n == end.line) { text = text.slice(0, end.ch); }
  820. if (n == start.line) { text = text.slice(start.ch); }
  821. out.push(text);
  822. ++n;
  823. });
  824. return out
  825. }
  826. // Get the lines between from and to, as array of strings.
  827. function getLines(doc, from, to) {
  828. var out = [];
  829. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  830. return out
  831. }
  832. // Update the height of a line, propagating the height change
  833. // upwards to parent nodes.
  834. function updateLineHeight(line, height) {
  835. var diff = height - line.height;
  836. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  837. }
  838. // Given a line object, find its line number by walking up through
  839. // its parent links.
  840. function lineNo(line) {
  841. if (line.parent == null) { return null }
  842. var cur = line.parent, no = indexOf(cur.lines, line);
  843. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  844. for (var i = 0;; ++i) {
  845. if (chunk.children[i] == cur) { break }
  846. no += chunk.children[i].chunkSize();
  847. }
  848. }
  849. return no + cur.first
  850. }
  851. // Find the line at the given vertical position, using the height
  852. // information in the document tree.
  853. function lineAtHeight(chunk, h) {
  854. var n = chunk.first;
  855. outer: do {
  856. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  857. var child = chunk.children[i$1], ch = child.height;
  858. if (h < ch) { chunk = child; continue outer }
  859. h -= ch;
  860. n += child.chunkSize();
  861. }
  862. return n
  863. } while (!chunk.lines)
  864. var i = 0;
  865. for (; i < chunk.lines.length; ++i) {
  866. var line = chunk.lines[i], lh = line.height;
  867. if (h < lh) { break }
  868. h -= lh;
  869. }
  870. return n + i
  871. }
  872. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  873. function lineNumberFor(options, i) {
  874. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  875. }
  876. // A Pos instance represents a position within the text.
  877. function Pos(line, ch, sticky) {
  878. if ( sticky === void 0 ) sticky = null;
  879. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  880. this.line = line;
  881. this.ch = ch;
  882. this.sticky = sticky;
  883. }
  884. // Compare two positions, return 0 if they are the same, a negative
  885. // number when a is less, and a positive number otherwise.
  886. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  887. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  888. function copyPos(x) {return Pos(x.line, x.ch)}
  889. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  890. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  891. // Most of the external API clips given positions to make sure they
  892. // actually exist within the document.
  893. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  894. function clipPos(doc, pos) {
  895. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  896. var last = doc.first + doc.size - 1;
  897. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  898. return clipToLen(pos, getLine(doc, pos.line).text.length)
  899. }
  900. function clipToLen(pos, linelen) {
  901. var ch = pos.ch;
  902. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  903. else if (ch < 0) { return Pos(pos.line, 0) }
  904. else { return pos }
  905. }
  906. function clipPosArray(doc, array) {
  907. var out = [];
  908. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  909. return out
  910. }
  911. var SavedContext = function(state, lookAhead) {
  912. this.state = state;
  913. this.lookAhead = lookAhead;
  914. };
  915. var Context = function(doc, state, line, lookAhead) {
  916. this.state = state;
  917. this.doc = doc;
  918. this.line = line;
  919. this.maxLookAhead = lookAhead || 0;
  920. this.baseTokens = null;
  921. this.baseTokenPos = 1;
  922. };
  923. Context.prototype.lookAhead = function (n) {
  924. var line = this.doc.getLine(this.line + n);
  925. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  926. return line
  927. };
  928. Context.prototype.baseToken = function (n) {
  929. if (!this.baseTokens) { return null }
  930. while (this.baseTokens[this.baseTokenPos] <= n)
  931. { this.baseTokenPos += 2; }
  932. var type = this.baseTokens[this.baseTokenPos + 1];
  933. return {type: type && type.replace(/( |^)overlay .*/, ""),
  934. size: this.baseTokens[this.baseTokenPos] - n}
  935. };
  936. Context.prototype.nextLine = function () {
  937. this.line++;
  938. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  939. };
  940. Context.fromSaved = function (doc, saved, line) {
  941. if (saved instanceof SavedContext)
  942. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  943. else
  944. { return new Context(doc, copyState(doc.mode, saved), line) }
  945. };
  946. Context.prototype.save = function (copy) {
  947. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  948. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  949. };
  950. // Compute a style array (an array starting with a mode generation
  951. // -- for invalidation -- followed by pairs of end positions and
  952. // style strings), which is used to highlight the tokens on the
  953. // line.
  954. function highlightLine(cm, line, context, forceToEnd) {
  955. // A styles array always starts with a number identifying the
  956. // mode/overlays that it is based on (for easy invalidation).
  957. var st = [cm.state.modeGen], lineClasses = {};
  958. // Compute the base array of styles
  959. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  960. lineClasses, forceToEnd);
  961. var state = context.state;
  962. // Run overlays, adjust style array.
  963. var loop = function ( o ) {
  964. context.baseTokens = st;
  965. var overlay = cm.state.overlays[o], i = 1, at = 0;
  966. context.state = true;
  967. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  968. var start = i;
  969. // Ensure there's a token end at the current position, and that i points at it
  970. while (at < end) {
  971. var i_end = st[i];
  972. if (i_end > end)
  973. { st.splice(i, 1, end, st[i+1], i_end); }
  974. i += 2;
  975. at = Math.min(end, i_end);
  976. }
  977. if (!style) { return }
  978. if (overlay.opaque) {
  979. st.splice(start, i - start, end, "overlay " + style);
  980. i = start + 2;
  981. } else {
  982. for (; start < i; start += 2) {
  983. var cur = st[start+1];
  984. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  985. }
  986. }
  987. }, lineClasses);
  988. context.state = state;
  989. context.baseTokens = null;
  990. context.baseTokenPos = 1;
  991. };
  992. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  993. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  994. }
  995. function getLineStyles(cm, line, updateFrontier) {
  996. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  997. var context = getContextBefore(cm, lineNo(line));
  998. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  999. var result = highlightLine(cm, line, context);
  1000. if (resetState) { context.state = resetState; }
  1001. line.stateAfter = context.save(!resetState);
  1002. line.styles = result.styles;
  1003. if (result.classes) { line.styleClasses = result.classes; }
  1004. else if (line.styleClasses) { line.styleClasses = null; }
  1005. if (updateFrontier === cm.doc.highlightFrontier)
  1006. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1007. }
  1008. return line.styles
  1009. }
  1010. function getContextBefore(cm, n, precise) {
  1011. var doc = cm.doc, display = cm.display;
  1012. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1013. var start = findStartLine(cm, n, precise);
  1014. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1015. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1016. doc.iter(start, n, function (line) {
  1017. processLine(cm, line.text, context);
  1018. var pos = context.line;
  1019. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1020. context.nextLine();
  1021. });
  1022. if (precise) { doc.modeFrontier = context.line; }
  1023. return context
  1024. }
  1025. // Lightweight form of highlight -- proceed over this line and
  1026. // update state, but don't save a style array. Used for lines that
  1027. // aren't currently visible.
  1028. function processLine(cm, text, context, startAt) {
  1029. var mode = cm.doc.mode;
  1030. var stream = new StringStream(text, cm.options.tabSize, context);
  1031. stream.start = stream.pos = startAt || 0;
  1032. if (text == "") { callBlankLine(mode, context.state); }
  1033. while (!stream.eol()) {
  1034. readToken(mode, stream, context.state);
  1035. stream.start = stream.pos;
  1036. }
  1037. }
  1038. function callBlankLine(mode, state) {
  1039. if (mode.blankLine) { return mode.blankLine(state) }
  1040. if (!mode.innerMode) { return }
  1041. var inner = innerMode(mode, state);
  1042. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1043. }
  1044. function readToken(mode, stream, state, inner) {
  1045. for (var i = 0; i < 10; i++) {
  1046. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1047. var style = mode.token(stream, state);
  1048. if (stream.pos > stream.start) { return style }
  1049. }
  1050. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1051. }
  1052. var Token = function(stream, type, state) {
  1053. this.start = stream.start; this.end = stream.pos;
  1054. this.string = stream.current();
  1055. this.type = type || null;
  1056. this.state = state;
  1057. };
  1058. // Utility for getTokenAt and getLineTokens
  1059. function takeToken(cm, pos, precise, asArray) {
  1060. var doc = cm.doc, mode = doc.mode, style;
  1061. pos = clipPos(doc, pos);
  1062. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1063. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1064. if (asArray) { tokens = []; }
  1065. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1066. stream.start = stream.pos;
  1067. style = readToken(mode, stream, context.state);
  1068. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1069. }
  1070. return asArray ? tokens : new Token(stream, style, context.state)
  1071. }
  1072. function extractLineClasses(type, output) {
  1073. if (type) { for (;;) {
  1074. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1075. if (!lineClass) { break }
  1076. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1077. var prop = lineClass[1] ? "bgClass" : "textClass";
  1078. if (output[prop] == null)
  1079. { output[prop] = lineClass[2]; }
  1080. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1081. { output[prop] += " " + lineClass[2]; }
  1082. } }
  1083. return type
  1084. }
  1085. // Run the given mode's parser over a line, calling f for each token.
  1086. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1087. var flattenSpans = mode.flattenSpans;
  1088. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1089. var curStart = 0, curStyle = null;
  1090. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1091. var inner = cm.options.addModeClass && [null];
  1092. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1093. while (!stream.eol()) {
  1094. if (stream.pos > cm.options.maxHighlightLength) {
  1095. flattenSpans = false;
  1096. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1097. stream.pos = text.length;
  1098. style = null;
  1099. } else {
  1100. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1101. }
  1102. if (inner) {
  1103. var mName = inner[0].name;
  1104. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1105. }
  1106. if (!flattenSpans || curStyle != style) {
  1107. while (curStart < stream.start) {
  1108. curStart = Math.min(stream.start, curStart + 5000);
  1109. f(curStart, curStyle);
  1110. }
  1111. curStyle = style;
  1112. }
  1113. stream.start = stream.pos;
  1114. }
  1115. while (curStart < stream.pos) {
  1116. // Webkit seems to refuse to render text nodes longer than 57444
  1117. // characters, and returns inaccurate measurements in nodes
  1118. // starting around 5000 chars.
  1119. var pos = Math.min(stream.pos, curStart + 5000);
  1120. f(pos, curStyle);
  1121. curStart = pos;
  1122. }
  1123. }
  1124. // Finds the line to start with when starting a parse. Tries to
  1125. // find a line with a stateAfter, so that it can start with a
  1126. // valid state. If that fails, it returns the line with the
  1127. // smallest indentation, which tends to need the least context to
  1128. // parse correctly.
  1129. function findStartLine(cm, n, precise) {
  1130. var minindent, minline, doc = cm.doc;
  1131. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1132. for (var search = n; search > lim; --search) {
  1133. if (search <= doc.first) { return doc.first }
  1134. var line = getLine(doc, search - 1), after = line.stateAfter;
  1135. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1136. { return search }
  1137. var indented = countColumn(line.text, null, cm.options.tabSize);
  1138. if (minline == null || minindent > indented) {
  1139. minline = search - 1;
  1140. minindent = indented;
  1141. }
  1142. }
  1143. return minline
  1144. }
  1145. function retreatFrontier(doc, n) {
  1146. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1147. if (doc.highlightFrontier < n - 10) { return }
  1148. var start = doc.first;
  1149. for (var line = n - 1; line > start; line--) {
  1150. var saved = getLine(doc, line).stateAfter;
  1151. // change is on 3
  1152. // state on line 1 looked ahead 2 -- so saw 3
  1153. // test 1 + 2 < 3 should cover this
  1154. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1155. start = line + 1;
  1156. break
  1157. }
  1158. }
  1159. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1160. }
  1161. // Optimize some code when these features are not used.
  1162. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1163. function seeReadOnlySpans() {
  1164. sawReadOnlySpans = true;
  1165. }
  1166. function seeCollapsedSpans() {
  1167. sawCollapsedSpans = true;
  1168. }
  1169. // TEXTMARKER SPANS
  1170. function MarkedSpan(marker, from, to) {
  1171. this.marker = marker;
  1172. this.from = from; this.to = to;
  1173. }
  1174. // Search an array of spans for a span matching the given marker.
  1175. function getMarkedSpanFor(spans, marker) {
  1176. if (spans) { for (var i = 0; i < spans.length; ++i) {
  1177. var span = spans[i];
  1178. if (span.marker == marker) { return span }
  1179. } }
  1180. }
  1181. // Remove a span from an array, returning undefined if no spans are
  1182. // left (we don't store arrays for lines without spans).
  1183. function removeMarkedSpan(spans, span) {
  1184. var r;
  1185. for (var i = 0; i < spans.length; ++i)
  1186. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1187. return r
  1188. }
  1189. // Add a span to a line.
  1190. function addMarkedSpan(line, span) {
  1191. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1192. span.marker.attachLine(line);
  1193. }
  1194. // Used for the algorithm that adjusts markers for a change in the
  1195. // document. These functions cut an array of spans at a given
  1196. // character position, returning an array of remaining chunks (or
  1197. // undefined if nothing remains).
  1198. function markedSpansBefore(old, startCh, isInsert) {
  1199. var nw;
  1200. if (old) { for (var i = 0; i < old.length; ++i) {
  1201. var span = old[i], marker = span.marker;
  1202. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1203. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1204. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1205. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1206. }
  1207. } }
  1208. return nw
  1209. }
  1210. function markedSpansAfter(old, endCh, isInsert) {
  1211. var nw;
  1212. if (old) { for (var i = 0; i < old.length; ++i) {
  1213. var span = old[i], marker = span.marker;
  1214. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1215. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1216. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1217. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1218. span.to == null ? null : span.to - endCh));
  1219. }
  1220. } }
  1221. return nw
  1222. }
  1223. // Given a change object, compute the new set of marker spans that
  1224. // cover the line in which the change took place. Removes spans
  1225. // entirely within the change, reconnects spans belonging to the
  1226. // same marker that appear on both sides of the change, and cuts off
  1227. // spans partially within the change. Returns an array of span
  1228. // arrays with one element for each line in (after) the change.
  1229. function stretchSpansOverChange(doc, change) {
  1230. if (change.full) { return null }
  1231. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1232. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1233. if (!oldFirst && !oldLast) { return null }
  1234. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1235. // Get the spans that 'stick out' on both sides
  1236. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1237. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1238. // Next, merge those two ends
  1239. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1240. if (first) {
  1241. // Fix up .to properties of first
  1242. for (var i = 0; i < first.length; ++i) {
  1243. var span = first[i];
  1244. if (span.to == null) {
  1245. var found = getMarkedSpanFor(last, span.marker);
  1246. if (!found) { span.to = startCh; }
  1247. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1248. }
  1249. }
  1250. }
  1251. if (last) {
  1252. // Fix up .from in last (or move them into first in case of sameLine)
  1253. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1254. var span$1 = last[i$1];
  1255. if (span$1.to != null) { span$1.to += offset; }
  1256. if (span$1.from == null) {
  1257. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1258. if (!found$1) {
  1259. span$1.from = offset;
  1260. if (sameLine) { (first || (first = [])).push(span$1); }
  1261. }
  1262. } else {
  1263. span$1.from += offset;
  1264. if (sameLine) { (first || (first = [])).push(span$1); }
  1265. }
  1266. }
  1267. }
  1268. // Make sure we didn't create any zero-length spans
  1269. if (first) { first = clearEmptySpans(first); }
  1270. if (last && last != first) { last = clearEmptySpans(last); }
  1271. var newMarkers = [first];
  1272. if (!sameLine) {
  1273. // Fill gap with whole-line-spans
  1274. var gap = change.text.length - 2, gapMarkers;
  1275. if (gap > 0 && first)
  1276. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1277. { if (first[i$2].to == null)
  1278. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1279. for (var i$3 = 0; i$3 < gap; ++i$3)
  1280. { newMarkers.push(gapMarkers); }
  1281. newMarkers.push(last);
  1282. }
  1283. return newMarkers
  1284. }
  1285. // Remove spans that are empty and don't have a clearWhenEmpty
  1286. // option of false.
  1287. function clearEmptySpans(spans) {
  1288. for (var i = 0; i < spans.length; ++i) {
  1289. var span = spans[i];
  1290. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1291. { spans.splice(i--, 1); }
  1292. }
  1293. if (!spans.length) { return null }
  1294. return spans
  1295. }
  1296. // Used to 'clip' out readOnly ranges when making a change.
  1297. function removeReadOnlyRanges(doc, from, to) {
  1298. var markers = null;
  1299. doc.iter(from.line, to.line + 1, function (line) {
  1300. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1301. var mark = line.markedSpans[i].marker;
  1302. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1303. { (markers || (markers = [])).push(mark); }
  1304. } }
  1305. });
  1306. if (!markers) { return null }
  1307. var parts = [{from: from, to: to}];
  1308. for (var i = 0; i < markers.length; ++i) {
  1309. var mk = markers[i], m = mk.find(0);
  1310. for (var j = 0; j < parts.length; ++j) {
  1311. var p = parts[j];
  1312. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1313. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1314. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1315. { newParts.push({from: p.from, to: m.from}); }
  1316. if (dto > 0 || !mk.inclusiveRight && !dto)
  1317. { newParts.push({from: m.to, to: p.to}); }
  1318. parts.splice.apply(parts, newParts);
  1319. j += newParts.length - 3;
  1320. }
  1321. }
  1322. return parts
  1323. }
  1324. // Connect or disconnect spans from a line.
  1325. function detachMarkedSpans(line) {
  1326. var spans = line.markedSpans;
  1327. if (!spans) { return }
  1328. for (var i = 0; i < spans.length; ++i)
  1329. { spans[i].marker.detachLine(line); }
  1330. line.markedSpans = null;
  1331. }
  1332. function attachMarkedSpans(line, spans) {
  1333. if (!spans) { return }
  1334. for (var i = 0; i < spans.length; ++i)
  1335. { spans[i].marker.attachLine(line); }
  1336. line.markedSpans = spans;
  1337. }
  1338. // Helpers used when computing which overlapping collapsed span
  1339. // counts as the larger one.
  1340. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1341. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1342. // Returns a number indicating which of two overlapping collapsed
  1343. // spans is larger (and thus includes the other). Falls back to
  1344. // comparing ids when the spans cover exactly the same range.
  1345. function compareCollapsedMarkers(a, b) {
  1346. var lenDiff = a.lines.length - b.lines.length;
  1347. if (lenDiff != 0) { return lenDiff }
  1348. var aPos = a.find(), bPos = b.find();
  1349. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1350. if (fromCmp) { return -fromCmp }
  1351. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1352. if (toCmp) { return toCmp }
  1353. return b.id - a.id
  1354. }
  1355. // Find out whether a line ends or starts in a collapsed span. If
  1356. // so, return the marker for that span.
  1357. function collapsedSpanAtSide(line, start) {
  1358. var sps = sawCollapsedSpans && line.markedSpans, found;
  1359. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1360. sp = sps[i];
  1361. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1362. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1363. { found = sp.marker; }
  1364. } }
  1365. return found
  1366. }
  1367. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1368. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1369. function collapsedSpanAround(line, ch) {
  1370. var sps = sawCollapsedSpans && line.markedSpans, found;
  1371. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1372. var sp = sps[i];
  1373. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1374. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1375. } }
  1376. return found
  1377. }
  1378. // Test whether there exists a collapsed span that partially
  1379. // overlaps (covers the start or end, but not both) of a new span.
  1380. // Such overlap is not allowed.
  1381. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1382. var line = getLine(doc, lineNo);
  1383. var sps = sawCollapsedSpans && line.markedSpans;
  1384. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1385. var sp = sps[i];
  1386. if (!sp.marker.collapsed) { continue }
  1387. var found = sp.marker.find(0);
  1388. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1389. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1390. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1391. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1392. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1393. { return true }
  1394. } }
  1395. }
  1396. // A visual line is a line as drawn on the screen. Folding, for
  1397. // example, can cause multiple logical lines to appear on the same
  1398. // visual line. This finds the start of the visual line that the
  1399. // given line is part of (usually that is the line itself).
  1400. function visualLine(line) {
  1401. var merged;
  1402. while (merged = collapsedSpanAtStart(line))
  1403. { line = merged.find(-1, true).line; }
  1404. return line
  1405. }
  1406. function visualLineEnd(line) {
  1407. var merged;
  1408. while (merged = collapsedSpanAtEnd(line))
  1409. { line = merged.find(1, true).line; }
  1410. return line
  1411. }
  1412. // Returns an array of logical lines that continue the visual line
  1413. // started by the argument, or undefined if there are no such lines.
  1414. function visualLineContinued(line) {
  1415. var merged, lines;
  1416. while (merged = collapsedSpanAtEnd(line)) {
  1417. line = merged.find(1, true).line
  1418. ;(lines || (lines = [])).push(line);
  1419. }
  1420. return lines
  1421. }
  1422. // Get the line number of the start of the visual line that the
  1423. // given line number is part of.
  1424. function visualLineNo(doc, lineN) {
  1425. var line = getLine(doc, lineN), vis = visualLine(line);
  1426. if (line == vis) { return lineN }
  1427. return lineNo(vis)
  1428. }
  1429. // Get the line number of the start of the next visual line after
  1430. // the given line.
  1431. function visualLineEndNo(doc, lineN) {
  1432. if (lineN > doc.lastLine()) { return lineN }
  1433. var line = getLine(doc, lineN), merged;
  1434. if (!lineIsHidden(doc, line)) { return lineN }
  1435. while (merged = collapsedSpanAtEnd(line))
  1436. { line = merged.find(1, true).line; }
  1437. return lineNo(line) + 1
  1438. }
  1439. // Compute whether a line is hidden. Lines count as hidden when they
  1440. // are part of a visual line that starts with another line, or when
  1441. // they are entirely covered by collapsed, non-widget span.
  1442. function lineIsHidden(doc, line) {
  1443. var sps = sawCollapsedSpans && line.markedSpans;
  1444. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1445. sp = sps[i];
  1446. if (!sp.marker.collapsed) { continue }
  1447. if (sp.from == null) { return true }
  1448. if (sp.marker.widgetNode) { continue }
  1449. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1450. { return true }
  1451. } }
  1452. }
  1453. function lineIsHiddenInner(doc, line, span) {
  1454. if (span.to == null) {
  1455. var end = span.marker.find(1, true);
  1456. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1457. }
  1458. if (span.marker.inclusiveRight && span.to == line.text.length)
  1459. { return true }
  1460. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1461. sp = line.markedSpans[i];
  1462. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1463. (sp.to == null || sp.to != span.from) &&
  1464. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1465. lineIsHiddenInner(doc, line, sp)) { return true }
  1466. }
  1467. }
  1468. // Find the height above the given line.
  1469. function heightAtLine(lineObj) {
  1470. lineObj = visualLine(lineObj);
  1471. var h = 0, chunk = lineObj.parent;
  1472. for (var i = 0; i < chunk.lines.length; ++i) {
  1473. var line = chunk.lines[i];
  1474. if (line == lineObj) { break }
  1475. else { h += line.height; }
  1476. }
  1477. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1478. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1479. var cur = p.children[i$1];
  1480. if (cur == chunk) { break }
  1481. else { h += cur.height; }
  1482. }
  1483. }
  1484. return h
  1485. }
  1486. // Compute the character length of a line, taking into account
  1487. // collapsed ranges (see markText) that might hide parts, and join
  1488. // other lines onto it.
  1489. function lineLength(line) {
  1490. if (line.height == 0) { return 0 }
  1491. var len = line.text.length, merged, cur = line;
  1492. while (merged = collapsedSpanAtStart(cur)) {
  1493. var found = merged.find(0, true);
  1494. cur = found.from.line;
  1495. len += found.from.ch - found.to.ch;
  1496. }
  1497. cur = line;
  1498. while (merged = collapsedSpanAtEnd(cur)) {
  1499. var found$1 = merged.find(0, true);
  1500. len -= cur.text.length - found$1.from.ch;
  1501. cur = found$1.to.line;
  1502. len += cur.text.length - found$1.to.ch;
  1503. }
  1504. return len
  1505. }
  1506. // Find the longest line in the document.
  1507. function findMaxLine(cm) {
  1508. var d = cm.display, doc = cm.doc;
  1509. d.maxLine = getLine(doc, doc.first);
  1510. d.maxLineLength = lineLength(d.maxLine);
  1511. d.maxLineChanged = true;
  1512. doc.iter(function (line) {
  1513. var len = lineLength(line);
  1514. if (len > d.maxLineLength) {
  1515. d.maxLineLength = len;
  1516. d.maxLine = line;
  1517. }
  1518. });
  1519. }
  1520. // LINE DATA STRUCTURE
  1521. // Line objects. These hold state related to a line, including
  1522. // highlighting info (the styles array).
  1523. var Line = function(text, markedSpans, estimateHeight) {
  1524. this.text = text;
  1525. attachMarkedSpans(this, markedSpans);
  1526. this.height = estimateHeight ? estimateHeight(this) : 1;
  1527. };
  1528. Line.prototype.lineNo = function () { return lineNo(this) };
  1529. eventMixin(Line);
  1530. // Change the content (text, markers) of a line. Automatically
  1531. // invalidates cached information and tries to re-estimate the
  1532. // line's height.
  1533. function updateLine(line, text, markedSpans, estimateHeight) {
  1534. line.text = text;
  1535. if (line.stateAfter) { line.stateAfter = null; }
  1536. if (line.styles) { line.styles = null; }
  1537. if (line.order != null) { line.order = null; }
  1538. detachMarkedSpans(line);
  1539. attachMarkedSpans(line, markedSpans);
  1540. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1541. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1542. }
  1543. // Detach a line from the document tree and its markers.
  1544. function cleanUpLine(line) {
  1545. line.parent = null;
  1546. detachMarkedSpans(line);
  1547. }
  1548. // Convert a style as returned by a mode (either null, or a string
  1549. // containing one or more styles) to a CSS style. This is cached,
  1550. // and also looks for line-wide styles.
  1551. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1552. function interpretTokenStyle(style, options) {
  1553. if (!style || /^\s*$/.test(style)) { return null }
  1554. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1555. return cache[style] ||
  1556. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1557. }
  1558. // Render the DOM representation of the text of a line. Also builds
  1559. // up a 'line map', which points at the DOM nodes that represent
  1560. // specific stretches of text, and is used by the measuring code.
  1561. // The returned object contains the DOM node, this map, and
  1562. // information about line-wide styles that were set by the mode.
  1563. function buildLineContent(cm, lineView) {
  1564. // The padding-right forces the element to have a 'border', which
  1565. // is needed on Webkit to be able to get line-level bounding
  1566. // rectangles for it (in measureChar).
  1567. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1568. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1569. col: 0, pos: 0, cm: cm,
  1570. trailingSpace: false,
  1571. splitSpaces: cm.getOption("lineWrapping")};
  1572. lineView.measure = {};
  1573. // Iterate over the logical lines that make up this visual line.
  1574. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1575. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1576. builder.pos = 0;
  1577. builder.addToken = buildToken;
  1578. // Optionally wire in some hacks into the token-rendering
  1579. // algorithm, to deal with browser quirks.
  1580. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1581. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1582. builder.map = [];
  1583. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1584. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1585. if (line.styleClasses) {
  1586. if (line.styleClasses.bgClass)
  1587. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1588. if (line.styleClasses.textClass)
  1589. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1590. }
  1591. // Ensure at least a single node is present, for measuring.
  1592. if (builder.map.length == 0)
  1593. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1594. // Store the map and a cache object for the current logical line
  1595. if (i == 0) {
  1596. lineView.measure.map = builder.map;
  1597. lineView.measure.cache = {};
  1598. } else {
  1599. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1600. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1601. }
  1602. }
  1603. // See issue #2901
  1604. if (webkit) {
  1605. var last = builder.content.lastChild;
  1606. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1607. { builder.content.className = "cm-tab-wrap-hack"; }
  1608. }
  1609. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1610. if (builder.pre.className)
  1611. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1612. return builder
  1613. }
  1614. function defaultSpecialCharPlaceholder(ch) {
  1615. var token = elt("span", "\u2022", "cm-invalidchar");
  1616. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1617. token.setAttribute("aria-label", token.title);
  1618. return token
  1619. }
  1620. // Build up the DOM representation for a single token, and add it to
  1621. // the line map. Takes care to render special characters separately.
  1622. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1623. if (!text) { return }
  1624. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1625. var special = builder.cm.state.specialChars, mustWrap = false;
  1626. var content;
  1627. if (!special.test(text)) {
  1628. builder.col += text.length;
  1629. content = document.createTextNode(displayText);
  1630. builder.map.push(builder.pos, builder.pos + text.length, content);
  1631. if (ie && ie_version < 9) { mustWrap = true; }
  1632. builder.pos += text.length;
  1633. } else {
  1634. content = document.createDocumentFragment();
  1635. var pos = 0;
  1636. while (true) {
  1637. special.lastIndex = pos;
  1638. var m = special.exec(text);
  1639. var skipped = m ? m.index - pos : text.length - pos;
  1640. if (skipped) {
  1641. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1642. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1643. else { content.appendChild(txt); }
  1644. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1645. builder.col += skipped;
  1646. builder.pos += skipped;
  1647. }
  1648. if (!m) { break }
  1649. pos += skipped + 1;
  1650. var txt$1 = (void 0);
  1651. if (m[0] == "\t") {
  1652. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1653. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1654. txt$1.setAttribute("role", "presentation");
  1655. txt$1.setAttribute("cm-text", "\t");
  1656. builder.col += tabWidth;
  1657. } else if (m[0] == "\r" || m[0] == "\n") {
  1658. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1659. txt$1.setAttribute("cm-text", m[0]);
  1660. builder.col += 1;
  1661. } else {
  1662. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1663. txt$1.setAttribute("cm-text", m[0]);
  1664. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1665. else { content.appendChild(txt$1); }
  1666. builder.col += 1;
  1667. }
  1668. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1669. builder.pos++;
  1670. }
  1671. }
  1672. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1673. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  1674. var fullStyle = style || "";
  1675. if (startStyle) { fullStyle += startStyle; }
  1676. if (endStyle) { fullStyle += endStyle; }
  1677. var token = elt("span", [content], fullStyle, css);
  1678. if (attributes) {
  1679. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1680. { token.setAttribute(attr, attributes[attr]); } }
  1681. }
  1682. return builder.content.appendChild(token)
  1683. }
  1684. builder.content.appendChild(content);
  1685. }
  1686. // Change some spaces to NBSP to prevent the browser from collapsing
  1687. // trailing spaces at the end of a line when rendering text (issue #1362).
  1688. function splitSpaces(text, trailingBefore) {
  1689. if (text.length > 1 && !/ /.test(text)) { return text }
  1690. var spaceBefore = trailingBefore, result = "";
  1691. for (var i = 0; i < text.length; i++) {
  1692. var ch = text.charAt(i);
  1693. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1694. { ch = "\u00a0"; }
  1695. result += ch;
  1696. spaceBefore = ch == " ";
  1697. }
  1698. return result
  1699. }
  1700. // Work around nonsense dimensions being reported for stretches of
  1701. // right-to-left text.
  1702. function buildTokenBadBidi(inner, order) {
  1703. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1704. style = style ? style + " cm-force-border" : "cm-force-border";
  1705. var start = builder.pos, end = start + text.length;
  1706. for (;;) {
  1707. // Find the part that overlaps with the start of this text
  1708. var part = (void 0);
  1709. for (var i = 0; i < order.length; i++) {
  1710. part = order[i];
  1711. if (part.to > start && part.from <= start) { break }
  1712. }
  1713. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1714. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1715. startStyle = null;
  1716. text = text.slice(part.to - start);
  1717. start = part.to;
  1718. }
  1719. }
  1720. }
  1721. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1722. var widget = !ignoreWidget && marker.widgetNode;
  1723. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1724. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1725. if (!widget)
  1726. { widget = builder.content.appendChild(document.createElement("span")); }
  1727. widget.setAttribute("cm-marker", marker.id);
  1728. }
  1729. if (widget) {
  1730. builder.cm.display.input.setUneditable(widget);
  1731. builder.content.appendChild(widget);
  1732. }
  1733. builder.pos += size;
  1734. builder.trailingSpace = false;
  1735. }
  1736. // Outputs a number of spans to make up a line, taking highlighting
  1737. // and marked text into account.
  1738. function insertLineContent(line, builder, styles) {
  1739. var spans = line.markedSpans, allText = line.text, at = 0;
  1740. if (!spans) {
  1741. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1742. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1743. return
  1744. }
  1745. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1746. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1747. for (;;) {
  1748. if (nextChange == pos) { // Update current marker set
  1749. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1750. attributes = null;
  1751. collapsed = null; nextChange = Infinity;
  1752. var foundBookmarks = [], endStyles = (void 0);
  1753. for (var j = 0; j < spans.length; ++j) {
  1754. var sp = spans[j], m = sp.marker;
  1755. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1756. foundBookmarks.push(m);
  1757. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1758. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1759. nextChange = sp.to;
  1760. spanEndStyle = "";
  1761. }
  1762. if (m.className) { spanStyle += " " + m.className; }
  1763. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1764. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1765. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1766. // support for the old title property
  1767. // https://github.com/codemirror/CodeMirror/pull/5673
  1768. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1769. if (m.attributes) {
  1770. for (var attr in m.attributes)
  1771. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1772. }
  1773. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1774. { collapsed = sp; }
  1775. } else if (sp.from > pos && nextChange > sp.from) {
  1776. nextChange = sp.from;
  1777. }
  1778. }
  1779. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1780. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1781. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1782. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1783. if (collapsed && (collapsed.from || 0) == pos) {
  1784. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1785. collapsed.marker, collapsed.from == null);
  1786. if (collapsed.to == null) { return }
  1787. if (collapsed.to == pos) { collapsed = false; }
  1788. }
  1789. }
  1790. if (pos >= len) { break }
  1791. var upto = Math.min(len, nextChange);
  1792. while (true) {
  1793. if (text) {
  1794. var end = pos + text.length;
  1795. if (!collapsed) {
  1796. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1797. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1798. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1799. }
  1800. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1801. pos = end;
  1802. spanStartStyle = "";
  1803. }
  1804. text = allText.slice(at, at = styles[i++]);
  1805. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1806. }
  1807. }
  1808. }
  1809. // These objects are used to represent the visible (currently drawn)
  1810. // part of the document. A LineView may correspond to multiple
  1811. // logical lines, if those are connected by collapsed ranges.
  1812. function LineView(doc, line, lineN) {
  1813. // The starting line
  1814. this.line = line;
  1815. // Continuing lines, if any
  1816. this.rest = visualLineContinued(line);
  1817. // Number of logical lines in this visual line
  1818. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1819. this.node = this.text = null;
  1820. this.hidden = lineIsHidden(doc, line);
  1821. }
  1822. // Create a range of LineView objects for the given lines.
  1823. function buildViewArray(cm, from, to) {
  1824. var array = [], nextPos;
  1825. for (var pos = from; pos < to; pos = nextPos) {
  1826. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1827. nextPos = pos + view.size;
  1828. array.push(view);
  1829. }
  1830. return array
  1831. }
  1832. var operationGroup = null;
  1833. function pushOperation(op) {
  1834. if (operationGroup) {
  1835. operationGroup.ops.push(op);
  1836. } else {
  1837. op.ownsGroup = operationGroup = {
  1838. ops: [op],
  1839. delayedCallbacks: []
  1840. };
  1841. }
  1842. }
  1843. function fireCallbacksForOps(group) {
  1844. // Calls delayed callbacks and cursorActivity handlers until no
  1845. // new ones appear
  1846. var callbacks = group.delayedCallbacks, i = 0;
  1847. do {
  1848. for (; i < callbacks.length; i++)
  1849. { callbacks[i].call(null); }
  1850. for (var j = 0; j < group.ops.length; j++) {
  1851. var op = group.ops[j];
  1852. if (op.cursorActivityHandlers)
  1853. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1854. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1855. }
  1856. } while (i < callbacks.length)
  1857. }
  1858. function finishOperation(op, endCb) {
  1859. var group = op.ownsGroup;
  1860. if (!group) { return }
  1861. try { fireCallbacksForOps(group); }
  1862. finally {
  1863. operationGroup = null;
  1864. endCb(group);
  1865. }
  1866. }
  1867. var orphanDelayedCallbacks = null;
  1868. // Often, we want to signal events at a point where we are in the
  1869. // middle of some work, but don't want the handler to start calling
  1870. // other methods on the editor, which might be in an inconsistent
  1871. // state or simply not expect any other events to happen.
  1872. // signalLater looks whether there are any handlers, and schedules
  1873. // them to be executed when the last operation ends, or, if no
  1874. // operation is active, when a timeout fires.
  1875. function signalLater(emitter, type /*, values...*/) {
  1876. var arr = getHandlers(emitter, type);
  1877. if (!arr.length) { return }
  1878. var args = Array.prototype.slice.call(arguments, 2), list;
  1879. if (operationGroup) {
  1880. list = operationGroup.delayedCallbacks;
  1881. } else if (orphanDelayedCallbacks) {
  1882. list = orphanDelayedCallbacks;
  1883. } else {
  1884. list = orphanDelayedCallbacks = [];
  1885. setTimeout(fireOrphanDelayed, 0);
  1886. }
  1887. var loop = function ( i ) {
  1888. list.push(function () { return arr[i].apply(null, args); });
  1889. };
  1890. for (var i = 0; i < arr.length; ++i)
  1891. loop( i );
  1892. }
  1893. function fireOrphanDelayed() {
  1894. var delayed = orphanDelayedCallbacks;
  1895. orphanDelayedCallbacks = null;
  1896. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1897. }
  1898. // When an aspect of a line changes, a string is added to
  1899. // lineView.changes. This updates the relevant part of the line's
  1900. // DOM structure.
  1901. function updateLineForChanges(cm, lineView, lineN, dims) {
  1902. for (var j = 0; j < lineView.changes.length; j++) {
  1903. var type = lineView.changes[j];
  1904. if (type == "text") { updateLineText(cm, lineView); }
  1905. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1906. else if (type == "class") { updateLineClasses(cm, lineView); }
  1907. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1908. }
  1909. lineView.changes = null;
  1910. }
  1911. // Lines with gutter elements, widgets or a background class need to
  1912. // be wrapped, and have the extra elements added to the wrapper div
  1913. function ensureLineWrapped(lineView) {
  1914. if (lineView.node == lineView.text) {
  1915. lineView.node = elt("div", null, null, "position: relative");
  1916. if (lineView.text.parentNode)
  1917. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1918. lineView.node.appendChild(lineView.text);
  1919. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1920. }
  1921. return lineView.node
  1922. }
  1923. function updateLineBackground(cm, lineView) {
  1924. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1925. if (cls) { cls += " CodeMirror-linebackground"; }
  1926. if (lineView.background) {
  1927. if (cls) { lineView.background.className = cls; }
  1928. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1929. } else if (cls) {
  1930. var wrap = ensureLineWrapped(lineView);
  1931. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1932. cm.display.input.setUneditable(lineView.background);
  1933. }
  1934. }
  1935. // Wrapper around buildLineContent which will reuse the structure
  1936. // in display.externalMeasured when possible.
  1937. function getLineContent(cm, lineView) {
  1938. var ext = cm.display.externalMeasured;
  1939. if (ext && ext.line == lineView.line) {
  1940. cm.display.externalMeasured = null;
  1941. lineView.measure = ext.measure;
  1942. return ext.built
  1943. }
  1944. return buildLineContent(cm, lineView)
  1945. }
  1946. // Redraw the line's text. Interacts with the background and text
  1947. // classes because the mode may output tokens that influence these
  1948. // classes.
  1949. function updateLineText(cm, lineView) {
  1950. var cls = lineView.text.className;
  1951. var built = getLineContent(cm, lineView);
  1952. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  1953. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  1954. lineView.text = built.pre;
  1955. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1956. lineView.bgClass = built.bgClass;
  1957. lineView.textClass = built.textClass;
  1958. updateLineClasses(cm, lineView);
  1959. } else if (cls) {
  1960. lineView.text.className = cls;
  1961. }
  1962. }
  1963. function updateLineClasses(cm, lineView) {
  1964. updateLineBackground(cm, lineView);
  1965. if (lineView.line.wrapClass)
  1966. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  1967. else if (lineView.node != lineView.text)
  1968. { lineView.node.className = ""; }
  1969. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  1970. lineView.text.className = textClass || "";
  1971. }
  1972. function updateLineGutter(cm, lineView, lineN, dims) {
  1973. if (lineView.gutter) {
  1974. lineView.node.removeChild(lineView.gutter);
  1975. lineView.gutter = null;
  1976. }
  1977. if (lineView.gutterBackground) {
  1978. lineView.node.removeChild(lineView.gutterBackground);
  1979. lineView.gutterBackground = null;
  1980. }
  1981. if (lineView.line.gutterClass) {
  1982. var wrap = ensureLineWrapped(lineView);
  1983. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1984. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  1985. cm.display.input.setUneditable(lineView.gutterBackground);
  1986. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  1987. }
  1988. var markers = lineView.line.gutterMarkers;
  1989. if (cm.options.lineNumbers || markers) {
  1990. var wrap$1 = ensureLineWrapped(lineView);
  1991. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  1992. cm.display.input.setUneditable(gutterWrap);
  1993. wrap$1.insertBefore(gutterWrap, lineView.text);
  1994. if (lineView.line.gutterClass)
  1995. { gutterWrap.className += " " + lineView.line.gutterClass; }
  1996. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  1997. { lineView.lineNumber = gutterWrap.appendChild(
  1998. elt("div", lineNumberFor(cm.options, lineN),
  1999. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2000. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2001. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2002. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2003. if (found)
  2004. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2005. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2006. } }
  2007. }
  2008. }
  2009. function updateLineWidgets(cm, lineView, dims) {
  2010. if (lineView.alignable) { lineView.alignable = null; }
  2011. var isWidget = classTest("CodeMirror-linewidget");
  2012. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2013. next = node.nextSibling;
  2014. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2015. }
  2016. insertLineWidgets(cm, lineView, dims);
  2017. }
  2018. // Build a line's DOM representation from scratch
  2019. function buildLineElement(cm, lineView, lineN, dims) {
  2020. var built = getLineContent(cm, lineView);
  2021. lineView.text = lineView.node = built.pre;
  2022. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2023. if (built.textClass) { lineView.textClass = built.textClass; }
  2024. updateLineClasses(cm, lineView);
  2025. updateLineGutter(cm, lineView, lineN, dims);
  2026. insertLineWidgets(cm, lineView, dims);
  2027. return lineView.node
  2028. }
  2029. // A lineView may contain multiple logical lines (when merged by
  2030. // collapsed spans). The widgets for all of them need to be drawn.
  2031. function insertLineWidgets(cm, lineView, dims) {
  2032. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2033. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2034. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2035. }
  2036. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2037. if (!line.widgets) { return }
  2038. var wrap = ensureLineWrapped(lineView);
  2039. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2040. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2041. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2042. positionLineWidget(widget, node, lineView, dims);
  2043. cm.display.input.setUneditable(node);
  2044. if (allowAbove && widget.above)
  2045. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2046. else
  2047. { wrap.appendChild(node); }
  2048. signalLater(widget, "redraw");
  2049. }
  2050. }
  2051. function positionLineWidget(widget, node, lineView, dims) {
  2052. if (widget.noHScroll) {
  2053. (lineView.alignable || (lineView.alignable = [])).push(node);
  2054. var width = dims.wrapperWidth;
  2055. node.style.left = dims.fixedPos + "px";
  2056. if (!widget.coverGutter) {
  2057. width -= dims.gutterTotalWidth;
  2058. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2059. }
  2060. node.style.width = width + "px";
  2061. }
  2062. if (widget.coverGutter) {
  2063. node.style.zIndex = 5;
  2064. node.style.position = "relative";
  2065. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2066. }
  2067. }
  2068. function widgetHeight(widget) {
  2069. if (widget.height != null) { return widget.height }
  2070. var cm = widget.doc.cm;
  2071. if (!cm) { return 0 }
  2072. if (!contains(document.body, widget.node)) {
  2073. var parentStyle = "position: relative;";
  2074. if (widget.coverGutter)
  2075. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2076. if (widget.noHScroll)
  2077. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2078. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2079. }
  2080. return widget.height = widget.node.parentNode.offsetHeight
  2081. }
  2082. // Return true when the given mouse event happened in a widget
  2083. function eventInWidget(display, e) {
  2084. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2085. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2086. (n.parentNode == display.sizer && n != display.mover))
  2087. { return true }
  2088. }
  2089. }
  2090. // POSITION MEASUREMENT
  2091. function paddingTop(display) {return display.lineSpace.offsetTop}
  2092. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2093. function paddingH(display) {
  2094. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2095. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2096. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2097. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2098. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2099. return data
  2100. }
  2101. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2102. function displayWidth(cm) {
  2103. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2104. }
  2105. function displayHeight(cm) {
  2106. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2107. }
  2108. // Ensure the lineView.wrapping.heights array is populated. This is
  2109. // an array of bottom offsets for the lines that make up a drawn
  2110. // line. When lineWrapping is on, there might be more than one
  2111. // height.
  2112. function ensureLineHeights(cm, lineView, rect) {
  2113. var wrapping = cm.options.lineWrapping;
  2114. var curWidth = wrapping && displayWidth(cm);
  2115. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2116. var heights = lineView.measure.heights = [];
  2117. if (wrapping) {
  2118. lineView.measure.width = curWidth;
  2119. var rects = lineView.text.firstChild.getClientRects();
  2120. for (var i = 0; i < rects.length - 1; i++) {
  2121. var cur = rects[i], next = rects[i + 1];
  2122. if (Math.abs(cur.bottom - next.bottom) > 2)
  2123. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2124. }
  2125. }
  2126. heights.push(rect.bottom - rect.top);
  2127. }
  2128. }
  2129. // Find a line map (mapping character offsets to text nodes) and a
  2130. // measurement cache for the given line number. (A line view might
  2131. // contain multiple lines when collapsed ranges are present.)
  2132. function mapFromLineView(lineView, line, lineN) {
  2133. if (lineView.line == line)
  2134. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2135. for (var i = 0; i < lineView.rest.length; i++)
  2136. { if (lineView.rest[i] == line)
  2137. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2138. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2139. { if (lineNo(lineView.rest[i$1]) > lineN)
  2140. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2141. }
  2142. // Render a line into the hidden node display.externalMeasured. Used
  2143. // when measurement is needed for a line that's not in the viewport.
  2144. function updateExternalMeasurement(cm, line) {
  2145. line = visualLine(line);
  2146. var lineN = lineNo(line);
  2147. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2148. view.lineN = lineN;
  2149. var built = view.built = buildLineContent(cm, view);
  2150. view.text = built.pre;
  2151. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2152. return view
  2153. }
  2154. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2155. // for a given character.
  2156. function measureChar(cm, line, ch, bias) {
  2157. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2158. }
  2159. // Find a line view that corresponds to the given line number.
  2160. function findViewForLine(cm, lineN) {
  2161. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2162. { return cm.display.view[findViewIndex(cm, lineN)] }
  2163. var ext = cm.display.externalMeasured;
  2164. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2165. { return ext }
  2166. }
  2167. // Measurement can be split in two steps, the set-up work that
  2168. // applies to the whole line, and the measurement of the actual
  2169. // character. Functions like coordsChar, that need to do a lot of
  2170. // measurements in a row, can thus ensure that the set-up work is
  2171. // only done once.
  2172. function prepareMeasureForLine(cm, line) {
  2173. var lineN = lineNo(line);
  2174. var view = findViewForLine(cm, lineN);
  2175. if (view && !view.text) {
  2176. view = null;
  2177. } else if (view && view.changes) {
  2178. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2179. cm.curOp.forceUpdate = true;
  2180. }
  2181. if (!view)
  2182. { view = updateExternalMeasurement(cm, line); }
  2183. var info = mapFromLineView(view, line, lineN);
  2184. return {
  2185. line: line, view: view, rect: null,
  2186. map: info.map, cache: info.cache, before: info.before,
  2187. hasHeights: false
  2188. }
  2189. }
  2190. // Given a prepared measurement object, measures the position of an
  2191. // actual character (or fetches it from the cache).
  2192. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2193. if (prepared.before) { ch = -1; }
  2194. var key = ch + (bias || ""), found;
  2195. if (prepared.cache.hasOwnProperty(key)) {
  2196. found = prepared.cache[key];
  2197. } else {
  2198. if (!prepared.rect)
  2199. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2200. if (!prepared.hasHeights) {
  2201. ensureLineHeights(cm, prepared.view, prepared.rect);
  2202. prepared.hasHeights = true;
  2203. }
  2204. found = measureCharInner(cm, prepared, ch, bias);
  2205. if (!found.bogus) { prepared.cache[key] = found; }
  2206. }
  2207. return {left: found.left, right: found.right,
  2208. top: varHeight ? found.rtop : found.top,
  2209. bottom: varHeight ? found.rbottom : found.bottom}
  2210. }
  2211. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2212. function nodeAndOffsetInLineMap(map, ch, bias) {
  2213. var node, start, end, collapse, mStart, mEnd;
  2214. // First, search the line map for the text node corresponding to,
  2215. // or closest to, the target character.
  2216. for (var i = 0; i < map.length; i += 3) {
  2217. mStart = map[i];
  2218. mEnd = map[i + 1];
  2219. if (ch < mStart) {
  2220. start = 0; end = 1;
  2221. collapse = "left";
  2222. } else if (ch < mEnd) {
  2223. start = ch - mStart;
  2224. end = start + 1;
  2225. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2226. end = mEnd - mStart;
  2227. start = end - 1;
  2228. if (ch >= mEnd) { collapse = "right"; }
  2229. }
  2230. if (start != null) {
  2231. node = map[i + 2];
  2232. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2233. { collapse = bias; }
  2234. if (bias == "left" && start == 0)
  2235. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2236. node = map[(i -= 3) + 2];
  2237. collapse = "left";
  2238. } }
  2239. if (bias == "right" && start == mEnd - mStart)
  2240. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2241. node = map[(i += 3) + 2];
  2242. collapse = "right";
  2243. } }
  2244. break
  2245. }
  2246. }
  2247. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2248. }
  2249. function getUsefulRect(rects, bias) {
  2250. var rect = nullRect;
  2251. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2252. if ((rect = rects[i]).left != rect.right) { break }
  2253. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2254. if ((rect = rects[i$1]).left != rect.right) { break }
  2255. } }
  2256. return rect
  2257. }
  2258. function measureCharInner(cm, prepared, ch, bias) {
  2259. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2260. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2261. var rect;
  2262. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2263. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2264. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2265. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2266. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2267. { rect = node.parentNode.getBoundingClientRect(); }
  2268. else
  2269. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2270. if (rect.left || rect.right || start == 0) { break }
  2271. end = start;
  2272. start = start - 1;
  2273. collapse = "right";
  2274. }
  2275. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2276. } else { // If it is a widget, simply get the box for the whole widget.
  2277. if (start > 0) { collapse = bias = "right"; }
  2278. var rects;
  2279. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2280. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2281. else
  2282. { rect = node.getBoundingClientRect(); }
  2283. }
  2284. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2285. var rSpan = node.parentNode.getClientRects()[0];
  2286. if (rSpan)
  2287. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2288. else
  2289. { rect = nullRect; }
  2290. }
  2291. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2292. var mid = (rtop + rbot) / 2;
  2293. var heights = prepared.view.measure.heights;
  2294. var i = 0;
  2295. for (; i < heights.length - 1; i++)
  2296. { if (mid < heights[i]) { break } }
  2297. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2298. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2299. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2300. top: top, bottom: bot};
  2301. if (!rect.left && !rect.right) { result.bogus = true; }
  2302. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2303. return result
  2304. }
  2305. // Work around problem with bounding client rects on ranges being
  2306. // returned incorrectly when zoomed on IE10 and below.
  2307. function maybeUpdateRectForZooming(measure, rect) {
  2308. if (!window.screen || screen.logicalXDPI == null ||
  2309. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2310. { return rect }
  2311. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2312. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2313. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2314. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2315. }
  2316. function clearLineMeasurementCacheFor(lineView) {
  2317. if (lineView.measure) {
  2318. lineView.measure.cache = {};
  2319. lineView.measure.heights = null;
  2320. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2321. { lineView.measure.caches[i] = {}; } }
  2322. }
  2323. }
  2324. function clearLineMeasurementCache(cm) {
  2325. cm.display.externalMeasure = null;
  2326. removeChildren(cm.display.lineMeasure);
  2327. for (var i = 0; i < cm.display.view.length; i++)
  2328. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2329. }
  2330. function clearCaches(cm) {
  2331. clearLineMeasurementCache(cm);
  2332. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2333. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2334. cm.display.lineNumChars = null;
  2335. }
  2336. function pageScrollX() {
  2337. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2338. // which causes page_Offset and bounding client rects to use
  2339. // different reference viewports and invalidate our calculations.
  2340. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2341. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2342. }
  2343. function pageScrollY() {
  2344. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2345. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2346. }
  2347. function widgetTopHeight(lineObj) {
  2348. var height = 0;
  2349. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2350. { height += widgetHeight(lineObj.widgets[i]); } } }
  2351. return height
  2352. }
  2353. // Converts a {top, bottom, left, right} box from line-local
  2354. // coordinates into another coordinate system. Context may be one of
  2355. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2356. // or "page".
  2357. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2358. if (!includeWidgets) {
  2359. var height = widgetTopHeight(lineObj);
  2360. rect.top += height; rect.bottom += height;
  2361. }
  2362. if (context == "line") { return rect }
  2363. if (!context) { context = "local"; }
  2364. var yOff = heightAtLine(lineObj);
  2365. if (context == "local") { yOff += paddingTop(cm.display); }
  2366. else { yOff -= cm.display.viewOffset; }
  2367. if (context == "page" || context == "window") {
  2368. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2369. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2370. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2371. rect.left += xOff; rect.right += xOff;
  2372. }
  2373. rect.top += yOff; rect.bottom += yOff;
  2374. return rect
  2375. }
  2376. // Coverts a box from "div" coords to another coordinate system.
  2377. // Context may be "window", "page", "div", or "local"./null.
  2378. function fromCoordSystem(cm, coords, context) {
  2379. if (context == "div") { return coords }
  2380. var left = coords.left, top = coords.top;
  2381. // First move into "page" coordinate system
  2382. if (context == "page") {
  2383. left -= pageScrollX();
  2384. top -= pageScrollY();
  2385. } else if (context == "local" || !context) {
  2386. var localBox = cm.display.sizer.getBoundingClientRect();
  2387. left += localBox.left;
  2388. top += localBox.top;
  2389. }
  2390. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2391. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2392. }
  2393. function charCoords(cm, pos, context, lineObj, bias) {
  2394. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2395. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2396. }
  2397. // Returns a box for a given cursor position, which may have an
  2398. // 'other' property containing the position of the secondary cursor
  2399. // on a bidi boundary.
  2400. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2401. // and after `char - 1` in writing order of `char - 1`
  2402. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2403. // and before `char` in writing order of `char`
  2404. // Examples (upper-case letters are RTL, lower-case are LTR):
  2405. // Pos(0, 1, ...)
  2406. // before after
  2407. // ab a|b a|b
  2408. // aB a|B aB|
  2409. // Ab |Ab A|b
  2410. // AB B|A B|A
  2411. // Every position after the last character on a line is considered to stick
  2412. // to the last character on the line.
  2413. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2414. lineObj = lineObj || getLine(cm.doc, pos.line);
  2415. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2416. function get(ch, right) {
  2417. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2418. if (right) { m.left = m.right; } else { m.right = m.left; }
  2419. return intoCoordSystem(cm, lineObj, m, context)
  2420. }
  2421. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2422. if (ch >= lineObj.text.length) {
  2423. ch = lineObj.text.length;
  2424. sticky = "before";
  2425. } else if (ch <= 0) {
  2426. ch = 0;
  2427. sticky = "after";
  2428. }
  2429. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2430. function getBidi(ch, partPos, invert) {
  2431. var part = order[partPos], right = part.level == 1;
  2432. return get(invert ? ch - 1 : ch, right != invert)
  2433. }
  2434. var partPos = getBidiPartAt(order, ch, sticky);
  2435. var other = bidiOther;
  2436. var val = getBidi(ch, partPos, sticky == "before");
  2437. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2438. return val
  2439. }
  2440. // Used to cheaply estimate the coordinates for a position. Used for
  2441. // intermediate scroll updates.
  2442. function estimateCoords(cm, pos) {
  2443. var left = 0;
  2444. pos = clipPos(cm.doc, pos);
  2445. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2446. var lineObj = getLine(cm.doc, pos.line);
  2447. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2448. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2449. }
  2450. // Positions returned by coordsChar contain some extra information.
  2451. // xRel is the relative x position of the input coordinates compared
  2452. // to the found position (so xRel > 0 means the coordinates are to
  2453. // the right of the character position, for example). When outside
  2454. // is true, that means the coordinates lie outside the line's
  2455. // vertical range.
  2456. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2457. var pos = Pos(line, ch, sticky);
  2458. pos.xRel = xRel;
  2459. if (outside) { pos.outside = outside; }
  2460. return pos
  2461. }
  2462. // Compute the character position closest to the given coordinates.
  2463. // Input must be lineSpace-local ("div" coordinate system).
  2464. function coordsChar(cm, x, y) {
  2465. var doc = cm.doc;
  2466. y += cm.display.viewOffset;
  2467. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2468. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2469. if (lineN > last)
  2470. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2471. if (x < 0) { x = 0; }
  2472. var lineObj = getLine(doc, lineN);
  2473. for (;;) {
  2474. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2475. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2476. if (!collapsed) { return found }
  2477. var rangeEnd = collapsed.find(1);
  2478. if (rangeEnd.line == lineN) { return rangeEnd }
  2479. lineObj = getLine(doc, lineN = rangeEnd.line);
  2480. }
  2481. }
  2482. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2483. y -= widgetTopHeight(lineObj);
  2484. var end = lineObj.text.length;
  2485. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2486. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2487. return {begin: begin, end: end}
  2488. }
  2489. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2490. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2491. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2492. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2493. }
  2494. // Returns true if the given side of a box is after the given
  2495. // coordinates, in top-to-bottom, left-to-right order.
  2496. function boxIsAfter(box, x, y, left) {
  2497. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2498. }
  2499. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2500. // Move y into line-local coordinate space
  2501. y -= heightAtLine(lineObj);
  2502. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2503. // When directly calling `measureCharPrepared`, we have to adjust
  2504. // for the widgets at this line.
  2505. var widgetHeight = widgetTopHeight(lineObj);
  2506. var begin = 0, end = lineObj.text.length, ltr = true;
  2507. var order = getOrder(lineObj, cm.doc.direction);
  2508. // If the line isn't plain left-to-right text, first figure out
  2509. // which bidi section the coordinates fall into.
  2510. if (order) {
  2511. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2512. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2513. ltr = part.level != 1;
  2514. // The awkward -1 offsets are needed because findFirst (called
  2515. // on these below) will treat its first bound as inclusive,
  2516. // second as exclusive, but we want to actually address the
  2517. // characters in the part's range
  2518. begin = ltr ? part.from : part.to - 1;
  2519. end = ltr ? part.to : part.from - 1;
  2520. }
  2521. // A binary search to find the first character whose bounding box
  2522. // starts after the coordinates. If we run across any whose box wrap
  2523. // the coordinates, store that.
  2524. var chAround = null, boxAround = null;
  2525. var ch = findFirst(function (ch) {
  2526. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2527. box.top += widgetHeight; box.bottom += widgetHeight;
  2528. if (!boxIsAfter(box, x, y, false)) { return false }
  2529. if (box.top <= y && box.left <= x) {
  2530. chAround = ch;
  2531. boxAround = box;
  2532. }
  2533. return true
  2534. }, begin, end);
  2535. var baseX, sticky, outside = false;
  2536. // If a box around the coordinates was found, use that
  2537. if (boxAround) {
  2538. // Distinguish coordinates nearer to the left or right side of the box
  2539. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2540. ch = chAround + (atStart ? 0 : 1);
  2541. sticky = atStart ? "after" : "before";
  2542. baseX = atLeft ? boxAround.left : boxAround.right;
  2543. } else {
  2544. // (Adjust for extended bound, if necessary.)
  2545. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2546. // To determine which side to associate with, get the box to the
  2547. // left of the character and compare it's vertical position to the
  2548. // coordinates
  2549. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2550. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2551. "after" : "before";
  2552. // Now get accurate coordinates for this place, in order to get a
  2553. // base X position
  2554. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2555. baseX = coords.left;
  2556. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2557. }
  2558. ch = skipExtendingChars(lineObj.text, ch, 1);
  2559. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2560. }
  2561. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2562. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2563. // situation, we can take this ordering to correspond to the visual
  2564. // ordering. This finds the first part whose end is after the given
  2565. // coordinates.
  2566. var index = findFirst(function (i) {
  2567. var part = order[i], ltr = part.level != 1;
  2568. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2569. "line", lineObj, preparedMeasure), x, y, true)
  2570. }, 0, order.length - 1);
  2571. var part = order[index];
  2572. // If this isn't the first part, the part's start is also after
  2573. // the coordinates, and the coordinates aren't on the same line as
  2574. // that start, move one part back.
  2575. if (index > 0) {
  2576. var ltr = part.level != 1;
  2577. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2578. "line", lineObj, preparedMeasure);
  2579. if (boxIsAfter(start, x, y, true) && start.top > y)
  2580. { part = order[index - 1]; }
  2581. }
  2582. return part
  2583. }
  2584. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2585. // In a wrapped line, rtl text on wrapping boundaries can do things
  2586. // that don't correspond to the ordering in our `order` array at
  2587. // all, so a binary search doesn't work, and we want to return a
  2588. // part that only spans one line so that the binary search in
  2589. // coordsCharInner is safe. As such, we first find the extent of the
  2590. // wrapped line, and then do a flat search in which we discard any
  2591. // spans that aren't on the line.
  2592. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2593. var begin = ref.begin;
  2594. var end = ref.end;
  2595. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2596. var part = null, closestDist = null;
  2597. for (var i = 0; i < order.length; i++) {
  2598. var p = order[i];
  2599. if (p.from >= end || p.to <= begin) { continue }
  2600. var ltr = p.level != 1;
  2601. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2602. // Weigh against spans ending before this, so that they are only
  2603. // picked if nothing ends after
  2604. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2605. if (!part || closestDist > dist) {
  2606. part = p;
  2607. closestDist = dist;
  2608. }
  2609. }
  2610. if (!part) { part = order[order.length - 1]; }
  2611. // Clip the part to the wrapped line.
  2612. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2613. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2614. return part
  2615. }
  2616. var measureText;
  2617. // Compute the default text height.
  2618. function textHeight(display) {
  2619. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2620. if (measureText == null) {
  2621. measureText = elt("pre", null, "CodeMirror-line-like");
  2622. // Measure a bunch of lines, for browsers that compute
  2623. // fractional heights.
  2624. for (var i = 0; i < 49; ++i) {
  2625. measureText.appendChild(document.createTextNode("x"));
  2626. measureText.appendChild(elt("br"));
  2627. }
  2628. measureText.appendChild(document.createTextNode("x"));
  2629. }
  2630. removeChildrenAndAdd(display.measure, measureText);
  2631. var height = measureText.offsetHeight / 50;
  2632. if (height > 3) { display.cachedTextHeight = height; }
  2633. removeChildren(display.measure);
  2634. return height || 1
  2635. }
  2636. // Compute the default character width.
  2637. function charWidth(display) {
  2638. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2639. var anchor = elt("span", "xxxxxxxxxx");
  2640. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2641. removeChildrenAndAdd(display.measure, pre);
  2642. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2643. if (width > 2) { display.cachedCharWidth = width; }
  2644. return width || 10
  2645. }
  2646. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2647. // view, so that we don't interleave reading and writing to the DOM.
  2648. function getDimensions(cm) {
  2649. var d = cm.display, left = {}, width = {};
  2650. var gutterLeft = d.gutters.clientLeft;
  2651. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2652. var id = cm.display.gutterSpecs[i].className;
  2653. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2654. width[id] = n.clientWidth;
  2655. }
  2656. return {fixedPos: compensateForHScroll(d),
  2657. gutterTotalWidth: d.gutters.offsetWidth,
  2658. gutterLeft: left,
  2659. gutterWidth: width,
  2660. wrapperWidth: d.wrapper.clientWidth}
  2661. }
  2662. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2663. // but using getBoundingClientRect to get a sub-pixel-accurate
  2664. // result.
  2665. function compensateForHScroll(display) {
  2666. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2667. }
  2668. // Returns a function that estimates the height of a line, to use as
  2669. // first approximation until the line becomes visible (and is thus
  2670. // properly measurable).
  2671. function estimateHeight(cm) {
  2672. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2673. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2674. return function (line) {
  2675. if (lineIsHidden(cm.doc, line)) { return 0 }
  2676. var widgetsHeight = 0;
  2677. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2678. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2679. } }
  2680. if (wrapping)
  2681. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2682. else
  2683. { return widgetsHeight + th }
  2684. }
  2685. }
  2686. function estimateLineHeights(cm) {
  2687. var doc = cm.doc, est = estimateHeight(cm);
  2688. doc.iter(function (line) {
  2689. var estHeight = est(line);
  2690. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2691. });
  2692. }
  2693. // Given a mouse event, find the corresponding position. If liberal
  2694. // is false, it checks whether a gutter or scrollbar was clicked,
  2695. // and returns null if it was. forRect is used by rectangular
  2696. // selections, and tries to estimate a character position even for
  2697. // coordinates beyond the right of the text.
  2698. function posFromMouse(cm, e, liberal, forRect) {
  2699. var display = cm.display;
  2700. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2701. var x, y, space = display.lineSpace.getBoundingClientRect();
  2702. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2703. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2704. catch (e$1) { return null }
  2705. var coords = coordsChar(cm, x, y), line;
  2706. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2707. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2708. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2709. }
  2710. return coords
  2711. }
  2712. // Find the view element corresponding to a given line. Return null
  2713. // when the line isn't visible.
  2714. function findViewIndex(cm, n) {
  2715. if (n >= cm.display.viewTo) { return null }
  2716. n -= cm.display.viewFrom;
  2717. if (n < 0) { return null }
  2718. var view = cm.display.view;
  2719. for (var i = 0; i < view.length; i++) {
  2720. n -= view[i].size;
  2721. if (n < 0) { return i }
  2722. }
  2723. }
  2724. // Updates the display.view data structure for a given change to the
  2725. // document. From and to are in pre-change coordinates. Lendiff is
  2726. // the amount of lines added or subtracted by the change. This is
  2727. // used for changes that span multiple lines, or change the way
  2728. // lines are divided into visual lines. regLineChange (below)
  2729. // registers single-line changes.
  2730. function regChange(cm, from, to, lendiff) {
  2731. if (from == null) { from = cm.doc.first; }
  2732. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2733. if (!lendiff) { lendiff = 0; }
  2734. var display = cm.display;
  2735. if (lendiff && to < display.viewTo &&
  2736. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2737. { display.updateLineNumbers = from; }
  2738. cm.curOp.viewChanged = true;
  2739. if (from >= display.viewTo) { // Change after
  2740. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2741. { resetView(cm); }
  2742. } else if (to <= display.viewFrom) { // Change before
  2743. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2744. resetView(cm);
  2745. } else {
  2746. display.viewFrom += lendiff;
  2747. display.viewTo += lendiff;
  2748. }
  2749. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2750. resetView(cm);
  2751. } else if (from <= display.viewFrom) { // Top overlap
  2752. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2753. if (cut) {
  2754. display.view = display.view.slice(cut.index);
  2755. display.viewFrom = cut.lineN;
  2756. display.viewTo += lendiff;
  2757. } else {
  2758. resetView(cm);
  2759. }
  2760. } else if (to >= display.viewTo) { // Bottom overlap
  2761. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2762. if (cut$1) {
  2763. display.view = display.view.slice(0, cut$1.index);
  2764. display.viewTo = cut$1.lineN;
  2765. } else {
  2766. resetView(cm);
  2767. }
  2768. } else { // Gap in the middle
  2769. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2770. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2771. if (cutTop && cutBot) {
  2772. display.view = display.view.slice(0, cutTop.index)
  2773. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2774. .concat(display.view.slice(cutBot.index));
  2775. display.viewTo += lendiff;
  2776. } else {
  2777. resetView(cm);
  2778. }
  2779. }
  2780. var ext = display.externalMeasured;
  2781. if (ext) {
  2782. if (to < ext.lineN)
  2783. { ext.lineN += lendiff; }
  2784. else if (from < ext.lineN + ext.size)
  2785. { display.externalMeasured = null; }
  2786. }
  2787. }
  2788. // Register a change to a single line. Type must be one of "text",
  2789. // "gutter", "class", "widget"
  2790. function regLineChange(cm, line, type) {
  2791. cm.curOp.viewChanged = true;
  2792. var display = cm.display, ext = cm.display.externalMeasured;
  2793. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2794. { display.externalMeasured = null; }
  2795. if (line < display.viewFrom || line >= display.viewTo) { return }
  2796. var lineView = display.view[findViewIndex(cm, line)];
  2797. if (lineView.node == null) { return }
  2798. var arr = lineView.changes || (lineView.changes = []);
  2799. if (indexOf(arr, type) == -1) { arr.push(type); }
  2800. }
  2801. // Clear the view.
  2802. function resetView(cm) {
  2803. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2804. cm.display.view = [];
  2805. cm.display.viewOffset = 0;
  2806. }
  2807. function viewCuttingPoint(cm, oldN, newN, dir) {
  2808. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2809. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2810. { return {index: index, lineN: newN} }
  2811. var n = cm.display.viewFrom;
  2812. for (var i = 0; i < index; i++)
  2813. { n += view[i].size; }
  2814. if (n != oldN) {
  2815. if (dir > 0) {
  2816. if (index == view.length - 1) { return null }
  2817. diff = (n + view[index].size) - oldN;
  2818. index++;
  2819. } else {
  2820. diff = n - oldN;
  2821. }
  2822. oldN += diff; newN += diff;
  2823. }
  2824. while (visualLineNo(cm.doc, newN) != newN) {
  2825. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2826. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2827. index += dir;
  2828. }
  2829. return {index: index, lineN: newN}
  2830. }
  2831. // Force the view to cover a given range, adding empty view element
  2832. // or clipping off existing ones as needed.
  2833. function adjustView(cm, from, to) {
  2834. var display = cm.display, view = display.view;
  2835. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2836. display.view = buildViewArray(cm, from, to);
  2837. display.viewFrom = from;
  2838. } else {
  2839. if (display.viewFrom > from)
  2840. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2841. else if (display.viewFrom < from)
  2842. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2843. display.viewFrom = from;
  2844. if (display.viewTo < to)
  2845. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2846. else if (display.viewTo > to)
  2847. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2848. }
  2849. display.viewTo = to;
  2850. }
  2851. // Count the number of lines in the view whose DOM representation is
  2852. // out of date (or nonexistent).
  2853. function countDirtyView(cm) {
  2854. var view = cm.display.view, dirty = 0;
  2855. for (var i = 0; i < view.length; i++) {
  2856. var lineView = view[i];
  2857. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2858. }
  2859. return dirty
  2860. }
  2861. function updateSelection(cm) {
  2862. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2863. }
  2864. function prepareSelection(cm, primary) {
  2865. if ( primary === void 0 ) primary = true;
  2866. var doc = cm.doc, result = {};
  2867. var curFragment = result.cursors = document.createDocumentFragment();
  2868. var selFragment = result.selection = document.createDocumentFragment();
  2869. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2870. if (!primary && i == doc.sel.primIndex) { continue }
  2871. var range = doc.sel.ranges[i];
  2872. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2873. var collapsed = range.empty();
  2874. if (collapsed || cm.options.showCursorWhenSelecting)
  2875. { drawSelectionCursor(cm, range.head, curFragment); }
  2876. if (!collapsed)
  2877. { drawSelectionRange(cm, range, selFragment); }
  2878. }
  2879. return result
  2880. }
  2881. // Draws a cursor for the given range
  2882. function drawSelectionCursor(cm, head, output) {
  2883. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2884. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2885. cursor.style.left = pos.left + "px";
  2886. cursor.style.top = pos.top + "px";
  2887. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2888. if (pos.other) {
  2889. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2890. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2891. otherCursor.style.display = "";
  2892. otherCursor.style.left = pos.other.left + "px";
  2893. otherCursor.style.top = pos.other.top + "px";
  2894. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2895. }
  2896. }
  2897. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2898. // Draws the given range as a highlighted selection
  2899. function drawSelectionRange(cm, range, output) {
  2900. var display = cm.display, doc = cm.doc;
  2901. var fragment = document.createDocumentFragment();
  2902. var padding = paddingH(cm.display), leftSide = padding.left;
  2903. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2904. var docLTR = doc.direction == "ltr";
  2905. function add(left, top, width, bottom) {
  2906. if (top < 0) { top = 0; }
  2907. top = Math.round(top);
  2908. bottom = Math.round(bottom);
  2909. 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")));
  2910. }
  2911. function drawForLine(line, fromArg, toArg) {
  2912. var lineObj = getLine(doc, line);
  2913. var lineLen = lineObj.text.length;
  2914. var start, end;
  2915. function coords(ch, bias) {
  2916. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2917. }
  2918. function wrapX(pos, dir, side) {
  2919. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2920. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2921. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2922. return coords(ch, prop)[prop]
  2923. }
  2924. var order = getOrder(lineObj, doc.direction);
  2925. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2926. var ltr = dir == "ltr";
  2927. var fromPos = coords(from, ltr ? "left" : "right");
  2928. var toPos = coords(to - 1, ltr ? "right" : "left");
  2929. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2930. var first = i == 0, last = !order || i == order.length - 1;
  2931. if (toPos.top - fromPos.top <= 3) { // Single line
  2932. var openLeft = (docLTR ? openStart : openEnd) && first;
  2933. var openRight = (docLTR ? openEnd : openStart) && last;
  2934. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2935. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2936. add(left, fromPos.top, right - left, fromPos.bottom);
  2937. } else { // Multiple lines
  2938. var topLeft, topRight, botLeft, botRight;
  2939. if (ltr) {
  2940. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2941. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2942. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2943. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2944. } else {
  2945. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2946. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2947. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2948. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2949. }
  2950. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2951. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2952. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2953. }
  2954. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2955. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2956. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2957. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2958. });
  2959. return {start: start, end: end}
  2960. }
  2961. var sFrom = range.from(), sTo = range.to();
  2962. if (sFrom.line == sTo.line) {
  2963. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2964. } else {
  2965. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2966. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2967. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2968. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2969. if (singleVLine) {
  2970. if (leftEnd.top < rightStart.top - 2) {
  2971. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2972. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2973. } else {
  2974. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2975. }
  2976. }
  2977. if (leftEnd.bottom < rightStart.top)
  2978. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  2979. }
  2980. output.appendChild(fragment);
  2981. }
  2982. // Cursor-blinking
  2983. function restartBlink(cm) {
  2984. if (!cm.state.focused) { return }
  2985. var display = cm.display;
  2986. clearInterval(display.blinker);
  2987. var on = true;
  2988. display.cursorDiv.style.visibility = "";
  2989. if (cm.options.cursorBlinkRate > 0)
  2990. { display.blinker = setInterval(function () {
  2991. if (!cm.hasFocus()) { onBlur(cm); }
  2992. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2993. }, cm.options.cursorBlinkRate); }
  2994. else if (cm.options.cursorBlinkRate < 0)
  2995. { display.cursorDiv.style.visibility = "hidden"; }
  2996. }
  2997. function ensureFocus(cm) {
  2998. if (!cm.hasFocus()) {
  2999. cm.display.input.focus();
  3000. if (!cm.state.focused) { onFocus(cm); }
  3001. }
  3002. }
  3003. function delayBlurEvent(cm) {
  3004. cm.state.delayingBlurEvent = true;
  3005. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  3006. cm.state.delayingBlurEvent = false;
  3007. if (cm.state.focused) { onBlur(cm); }
  3008. } }, 100);
  3009. }
  3010. function onFocus(cm, e) {
  3011. if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  3012. if (cm.options.readOnly == "nocursor") { return }
  3013. if (!cm.state.focused) {
  3014. signal(cm, "focus", cm, e);
  3015. cm.state.focused = true;
  3016. addClass(cm.display.wrapper, "CodeMirror-focused");
  3017. // This test prevents this from firing when a context
  3018. // menu is closed (since the input reset would kill the
  3019. // select-all detection hack)
  3020. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3021. cm.display.input.reset();
  3022. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3023. }
  3024. cm.display.input.receivedFocus();
  3025. }
  3026. restartBlink(cm);
  3027. }
  3028. function onBlur(cm, e) {
  3029. if (cm.state.delayingBlurEvent) { return }
  3030. if (cm.state.focused) {
  3031. signal(cm, "blur", cm, e);
  3032. cm.state.focused = false;
  3033. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3034. }
  3035. clearInterval(cm.display.blinker);
  3036. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3037. }
  3038. // Read the actual heights of the rendered lines, and update their
  3039. // stored heights to match.
  3040. function updateHeightsInViewport(cm) {
  3041. var display = cm.display;
  3042. var prevBottom = display.lineDiv.offsetTop;
  3043. for (var i = 0; i < display.view.length; i++) {
  3044. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3045. var height = (void 0), width = 0;
  3046. if (cur.hidden) { continue }
  3047. if (ie && ie_version < 8) {
  3048. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3049. height = bot - prevBottom;
  3050. prevBottom = bot;
  3051. } else {
  3052. var box = cur.node.getBoundingClientRect();
  3053. height = box.bottom - box.top;
  3054. // Check that lines don't extend past the right of the current
  3055. // editor width
  3056. if (!wrapping && cur.text.firstChild)
  3057. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3058. }
  3059. var diff = cur.line.height - height;
  3060. if (diff > .005 || diff < -.005) {
  3061. updateLineHeight(cur.line, height);
  3062. updateWidgetHeight(cur.line);
  3063. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3064. { updateWidgetHeight(cur.rest[j]); } }
  3065. }
  3066. if (width > cm.display.sizerWidth) {
  3067. var chWidth = Math.ceil(width / charWidth(cm.display));
  3068. if (chWidth > cm.display.maxLineLength) {
  3069. cm.display.maxLineLength = chWidth;
  3070. cm.display.maxLine = cur.line;
  3071. cm.display.maxLineChanged = true;
  3072. }
  3073. }
  3074. }
  3075. }
  3076. // Read and store the height of line widgets associated with the
  3077. // given line.
  3078. function updateWidgetHeight(line) {
  3079. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3080. var w = line.widgets[i], parent = w.node.parentNode;
  3081. if (parent) { w.height = parent.offsetHeight; }
  3082. } }
  3083. }
  3084. // Compute the lines that are visible in a given viewport (defaults
  3085. // the the current scroll position). viewport may contain top,
  3086. // height, and ensure (see op.scrollToPos) properties.
  3087. function visibleLines(display, doc, viewport) {
  3088. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3089. top = Math.floor(top - paddingTop(display));
  3090. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3091. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3092. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3093. // forces those lines into the viewport (if possible).
  3094. if (viewport && viewport.ensure) {
  3095. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3096. if (ensureFrom < from) {
  3097. from = ensureFrom;
  3098. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3099. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3100. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3101. to = ensureTo;
  3102. }
  3103. }
  3104. return {from: from, to: Math.max(to, from + 1)}
  3105. }
  3106. // SCROLLING THINGS INTO VIEW
  3107. // If an editor sits on the top or bottom of the window, partially
  3108. // scrolled out of view, this ensures that the cursor is visible.
  3109. function maybeScrollWindow(cm, rect) {
  3110. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3111. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3112. if (rect.top + box.top < 0) { doScroll = true; }
  3113. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3114. if (doScroll != null && !phantom) {
  3115. 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;"));
  3116. cm.display.lineSpace.appendChild(scrollNode);
  3117. scrollNode.scrollIntoView(doScroll);
  3118. cm.display.lineSpace.removeChild(scrollNode);
  3119. }
  3120. }
  3121. // Scroll a given position into view (immediately), verifying that
  3122. // it actually became visible (as line heights are accurately
  3123. // measured, the position of something may 'drift' during drawing).
  3124. function scrollPosIntoView(cm, pos, end, margin) {
  3125. if (margin == null) { margin = 0; }
  3126. var rect;
  3127. if (!cm.options.lineWrapping && pos == end) {
  3128. // Set pos and end to the cursor positions around the character pos sticks to
  3129. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3130. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3131. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3132. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3133. }
  3134. for (var limit = 0; limit < 5; limit++) {
  3135. var changed = false;
  3136. var coords = cursorCoords(cm, pos);
  3137. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3138. rect = {left: Math.min(coords.left, endCoords.left),
  3139. top: Math.min(coords.top, endCoords.top) - margin,
  3140. right: Math.max(coords.left, endCoords.left),
  3141. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3142. var scrollPos = calculateScrollPos(cm, rect);
  3143. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3144. if (scrollPos.scrollTop != null) {
  3145. updateScrollTop(cm, scrollPos.scrollTop);
  3146. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3147. }
  3148. if (scrollPos.scrollLeft != null) {
  3149. setScrollLeft(cm, scrollPos.scrollLeft);
  3150. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3151. }
  3152. if (!changed) { break }
  3153. }
  3154. return rect
  3155. }
  3156. // Scroll a given set of coordinates into view (immediately).
  3157. function scrollIntoView(cm, rect) {
  3158. var scrollPos = calculateScrollPos(cm, rect);
  3159. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3160. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3161. }
  3162. // Calculate a new scroll position needed to scroll the given
  3163. // rectangle into view. Returns an object with scrollTop and
  3164. // scrollLeft properties. When these are undefined, the
  3165. // vertical/horizontal position does not need to be adjusted.
  3166. function calculateScrollPos(cm, rect) {
  3167. var display = cm.display, snapMargin = textHeight(cm.display);
  3168. if (rect.top < 0) { rect.top = 0; }
  3169. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3170. var screen = displayHeight(cm), result = {};
  3171. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3172. var docBottom = cm.doc.height + paddingVert(display);
  3173. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3174. if (rect.top < screentop) {
  3175. result.scrollTop = atTop ? 0 : rect.top;
  3176. } else if (rect.bottom > screentop + screen) {
  3177. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3178. if (newTop != screentop) { result.scrollTop = newTop; }
  3179. }
  3180. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  3181. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  3182. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  3183. var tooWide = rect.right - rect.left > screenw;
  3184. if (tooWide) { rect.right = rect.left + screenw; }
  3185. if (rect.left < 10)
  3186. { result.scrollLeft = 0; }
  3187. else if (rect.left < screenleft)
  3188. { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  3189. else if (rect.right > screenw + screenleft - 3)
  3190. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3191. return result
  3192. }
  3193. // Store a relative adjustment to the scroll position in the current
  3194. // operation (to be applied when the operation finishes).
  3195. function addToScrollTop(cm, top) {
  3196. if (top == null) { return }
  3197. resolveScrollToPos(cm);
  3198. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3199. }
  3200. // Make sure that at the end of the operation the current cursor is
  3201. // shown.
  3202. function ensureCursorVisible(cm) {
  3203. resolveScrollToPos(cm);
  3204. var cur = cm.getCursor();
  3205. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3206. }
  3207. function scrollToCoords(cm, x, y) {
  3208. if (x != null || y != null) { resolveScrollToPos(cm); }
  3209. if (x != null) { cm.curOp.scrollLeft = x; }
  3210. if (y != null) { cm.curOp.scrollTop = y; }
  3211. }
  3212. function scrollToRange(cm, range) {
  3213. resolveScrollToPos(cm);
  3214. cm.curOp.scrollToPos = range;
  3215. }
  3216. // When an operation has its scrollToPos property set, and another
  3217. // scroll action is applied before the end of the operation, this
  3218. // 'simulates' scrolling that position into view in a cheap way, so
  3219. // that the effect of intermediate scroll commands is not ignored.
  3220. function resolveScrollToPos(cm) {
  3221. var range = cm.curOp.scrollToPos;
  3222. if (range) {
  3223. cm.curOp.scrollToPos = null;
  3224. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3225. scrollToCoordsRange(cm, from, to, range.margin);
  3226. }
  3227. }
  3228. function scrollToCoordsRange(cm, from, to, margin) {
  3229. var sPos = calculateScrollPos(cm, {
  3230. left: Math.min(from.left, to.left),
  3231. top: Math.min(from.top, to.top) - margin,
  3232. right: Math.max(from.right, to.right),
  3233. bottom: Math.max(from.bottom, to.bottom) + margin
  3234. });
  3235. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3236. }
  3237. // Sync the scrollable area and scrollbars, ensure the viewport
  3238. // covers the visible area.
  3239. function updateScrollTop(cm, val) {
  3240. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3241. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3242. setScrollTop(cm, val, true);
  3243. if (gecko) { updateDisplaySimple(cm); }
  3244. startWorker(cm, 100);
  3245. }
  3246. function setScrollTop(cm, val, forceScroll) {
  3247. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3248. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3249. cm.doc.scrollTop = val;
  3250. cm.display.scrollbars.setScrollTop(val);
  3251. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3252. }
  3253. // Sync scroller and scrollbar, ensure the gutter elements are
  3254. // aligned.
  3255. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3256. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3257. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3258. cm.doc.scrollLeft = val;
  3259. alignHorizontally(cm);
  3260. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3261. cm.display.scrollbars.setScrollLeft(val);
  3262. }
  3263. // SCROLLBARS
  3264. // Prepare DOM reads needed to update the scrollbars. Done in one
  3265. // shot to minimize update/measure roundtrips.
  3266. function measureForScrollbars(cm) {
  3267. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3268. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3269. return {
  3270. clientHeight: d.scroller.clientHeight,
  3271. viewHeight: d.wrapper.clientHeight,
  3272. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3273. viewWidth: d.wrapper.clientWidth,
  3274. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3275. docHeight: docH,
  3276. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3277. nativeBarWidth: d.nativeBarWidth,
  3278. gutterWidth: gutterW
  3279. }
  3280. }
  3281. var NativeScrollbars = function(place, scroll, cm) {
  3282. this.cm = cm;
  3283. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3284. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3285. vert.tabIndex = horiz.tabIndex = -1;
  3286. place(vert); place(horiz);
  3287. on(vert, "scroll", function () {
  3288. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3289. });
  3290. on(horiz, "scroll", function () {
  3291. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3292. });
  3293. this.checkedZeroWidth = false;
  3294. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3295. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3296. };
  3297. NativeScrollbars.prototype.update = function (measure) {
  3298. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3299. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3300. var sWidth = measure.nativeBarWidth;
  3301. if (needsV) {
  3302. this.vert.style.display = "block";
  3303. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3304. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3305. // A bug in IE8 can cause this value to be negative, so guard it.
  3306. this.vert.firstChild.style.height =
  3307. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3308. } else {
  3309. this.vert.style.display = "";
  3310. this.vert.firstChild.style.height = "0";
  3311. }
  3312. if (needsH) {
  3313. this.horiz.style.display = "block";
  3314. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3315. this.horiz.style.left = measure.barLeft + "px";
  3316. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3317. this.horiz.firstChild.style.width =
  3318. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3319. } else {
  3320. this.horiz.style.display = "";
  3321. this.horiz.firstChild.style.width = "0";
  3322. }
  3323. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3324. if (sWidth == 0) { this.zeroWidthHack(); }
  3325. this.checkedZeroWidth = true;
  3326. }
  3327. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3328. };
  3329. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3330. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3331. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3332. };
  3333. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3334. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3335. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3336. };
  3337. NativeScrollbars.prototype.zeroWidthHack = function () {
  3338. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3339. this.horiz.style.height = this.vert.style.width = w;
  3340. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3341. this.disableHoriz = new Delayed;
  3342. this.disableVert = new Delayed;
  3343. };
  3344. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3345. bar.style.pointerEvents = "auto";
  3346. function maybeDisable() {
  3347. // To find out whether the scrollbar is still visible, we
  3348. // check whether the element under the pixel in the bottom
  3349. // right corner of the scrollbar box is the scrollbar box
  3350. // itself (when the bar is still visible) or its filler child
  3351. // (when the bar is hidden). If it is still visible, we keep
  3352. // it enabled, if it's hidden, we disable pointer events.
  3353. var box = bar.getBoundingClientRect();
  3354. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3355. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3356. if (elt != bar) { bar.style.pointerEvents = "none"; }
  3357. else { delay.set(1000, maybeDisable); }
  3358. }
  3359. delay.set(1000, maybeDisable);
  3360. };
  3361. NativeScrollbars.prototype.clear = function () {
  3362. var parent = this.horiz.parentNode;
  3363. parent.removeChild(this.horiz);
  3364. parent.removeChild(this.vert);
  3365. };
  3366. var NullScrollbars = function () {};
  3367. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3368. NullScrollbars.prototype.setScrollLeft = function () {};
  3369. NullScrollbars.prototype.setScrollTop = function () {};
  3370. NullScrollbars.prototype.clear = function () {};
  3371. function updateScrollbars(cm, measure) {
  3372. if (!measure) { measure = measureForScrollbars(cm); }
  3373. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3374. updateScrollbarsInner(cm, measure);
  3375. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3376. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3377. { updateHeightsInViewport(cm); }
  3378. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3379. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3380. }
  3381. }
  3382. // Re-synchronize the fake scrollbars with the actual size of the
  3383. // content.
  3384. function updateScrollbarsInner(cm, measure) {
  3385. var d = cm.display;
  3386. var sizes = d.scrollbars.update(measure);
  3387. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3388. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3389. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3390. if (sizes.right && sizes.bottom) {
  3391. d.scrollbarFiller.style.display = "block";
  3392. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3393. d.scrollbarFiller.style.width = sizes.right + "px";
  3394. } else { d.scrollbarFiller.style.display = ""; }
  3395. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3396. d.gutterFiller.style.display = "block";
  3397. d.gutterFiller.style.height = sizes.bottom + "px";
  3398. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3399. } else { d.gutterFiller.style.display = ""; }
  3400. }
  3401. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3402. function initScrollbars(cm) {
  3403. if (cm.display.scrollbars) {
  3404. cm.display.scrollbars.clear();
  3405. if (cm.display.scrollbars.addClass)
  3406. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3407. }
  3408. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3409. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3410. // Prevent clicks in the scrollbars from killing focus
  3411. on(node, "mousedown", function () {
  3412. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3413. });
  3414. node.setAttribute("cm-not-content", "true");
  3415. }, function (pos, axis) {
  3416. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3417. else { updateScrollTop(cm, pos); }
  3418. }, cm);
  3419. if (cm.display.scrollbars.addClass)
  3420. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3421. }
  3422. // Operations are used to wrap a series of changes to the editor
  3423. // state in such a way that each change won't have to update the
  3424. // cursor and display (which would be awkward, slow, and
  3425. // error-prone). Instead, display updates are batched and then all
  3426. // combined and executed at once.
  3427. var nextOpId = 0;
  3428. // Start a new operation.
  3429. function startOperation(cm) {
  3430. cm.curOp = {
  3431. cm: cm,
  3432. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3433. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3434. forceUpdate: false, // Used to force a redraw
  3435. updateInput: 0, // Whether to reset the input textarea
  3436. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3437. changeObjs: null, // Accumulated changes, for firing change events
  3438. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3439. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3440. selectionChanged: false, // Whether the selection needs to be redrawn
  3441. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3442. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3443. scrollToPos: null, // Used to scroll to a specific position
  3444. focus: false,
  3445. id: ++nextOpId // Unique ID
  3446. };
  3447. pushOperation(cm.curOp);
  3448. }
  3449. // Finish an operation, updating the display and signalling delayed events
  3450. function endOperation(cm) {
  3451. var op = cm.curOp;
  3452. if (op) { finishOperation(op, function (group) {
  3453. for (var i = 0; i < group.ops.length; i++)
  3454. { group.ops[i].cm.curOp = null; }
  3455. endOperations(group);
  3456. }); }
  3457. }
  3458. // The DOM updates done when an operation finishes are batched so
  3459. // that the minimum number of relayouts are required.
  3460. function endOperations(group) {
  3461. var ops = group.ops;
  3462. for (var i = 0; i < ops.length; i++) // Read DOM
  3463. { endOperation_R1(ops[i]); }
  3464. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3465. { endOperation_W1(ops[i$1]); }
  3466. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3467. { endOperation_R2(ops[i$2]); }
  3468. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3469. { endOperation_W2(ops[i$3]); }
  3470. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3471. { endOperation_finish(ops[i$4]); }
  3472. }
  3473. function endOperation_R1(op) {
  3474. var cm = op.cm, display = cm.display;
  3475. maybeClipScrollbars(cm);
  3476. if (op.updateMaxLine) { findMaxLine(cm); }
  3477. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3478. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3479. op.scrollToPos.to.line >= display.viewTo) ||
  3480. display.maxLineChanged && cm.options.lineWrapping;
  3481. op.update = op.mustUpdate &&
  3482. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3483. }
  3484. function endOperation_W1(op) {
  3485. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3486. }
  3487. function endOperation_R2(op) {
  3488. var cm = op.cm, display = cm.display;
  3489. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3490. op.barMeasure = measureForScrollbars(cm);
  3491. // If the max line changed since it was last measured, measure it,
  3492. // and ensure the document's width matches it.
  3493. // updateDisplay_W2 will use these properties to do the actual resizing
  3494. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3495. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3496. cm.display.sizerWidth = op.adjustWidthTo;
  3497. op.barMeasure.scrollWidth =
  3498. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3499. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3500. }
  3501. if (op.updatedDisplay || op.selectionChanged)
  3502. { op.preparedSelection = display.input.prepareSelection(); }
  3503. }
  3504. function endOperation_W2(op) {
  3505. var cm = op.cm;
  3506. if (op.adjustWidthTo != null) {
  3507. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3508. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3509. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3510. cm.display.maxLineChanged = false;
  3511. }
  3512. var takeFocus = op.focus && op.focus == activeElt();
  3513. if (op.preparedSelection)
  3514. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3515. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3516. { updateScrollbars(cm, op.barMeasure); }
  3517. if (op.updatedDisplay)
  3518. { setDocumentHeight(cm, op.barMeasure); }
  3519. if (op.selectionChanged) { restartBlink(cm); }
  3520. if (cm.state.focused && op.updateInput)
  3521. { cm.display.input.reset(op.typing); }
  3522. if (takeFocus) { ensureFocus(op.cm); }
  3523. }
  3524. function endOperation_finish(op) {
  3525. var cm = op.cm, display = cm.display, doc = cm.doc;
  3526. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3527. // Abort mouse wheel delta measurement, when scrolling explicitly
  3528. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3529. { display.wheelStartX = display.wheelStartY = null; }
  3530. // Propagate the scroll position to the actual DOM scroller
  3531. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3532. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3533. // If we need to scroll a specific position into view, do so.
  3534. if (op.scrollToPos) {
  3535. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3536. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3537. maybeScrollWindow(cm, rect);
  3538. }
  3539. // Fire events for markers that are hidden/unidden by editing or
  3540. // undoing
  3541. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3542. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3543. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3544. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3545. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3546. if (display.wrapper.offsetHeight)
  3547. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3548. // Fire change events, and delayed event handlers
  3549. if (op.changeObjs)
  3550. { signal(cm, "changes", cm, op.changeObjs); }
  3551. if (op.update)
  3552. { op.update.finish(); }
  3553. }
  3554. // Run the given function in an operation
  3555. function runInOp(cm, f) {
  3556. if (cm.curOp) { return f() }
  3557. startOperation(cm);
  3558. try { return f() }
  3559. finally { endOperation(cm); }
  3560. }
  3561. // Wraps a function in an operation. Returns the wrapped function.
  3562. function operation(cm, f) {
  3563. return function() {
  3564. if (cm.curOp) { return f.apply(cm, arguments) }
  3565. startOperation(cm);
  3566. try { return f.apply(cm, arguments) }
  3567. finally { endOperation(cm); }
  3568. }
  3569. }
  3570. // Used to add methods to editor and doc instances, wrapping them in
  3571. // operations.
  3572. function methodOp(f) {
  3573. return function() {
  3574. if (this.curOp) { return f.apply(this, arguments) }
  3575. startOperation(this);
  3576. try { return f.apply(this, arguments) }
  3577. finally { endOperation(this); }
  3578. }
  3579. }
  3580. function docMethodOp(f) {
  3581. return function() {
  3582. var cm = this.cm;
  3583. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3584. startOperation(cm);
  3585. try { return f.apply(this, arguments) }
  3586. finally { endOperation(cm); }
  3587. }
  3588. }
  3589. // HIGHLIGHT WORKER
  3590. function startWorker(cm, time) {
  3591. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3592. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3593. }
  3594. function highlightWorker(cm) {
  3595. var doc = cm.doc;
  3596. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3597. var end = +new Date + cm.options.workTime;
  3598. var context = getContextBefore(cm, doc.highlightFrontier);
  3599. var changedLines = [];
  3600. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3601. if (context.line >= cm.display.viewFrom) { // Visible
  3602. var oldStyles = line.styles;
  3603. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3604. var highlighted = highlightLine(cm, line, context, true);
  3605. if (resetState) { context.state = resetState; }
  3606. line.styles = highlighted.styles;
  3607. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3608. if (newCls) { line.styleClasses = newCls; }
  3609. else if (oldCls) { line.styleClasses = null; }
  3610. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3611. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3612. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3613. if (ischange) { changedLines.push(context.line); }
  3614. line.stateAfter = context.save();
  3615. context.nextLine();
  3616. } else {
  3617. if (line.text.length <= cm.options.maxHighlightLength)
  3618. { processLine(cm, line.text, context); }
  3619. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3620. context.nextLine();
  3621. }
  3622. if (+new Date > end) {
  3623. startWorker(cm, cm.options.workDelay);
  3624. return true
  3625. }
  3626. });
  3627. doc.highlightFrontier = context.line;
  3628. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3629. if (changedLines.length) { runInOp(cm, function () {
  3630. for (var i = 0; i < changedLines.length; i++)
  3631. { regLineChange(cm, changedLines[i], "text"); }
  3632. }); }
  3633. }
  3634. // DISPLAY DRAWING
  3635. var DisplayUpdate = function(cm, viewport, force) {
  3636. var display = cm.display;
  3637. this.viewport = viewport;
  3638. // Store some values that we'll need later (but don't want to force a relayout for)
  3639. this.visible = visibleLines(display, cm.doc, viewport);
  3640. this.editorIsHidden = !display.wrapper.offsetWidth;
  3641. this.wrapperHeight = display.wrapper.clientHeight;
  3642. this.wrapperWidth = display.wrapper.clientWidth;
  3643. this.oldDisplayWidth = displayWidth(cm);
  3644. this.force = force;
  3645. this.dims = getDimensions(cm);
  3646. this.events = [];
  3647. };
  3648. DisplayUpdate.prototype.signal = function (emitter, type) {
  3649. if (hasHandler(emitter, type))
  3650. { this.events.push(arguments); }
  3651. };
  3652. DisplayUpdate.prototype.finish = function () {
  3653. for (var i = 0; i < this.events.length; i++)
  3654. { signal.apply(null, this.events[i]); }
  3655. };
  3656. function maybeClipScrollbars(cm) {
  3657. var display = cm.display;
  3658. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3659. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3660. display.heightForcer.style.height = scrollGap(cm) + "px";
  3661. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3662. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3663. display.scrollbarsClipped = true;
  3664. }
  3665. }
  3666. function selectionSnapshot(cm) {
  3667. if (cm.hasFocus()) { return null }
  3668. var active = activeElt();
  3669. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3670. var result = {activeElt: active};
  3671. if (window.getSelection) {
  3672. var sel = window.getSelection();
  3673. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3674. result.anchorNode = sel.anchorNode;
  3675. result.anchorOffset = sel.anchorOffset;
  3676. result.focusNode = sel.focusNode;
  3677. result.focusOffset = sel.focusOffset;
  3678. }
  3679. }
  3680. return result
  3681. }
  3682. function restoreSelection(snapshot) {
  3683. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3684. snapshot.activeElt.focus();
  3685. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  3686. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3687. var sel = window.getSelection(), range = document.createRange();
  3688. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3689. range.collapse(false);
  3690. sel.removeAllRanges();
  3691. sel.addRange(range);
  3692. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3693. }
  3694. }
  3695. // Does the actual updating of the line display. Bails out
  3696. // (returning false) when there is nothing to be done and forced is
  3697. // false.
  3698. function updateDisplayIfNeeded(cm, update) {
  3699. var display = cm.display, doc = cm.doc;
  3700. if (update.editorIsHidden) {
  3701. resetView(cm);
  3702. return false
  3703. }
  3704. // Bail out if the visible area is already rendered and nothing changed.
  3705. if (!update.force &&
  3706. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3707. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3708. display.renderedView == display.view && countDirtyView(cm) == 0)
  3709. { return false }
  3710. if (maybeUpdateLineNumberWidth(cm)) {
  3711. resetView(cm);
  3712. update.dims = getDimensions(cm);
  3713. }
  3714. // Compute a suitable new viewport (from & to)
  3715. var end = doc.first + doc.size;
  3716. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3717. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3718. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3719. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3720. if (sawCollapsedSpans) {
  3721. from = visualLineNo(cm.doc, from);
  3722. to = visualLineEndNo(cm.doc, to);
  3723. }
  3724. var different = from != display.viewFrom || to != display.viewTo ||
  3725. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3726. adjustView(cm, from, to);
  3727. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3728. // Position the mover div to align with the current scroll position
  3729. cm.display.mover.style.top = display.viewOffset + "px";
  3730. var toUpdate = countDirtyView(cm);
  3731. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3732. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3733. { return false }
  3734. // For big changes, we hide the enclosing element during the
  3735. // update, since that speeds up the operations on most browsers.
  3736. var selSnapshot = selectionSnapshot(cm);
  3737. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3738. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3739. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3740. display.renderedView = display.view;
  3741. // There might have been a widget with a focused element that got
  3742. // hidden or updated, if so re-focus it.
  3743. restoreSelection(selSnapshot);
  3744. // Prevent selection and cursors from interfering with the scroll
  3745. // width and height.
  3746. removeChildren(display.cursorDiv);
  3747. removeChildren(display.selectionDiv);
  3748. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3749. if (different) {
  3750. display.lastWrapHeight = update.wrapperHeight;
  3751. display.lastWrapWidth = update.wrapperWidth;
  3752. startWorker(cm, 400);
  3753. }
  3754. display.updateLineNumbers = null;
  3755. return true
  3756. }
  3757. function postUpdateDisplay(cm, update) {
  3758. var viewport = update.viewport;
  3759. for (var first = true;; first = false) {
  3760. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3761. // Clip forced viewport to actual scrollable area.
  3762. if (viewport && viewport.top != null)
  3763. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3764. // Updated line heights might result in the drawn area not
  3765. // actually covering the viewport. Keep looping until it does.
  3766. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3767. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3768. { break }
  3769. } else if (first) {
  3770. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3771. }
  3772. if (!updateDisplayIfNeeded(cm, update)) { break }
  3773. updateHeightsInViewport(cm);
  3774. var barMeasure = measureForScrollbars(cm);
  3775. updateSelection(cm);
  3776. updateScrollbars(cm, barMeasure);
  3777. setDocumentHeight(cm, barMeasure);
  3778. update.force = false;
  3779. }
  3780. update.signal(cm, "update", cm);
  3781. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3782. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3783. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3784. }
  3785. }
  3786. function updateDisplaySimple(cm, viewport) {
  3787. var update = new DisplayUpdate(cm, viewport);
  3788. if (updateDisplayIfNeeded(cm, update)) {
  3789. updateHeightsInViewport(cm);
  3790. postUpdateDisplay(cm, update);
  3791. var barMeasure = measureForScrollbars(cm);
  3792. updateSelection(cm);
  3793. updateScrollbars(cm, barMeasure);
  3794. setDocumentHeight(cm, barMeasure);
  3795. update.finish();
  3796. }
  3797. }
  3798. // Sync the actual display DOM structure with display.view, removing
  3799. // nodes for lines that are no longer in view, and creating the ones
  3800. // that are not there yet, and updating the ones that are out of
  3801. // date.
  3802. function patchDisplay(cm, updateNumbersFrom, dims) {
  3803. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3804. var container = display.lineDiv, cur = container.firstChild;
  3805. function rm(node) {
  3806. var next = node.nextSibling;
  3807. // Works around a throw-scroll bug in OS X Webkit
  3808. if (webkit && mac && cm.display.currentWheelTarget == node)
  3809. { node.style.display = "none"; }
  3810. else
  3811. { node.parentNode.removeChild(node); }
  3812. return next
  3813. }
  3814. var view = display.view, lineN = display.viewFrom;
  3815. // Loop over the elements in the view, syncing cur (the DOM nodes
  3816. // in display.lineDiv) with the view as we go.
  3817. for (var i = 0; i < view.length; i++) {
  3818. var lineView = view[i];
  3819. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3820. var node = buildLineElement(cm, lineView, lineN, dims);
  3821. container.insertBefore(node, cur);
  3822. } else { // Already drawn
  3823. while (cur != lineView.node) { cur = rm(cur); }
  3824. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3825. updateNumbersFrom <= lineN && lineView.lineNumber;
  3826. if (lineView.changes) {
  3827. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3828. updateLineForChanges(cm, lineView, lineN, dims);
  3829. }
  3830. if (updateNumber) {
  3831. removeChildren(lineView.lineNumber);
  3832. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3833. }
  3834. cur = lineView.node.nextSibling;
  3835. }
  3836. lineN += lineView.size;
  3837. }
  3838. while (cur) { cur = rm(cur); }
  3839. }
  3840. function updateGutterSpace(display) {
  3841. var width = display.gutters.offsetWidth;
  3842. display.sizer.style.marginLeft = width + "px";
  3843. }
  3844. function setDocumentHeight(cm, measure) {
  3845. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3846. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3847. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3848. }
  3849. // Re-align line numbers and gutter marks to compensate for
  3850. // horizontal scrolling.
  3851. function alignHorizontally(cm) {
  3852. var display = cm.display, view = display.view;
  3853. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3854. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3855. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3856. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3857. if (cm.options.fixedGutter) {
  3858. if (view[i].gutter)
  3859. { view[i].gutter.style.left = left; }
  3860. if (view[i].gutterBackground)
  3861. { view[i].gutterBackground.style.left = left; }
  3862. }
  3863. var align = view[i].alignable;
  3864. if (align) { for (var j = 0; j < align.length; j++)
  3865. { align[j].style.left = left; } }
  3866. } }
  3867. if (cm.options.fixedGutter)
  3868. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3869. }
  3870. // Used to ensure that the line number gutter is still the right
  3871. // size for the current document size. Returns true when an update
  3872. // is needed.
  3873. function maybeUpdateLineNumberWidth(cm) {
  3874. if (!cm.options.lineNumbers) { return false }
  3875. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3876. if (last.length != display.lineNumChars) {
  3877. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3878. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3879. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3880. display.lineGutter.style.width = "";
  3881. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3882. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3883. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3884. display.lineGutter.style.width = display.lineNumWidth + "px";
  3885. updateGutterSpace(cm.display);
  3886. return true
  3887. }
  3888. return false
  3889. }
  3890. function getGutters(gutters, lineNumbers) {
  3891. var result = [], sawLineNumbers = false;
  3892. for (var i = 0; i < gutters.length; i++) {
  3893. var name = gutters[i], style = null;
  3894. if (typeof name != "string") { style = name.style; name = name.className; }
  3895. if (name == "CodeMirror-linenumbers") {
  3896. if (!lineNumbers) { continue }
  3897. else { sawLineNumbers = true; }
  3898. }
  3899. result.push({className: name, style: style});
  3900. }
  3901. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  3902. return result
  3903. }
  3904. // Rebuild the gutter elements, ensure the margin to the left of the
  3905. // code matches their width.
  3906. function renderGutters(display) {
  3907. var gutters = display.gutters, specs = display.gutterSpecs;
  3908. removeChildren(gutters);
  3909. display.lineGutter = null;
  3910. for (var i = 0; i < specs.length; ++i) {
  3911. var ref = specs[i];
  3912. var className = ref.className;
  3913. var style = ref.style;
  3914. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  3915. if (style) { gElt.style.cssText = style; }
  3916. if (className == "CodeMirror-linenumbers") {
  3917. display.lineGutter = gElt;
  3918. gElt.style.width = (display.lineNumWidth || 1) + "px";
  3919. }
  3920. }
  3921. gutters.style.display = specs.length ? "" : "none";
  3922. updateGutterSpace(display);
  3923. }
  3924. function updateGutters(cm) {
  3925. renderGutters(cm.display);
  3926. regChange(cm);
  3927. alignHorizontally(cm);
  3928. }
  3929. // The display handles the DOM integration, both for input reading
  3930. // and content drawing. It holds references to DOM nodes and
  3931. // display-related state.
  3932. function Display(place, doc, input, options) {
  3933. var d = this;
  3934. this.input = input;
  3935. // Covers bottom-right square when both scrollbars are present.
  3936. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  3937. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  3938. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  3939. // and h scrollbar is present.
  3940. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  3941. d.gutterFiller.setAttribute("cm-not-content", "true");
  3942. // Will contain the actual code, positioned to cover the viewport.
  3943. d.lineDiv = eltP("div", null, "CodeMirror-code");
  3944. // Elements are added to these to represent selection and cursors.
  3945. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  3946. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  3947. // A visibility: hidden element used to find the size of things.
  3948. d.measure = elt("div", null, "CodeMirror-measure");
  3949. // When lines outside of the viewport are measured, they are drawn in this.
  3950. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  3951. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  3952. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  3953. null, "position: relative; outline: none");
  3954. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  3955. // Moved around its parent to cover visible view.
  3956. d.mover = elt("div", [lines], null, "position: relative");
  3957. // Set to the height of the document, allowing scrolling.
  3958. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  3959. d.sizerWidth = null;
  3960. // Behavior of elts with overflow: auto and padding is
  3961. // inconsistent across browsers. This is used to ensure the
  3962. // scrollable area is big enough.
  3963. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  3964. // Will contain the gutters, if any.
  3965. d.gutters = elt("div", null, "CodeMirror-gutters");
  3966. d.lineGutter = null;
  3967. // Actual scrollable element.
  3968. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  3969. d.scroller.setAttribute("tabIndex", "-1");
  3970. // The element in which the editor lives.
  3971. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  3972. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  3973. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  3974. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  3975. if (place) {
  3976. if (place.appendChild) { place.appendChild(d.wrapper); }
  3977. else { place(d.wrapper); }
  3978. }
  3979. // Current rendered range (may be bigger than the view window).
  3980. d.viewFrom = d.viewTo = doc.first;
  3981. d.reportedViewFrom = d.reportedViewTo = doc.first;
  3982. // Information about the rendered lines.
  3983. d.view = [];
  3984. d.renderedView = null;
  3985. // Holds info about a single rendered line when it was rendered
  3986. // for measurement, while not in view.
  3987. d.externalMeasured = null;
  3988. // Empty space (in pixels) above the view
  3989. d.viewOffset = 0;
  3990. d.lastWrapHeight = d.lastWrapWidth = 0;
  3991. d.updateLineNumbers = null;
  3992. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  3993. d.scrollbarsClipped = false;
  3994. // Used to only resize the line number gutter when necessary (when
  3995. // the amount of lines crosses a boundary that makes its width change)
  3996. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  3997. // Set to true when a non-horizontal-scrolling line widget is
  3998. // added. As an optimization, line widget aligning is skipped when
  3999. // this is false.
  4000. d.alignWidgets = false;
  4001. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4002. // Tracks the maximum line length so that the horizontal scrollbar
  4003. // can be kept static when scrolling.
  4004. d.maxLine = null;
  4005. d.maxLineLength = 0;
  4006. d.maxLineChanged = false;
  4007. // Used for measuring wheel scrolling granularity
  4008. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4009. // True when shift is held down.
  4010. d.shift = false;
  4011. // Used to track whether anything happened since the context menu
  4012. // was opened.
  4013. d.selForContextMenu = null;
  4014. d.activeTouch = null;
  4015. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4016. renderGutters(d);
  4017. input.init(d);
  4018. }
  4019. // Since the delta values reported on mouse wheel events are
  4020. // unstandardized between browsers and even browser versions, and
  4021. // generally horribly unpredictable, this code starts by measuring
  4022. // the scroll effect that the first few mouse wheel events have,
  4023. // and, from that, detects the way it can convert deltas to pixel
  4024. // offsets afterwards.
  4025. //
  4026. // The reason we want to know the amount a wheel event will scroll
  4027. // is that it gives us a chance to update the display before the
  4028. // actual scrolling happens, reducing flickering.
  4029. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4030. // Fill in a browser-detected starting value on browsers where we
  4031. // know one. These don't have to be accurate -- the result of them
  4032. // being wrong would just be a slight flicker on the first wheel
  4033. // scroll (if it is large enough).
  4034. if (ie) { wheelPixelsPerUnit = -.53; }
  4035. else if (gecko) { wheelPixelsPerUnit = 15; }
  4036. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4037. else if (safari) { wheelPixelsPerUnit = -1/3; }
  4038. function wheelEventDelta(e) {
  4039. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4040. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4041. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4042. else if (dy == null) { dy = e.wheelDelta; }
  4043. return {x: dx, y: dy}
  4044. }
  4045. function wheelEventPixels(e) {
  4046. var delta = wheelEventDelta(e);
  4047. delta.x *= wheelPixelsPerUnit;
  4048. delta.y *= wheelPixelsPerUnit;
  4049. return delta
  4050. }
  4051. function onScrollWheel(cm, e) {
  4052. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4053. var display = cm.display, scroll = display.scroller;
  4054. // Quit if there's nothing to scroll here
  4055. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4056. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4057. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4058. // Webkit browsers on OS X abort momentum scrolls when the target
  4059. // of the scroll event is removed from the scrollable element.
  4060. // This hack (see related code in patchDisplay) makes sure the
  4061. // element is kept around.
  4062. if (dy && mac && webkit) {
  4063. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4064. for (var i = 0; i < view.length; i++) {
  4065. if (view[i].node == cur) {
  4066. cm.display.currentWheelTarget = cur;
  4067. break outer
  4068. }
  4069. }
  4070. }
  4071. }
  4072. // On some browsers, horizontal scrolling will cause redraws to
  4073. // happen before the gutter has been realigned, causing it to
  4074. // wriggle around in a most unseemly way. When we have an
  4075. // estimated pixels/delta value, we just handle horizontal
  4076. // scrolling entirely here. It'll be slightly off from native, but
  4077. // better than glitching out.
  4078. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4079. if (dy && canScrollY)
  4080. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  4081. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  4082. // Only prevent default scrolling if vertical scrolling is
  4083. // actually possible. Otherwise, it causes vertical scroll
  4084. // jitter on OSX trackpads when deltaX is small and deltaY
  4085. // is large (issue #3579)
  4086. if (!dy || (dy && canScrollY))
  4087. { e_preventDefault(e); }
  4088. display.wheelStartX = null; // Abort measurement, if in progress
  4089. return
  4090. }
  4091. // 'Project' the visible viewport to cover the area that is being
  4092. // scrolled into view (if we know enough to estimate it).
  4093. if (dy && wheelPixelsPerUnit != null) {
  4094. var pixels = dy * wheelPixelsPerUnit;
  4095. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4096. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4097. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4098. updateDisplaySimple(cm, {top: top, bottom: bot});
  4099. }
  4100. if (wheelSamples < 20) {
  4101. if (display.wheelStartX == null) {
  4102. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4103. display.wheelDX = dx; display.wheelDY = dy;
  4104. setTimeout(function () {
  4105. if (display.wheelStartX == null) { return }
  4106. var movedX = scroll.scrollLeft - display.wheelStartX;
  4107. var movedY = scroll.scrollTop - display.wheelStartY;
  4108. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4109. (movedX && display.wheelDX && movedX / display.wheelDX);
  4110. display.wheelStartX = display.wheelStartY = null;
  4111. if (!sample) { return }
  4112. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4113. ++wheelSamples;
  4114. }, 200);
  4115. } else {
  4116. display.wheelDX += dx; display.wheelDY += dy;
  4117. }
  4118. }
  4119. }
  4120. // Selection objects are immutable. A new one is created every time
  4121. // the selection changes. A selection is one or more non-overlapping
  4122. // (and non-touching) ranges, sorted, and an integer that indicates
  4123. // which one is the primary selection (the one that's scrolled into
  4124. // view, that getCursor returns, etc).
  4125. var Selection = function(ranges, primIndex) {
  4126. this.ranges = ranges;
  4127. this.primIndex = primIndex;
  4128. };
  4129. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4130. Selection.prototype.equals = function (other) {
  4131. if (other == this) { return true }
  4132. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4133. for (var i = 0; i < this.ranges.length; i++) {
  4134. var here = this.ranges[i], there = other.ranges[i];
  4135. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4136. }
  4137. return true
  4138. };
  4139. Selection.prototype.deepCopy = function () {
  4140. var out = [];
  4141. for (var i = 0; i < this.ranges.length; i++)
  4142. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4143. return new Selection(out, this.primIndex)
  4144. };
  4145. Selection.prototype.somethingSelected = function () {
  4146. for (var i = 0; i < this.ranges.length; i++)
  4147. { if (!this.ranges[i].empty()) { return true } }
  4148. return false
  4149. };
  4150. Selection.prototype.contains = function (pos, end) {
  4151. if (!end) { end = pos; }
  4152. for (var i = 0; i < this.ranges.length; i++) {
  4153. var range = this.ranges[i];
  4154. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4155. { return i }
  4156. }
  4157. return -1
  4158. };
  4159. var Range = function(anchor, head) {
  4160. this.anchor = anchor; this.head = head;
  4161. };
  4162. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4163. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4164. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4165. // Take an unsorted, potentially overlapping set of ranges, and
  4166. // build a selection out of it. 'Consumes' ranges array (modifying
  4167. // it).
  4168. function normalizeSelection(cm, ranges, primIndex) {
  4169. var mayTouch = cm && cm.options.selectionsMayTouch;
  4170. var prim = ranges[primIndex];
  4171. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4172. primIndex = indexOf(ranges, prim);
  4173. for (var i = 1; i < ranges.length; i++) {
  4174. var cur = ranges[i], prev = ranges[i - 1];
  4175. var diff = cmp(prev.to(), cur.from());
  4176. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4177. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4178. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4179. if (i <= primIndex) { --primIndex; }
  4180. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4181. }
  4182. }
  4183. return new Selection(ranges, primIndex)
  4184. }
  4185. function simpleSelection(anchor, head) {
  4186. return new Selection([new Range(anchor, head || anchor)], 0)
  4187. }
  4188. // Compute the position of the end of a change (its 'to' property
  4189. // refers to the pre-change end).
  4190. function changeEnd(change) {
  4191. if (!change.text) { return change.to }
  4192. return Pos(change.from.line + change.text.length - 1,
  4193. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4194. }
  4195. // Adjust a position to refer to the post-change position of the
  4196. // same text, or the end of the change if the change covers it.
  4197. function adjustForChange(pos, change) {
  4198. if (cmp(pos, change.from) < 0) { return pos }
  4199. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4200. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4201. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4202. return Pos(line, ch)
  4203. }
  4204. function computeSelAfterChange(doc, change) {
  4205. var out = [];
  4206. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4207. var range = doc.sel.ranges[i];
  4208. out.push(new Range(adjustForChange(range.anchor, change),
  4209. adjustForChange(range.head, change)));
  4210. }
  4211. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4212. }
  4213. function offsetPos(pos, old, nw) {
  4214. if (pos.line == old.line)
  4215. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4216. else
  4217. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4218. }
  4219. // Used by replaceSelections to allow moving the selection to the
  4220. // start or around the replaced test. Hint may be "start" or "around".
  4221. function computeReplacedSel(doc, changes, hint) {
  4222. var out = [];
  4223. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4224. for (var i = 0; i < changes.length; i++) {
  4225. var change = changes[i];
  4226. var from = offsetPos(change.from, oldPrev, newPrev);
  4227. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4228. oldPrev = change.to;
  4229. newPrev = to;
  4230. if (hint == "around") {
  4231. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4232. out[i] = new Range(inv ? to : from, inv ? from : to);
  4233. } else {
  4234. out[i] = new Range(from, from);
  4235. }
  4236. }
  4237. return new Selection(out, doc.sel.primIndex)
  4238. }
  4239. // Used to get the editor into a consistent state again when options change.
  4240. function loadMode(cm) {
  4241. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4242. resetModeState(cm);
  4243. }
  4244. function resetModeState(cm) {
  4245. cm.doc.iter(function (line) {
  4246. if (line.stateAfter) { line.stateAfter = null; }
  4247. if (line.styles) { line.styles = null; }
  4248. });
  4249. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4250. startWorker(cm, 100);
  4251. cm.state.modeGen++;
  4252. if (cm.curOp) { regChange(cm); }
  4253. }
  4254. // DOCUMENT DATA STRUCTURE
  4255. // By default, updates that start and end at the beginning of a line
  4256. // are treated specially, in order to make the association of line
  4257. // widgets and marker elements with the text behave more intuitive.
  4258. function isWholeLineUpdate(doc, change) {
  4259. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4260. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4261. }
  4262. // Perform a change on the document data structure.
  4263. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4264. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4265. function update(line, text, spans) {
  4266. updateLine(line, text, spans, estimateHeight);
  4267. signalLater(line, "change", line, change);
  4268. }
  4269. function linesFor(start, end) {
  4270. var result = [];
  4271. for (var i = start; i < end; ++i)
  4272. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4273. return result
  4274. }
  4275. var from = change.from, to = change.to, text = change.text;
  4276. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4277. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4278. // Adjust the line structure
  4279. if (change.full) {
  4280. doc.insert(0, linesFor(0, text.length));
  4281. doc.remove(text.length, doc.size - text.length);
  4282. } else if (isWholeLineUpdate(doc, change)) {
  4283. // This is a whole-line replace. Treated specially to make
  4284. // sure line objects move the way they are supposed to.
  4285. var added = linesFor(0, text.length - 1);
  4286. update(lastLine, lastLine.text, lastSpans);
  4287. if (nlines) { doc.remove(from.line, nlines); }
  4288. if (added.length) { doc.insert(from.line, added); }
  4289. } else if (firstLine == lastLine) {
  4290. if (text.length == 1) {
  4291. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4292. } else {
  4293. var added$1 = linesFor(1, text.length - 1);
  4294. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4295. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4296. doc.insert(from.line + 1, added$1);
  4297. }
  4298. } else if (text.length == 1) {
  4299. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4300. doc.remove(from.line + 1, nlines);
  4301. } else {
  4302. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4303. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4304. var added$2 = linesFor(1, text.length - 1);
  4305. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4306. doc.insert(from.line + 1, added$2);
  4307. }
  4308. signalLater(doc, "change", doc, change);
  4309. }
  4310. // Call f for all linked documents.
  4311. function linkedDocs(doc, f, sharedHistOnly) {
  4312. function propagate(doc, skip, sharedHist) {
  4313. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4314. var rel = doc.linked[i];
  4315. if (rel.doc == skip) { continue }
  4316. var shared = sharedHist && rel.sharedHist;
  4317. if (sharedHistOnly && !shared) { continue }
  4318. f(rel.doc, shared);
  4319. propagate(rel.doc, doc, shared);
  4320. } }
  4321. }
  4322. propagate(doc, null, true);
  4323. }
  4324. // Attach a document to an editor.
  4325. function attachDoc(cm, doc) {
  4326. if (doc.cm) { throw new Error("This document is already in use.") }
  4327. cm.doc = doc;
  4328. doc.cm = cm;
  4329. estimateLineHeights(cm);
  4330. loadMode(cm);
  4331. setDirectionClass(cm);
  4332. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4333. cm.options.mode = doc.modeOption;
  4334. regChange(cm);
  4335. }
  4336. function setDirectionClass(cm) {
  4337. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4338. }
  4339. function directionChanged(cm) {
  4340. runInOp(cm, function () {
  4341. setDirectionClass(cm);
  4342. regChange(cm);
  4343. });
  4344. }
  4345. function History(startGen) {
  4346. // Arrays of change events and selections. Doing something adds an
  4347. // event to done and clears undo. Undoing moves events from done
  4348. // to undone, redoing moves them in the other direction.
  4349. this.done = []; this.undone = [];
  4350. this.undoDepth = Infinity;
  4351. // Used to track when changes can be merged into a single undo
  4352. // event
  4353. this.lastModTime = this.lastSelTime = 0;
  4354. this.lastOp = this.lastSelOp = null;
  4355. this.lastOrigin = this.lastSelOrigin = null;
  4356. // Used by the isClean() method
  4357. this.generation = this.maxGeneration = startGen || 1;
  4358. }
  4359. // Create a history change event from an updateDoc-style change
  4360. // object.
  4361. function historyChangeFromChange(doc, change) {
  4362. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4363. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4364. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4365. return histChange
  4366. }
  4367. // Pop all selection events off the end of a history array. Stop at
  4368. // a change event.
  4369. function clearSelectionEvents(array) {
  4370. while (array.length) {
  4371. var last = lst(array);
  4372. if (last.ranges) { array.pop(); }
  4373. else { break }
  4374. }
  4375. }
  4376. // Find the top change event in the history. Pop off selection
  4377. // events that are in the way.
  4378. function lastChangeEvent(hist, force) {
  4379. if (force) {
  4380. clearSelectionEvents(hist.done);
  4381. return lst(hist.done)
  4382. } else if (hist.done.length && !lst(hist.done).ranges) {
  4383. return lst(hist.done)
  4384. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4385. hist.done.pop();
  4386. return lst(hist.done)
  4387. }
  4388. }
  4389. // Register a change in the history. Merges changes that are within
  4390. // a single operation, or are close together with an origin that
  4391. // allows merging (starting with "+") into a single event.
  4392. function addChangeToHistory(doc, change, selAfter, opId) {
  4393. var hist = doc.history;
  4394. hist.undone.length = 0;
  4395. var time = +new Date, cur;
  4396. var last;
  4397. if ((hist.lastOp == opId ||
  4398. hist.lastOrigin == change.origin && change.origin &&
  4399. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4400. change.origin.charAt(0) == "*")) &&
  4401. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4402. // Merge this change into the last event
  4403. last = lst(cur.changes);
  4404. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4405. // Optimized case for simple insertion -- don't want to add
  4406. // new changesets for every character typed
  4407. last.to = changeEnd(change);
  4408. } else {
  4409. // Add new sub-event
  4410. cur.changes.push(historyChangeFromChange(doc, change));
  4411. }
  4412. } else {
  4413. // Can not be merged, start a new event.
  4414. var before = lst(hist.done);
  4415. if (!before || !before.ranges)
  4416. { pushSelectionToHistory(doc.sel, hist.done); }
  4417. cur = {changes: [historyChangeFromChange(doc, change)],
  4418. generation: hist.generation};
  4419. hist.done.push(cur);
  4420. while (hist.done.length > hist.undoDepth) {
  4421. hist.done.shift();
  4422. if (!hist.done[0].ranges) { hist.done.shift(); }
  4423. }
  4424. }
  4425. hist.done.push(selAfter);
  4426. hist.generation = ++hist.maxGeneration;
  4427. hist.lastModTime = hist.lastSelTime = time;
  4428. hist.lastOp = hist.lastSelOp = opId;
  4429. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4430. if (!last) { signal(doc, "historyAdded"); }
  4431. }
  4432. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4433. var ch = origin.charAt(0);
  4434. return ch == "*" ||
  4435. ch == "+" &&
  4436. prev.ranges.length == sel.ranges.length &&
  4437. prev.somethingSelected() == sel.somethingSelected() &&
  4438. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4439. }
  4440. // Called whenever the selection changes, sets the new selection as
  4441. // the pending selection in the history, and pushes the old pending
  4442. // selection into the 'done' array when it was significantly
  4443. // different (in number of selected ranges, emptiness, or time).
  4444. function addSelectionToHistory(doc, sel, opId, options) {
  4445. var hist = doc.history, origin = options && options.origin;
  4446. // A new event is started when the previous origin does not match
  4447. // the current, or the origins don't allow matching. Origins
  4448. // starting with * are always merged, those starting with + are
  4449. // merged when similar and close together in time.
  4450. if (opId == hist.lastSelOp ||
  4451. (origin && hist.lastSelOrigin == origin &&
  4452. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4453. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4454. { hist.done[hist.done.length - 1] = sel; }
  4455. else
  4456. { pushSelectionToHistory(sel, hist.done); }
  4457. hist.lastSelTime = +new Date;
  4458. hist.lastSelOrigin = origin;
  4459. hist.lastSelOp = opId;
  4460. if (options && options.clearRedo !== false)
  4461. { clearSelectionEvents(hist.undone); }
  4462. }
  4463. function pushSelectionToHistory(sel, dest) {
  4464. var top = lst(dest);
  4465. if (!(top && top.ranges && top.equals(sel)))
  4466. { dest.push(sel); }
  4467. }
  4468. // Used to store marked span information in the history.
  4469. function attachLocalSpans(doc, change, from, to) {
  4470. var existing = change["spans_" + doc.id], n = 0;
  4471. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4472. if (line.markedSpans)
  4473. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4474. ++n;
  4475. });
  4476. }
  4477. // When un/re-doing restores text containing marked spans, those
  4478. // that have been explicitly cleared should not be restored.
  4479. function removeClearedSpans(spans) {
  4480. if (!spans) { return null }
  4481. var out;
  4482. for (var i = 0; i < spans.length; ++i) {
  4483. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4484. else if (out) { out.push(spans[i]); }
  4485. }
  4486. return !out ? spans : out.length ? out : null
  4487. }
  4488. // Retrieve and filter the old marked spans stored in a change event.
  4489. function getOldSpans(doc, change) {
  4490. var found = change["spans_" + doc.id];
  4491. if (!found) { return null }
  4492. var nw = [];
  4493. for (var i = 0; i < change.text.length; ++i)
  4494. { nw.push(removeClearedSpans(found[i])); }
  4495. return nw
  4496. }
  4497. // Used for un/re-doing changes from the history. Combines the
  4498. // result of computing the existing spans with the set of spans that
  4499. // existed in the history (so that deleting around a span and then
  4500. // undoing brings back the span).
  4501. function mergeOldSpans(doc, change) {
  4502. var old = getOldSpans(doc, change);
  4503. var stretched = stretchSpansOverChange(doc, change);
  4504. if (!old) { return stretched }
  4505. if (!stretched) { return old }
  4506. for (var i = 0; i < old.length; ++i) {
  4507. var oldCur = old[i], stretchCur = stretched[i];
  4508. if (oldCur && stretchCur) {
  4509. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4510. var span = stretchCur[j];
  4511. for (var k = 0; k < oldCur.length; ++k)
  4512. { if (oldCur[k].marker == span.marker) { continue spans } }
  4513. oldCur.push(span);
  4514. }
  4515. } else if (stretchCur) {
  4516. old[i] = stretchCur;
  4517. }
  4518. }
  4519. return old
  4520. }
  4521. // Used both to provide a JSON-safe object in .getHistory, and, when
  4522. // detaching a document, to split the history in two
  4523. function copyHistoryArray(events, newGroup, instantiateSel) {
  4524. var copy = [];
  4525. for (var i = 0; i < events.length; ++i) {
  4526. var event = events[i];
  4527. if (event.ranges) {
  4528. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4529. continue
  4530. }
  4531. var changes = event.changes, newChanges = [];
  4532. copy.push({changes: newChanges});
  4533. for (var j = 0; j < changes.length; ++j) {
  4534. var change = changes[j], m = (void 0);
  4535. newChanges.push({from: change.from, to: change.to, text: change.text});
  4536. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4537. if (indexOf(newGroup, Number(m[1])) > -1) {
  4538. lst(newChanges)[prop] = change[prop];
  4539. delete change[prop];
  4540. }
  4541. } } }
  4542. }
  4543. }
  4544. return copy
  4545. }
  4546. // The 'scroll' parameter given to many of these indicated whether
  4547. // the new cursor position should be scrolled into view after
  4548. // modifying the selection.
  4549. // If shift is held or the extend flag is set, extends a range to
  4550. // include a given position (and optionally a second position).
  4551. // Otherwise, simply returns the range between the given positions.
  4552. // Used for cursor motion and such.
  4553. function extendRange(range, head, other, extend) {
  4554. if (extend) {
  4555. var anchor = range.anchor;
  4556. if (other) {
  4557. var posBefore = cmp(head, anchor) < 0;
  4558. if (posBefore != (cmp(other, anchor) < 0)) {
  4559. anchor = head;
  4560. head = other;
  4561. } else if (posBefore != (cmp(head, other) < 0)) {
  4562. head = other;
  4563. }
  4564. }
  4565. return new Range(anchor, head)
  4566. } else {
  4567. return new Range(other || head, head)
  4568. }
  4569. }
  4570. // Extend the primary selection range, discard the rest.
  4571. function extendSelection(doc, head, other, options, extend) {
  4572. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4573. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4574. }
  4575. // Extend all selections (pos is an array of selections with length
  4576. // equal the number of selections)
  4577. function extendSelections(doc, heads, options) {
  4578. var out = [];
  4579. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4580. for (var i = 0; i < doc.sel.ranges.length; i++)
  4581. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4582. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4583. setSelection(doc, newSel, options);
  4584. }
  4585. // Updates a single range in the selection.
  4586. function replaceOneSelection(doc, i, range, options) {
  4587. var ranges = doc.sel.ranges.slice(0);
  4588. ranges[i] = range;
  4589. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4590. }
  4591. // Reset the selection to a single range.
  4592. function setSimpleSelection(doc, anchor, head, options) {
  4593. setSelection(doc, simpleSelection(anchor, head), options);
  4594. }
  4595. // Give beforeSelectionChange handlers a change to influence a
  4596. // selection update.
  4597. function filterSelectionChange(doc, sel, options) {
  4598. var obj = {
  4599. ranges: sel.ranges,
  4600. update: function(ranges) {
  4601. this.ranges = [];
  4602. for (var i = 0; i < ranges.length; i++)
  4603. { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4604. clipPos(doc, ranges[i].head)); }
  4605. },
  4606. origin: options && options.origin
  4607. };
  4608. signal(doc, "beforeSelectionChange", doc, obj);
  4609. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4610. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4611. else { return sel }
  4612. }
  4613. function setSelectionReplaceHistory(doc, sel, options) {
  4614. var done = doc.history.done, last = lst(done);
  4615. if (last && last.ranges) {
  4616. done[done.length - 1] = sel;
  4617. setSelectionNoUndo(doc, sel, options);
  4618. } else {
  4619. setSelection(doc, sel, options);
  4620. }
  4621. }
  4622. // Set a new selection.
  4623. function setSelection(doc, sel, options) {
  4624. setSelectionNoUndo(doc, sel, options);
  4625. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4626. }
  4627. function setSelectionNoUndo(doc, sel, options) {
  4628. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4629. { sel = filterSelectionChange(doc, sel, options); }
  4630. var bias = options && options.bias ||
  4631. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4632. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4633. if (!(options && options.scroll === false) && doc.cm)
  4634. { ensureCursorVisible(doc.cm); }
  4635. }
  4636. function setSelectionInner(doc, sel) {
  4637. if (sel.equals(doc.sel)) { return }
  4638. doc.sel = sel;
  4639. if (doc.cm) {
  4640. doc.cm.curOp.updateInput = 1;
  4641. doc.cm.curOp.selectionChanged = true;
  4642. signalCursorActivity(doc.cm);
  4643. }
  4644. signalLater(doc, "cursorActivity", doc);
  4645. }
  4646. // Verify that the selection does not partially select any atomic
  4647. // marked ranges.
  4648. function reCheckSelection(doc) {
  4649. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4650. }
  4651. // Return a selection that does not partially select any atomic
  4652. // ranges.
  4653. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4654. var out;
  4655. for (var i = 0; i < sel.ranges.length; i++) {
  4656. var range = sel.ranges[i];
  4657. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4658. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4659. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4660. if (out || newAnchor != range.anchor || newHead != range.head) {
  4661. if (!out) { out = sel.ranges.slice(0, i); }
  4662. out[i] = new Range(newAnchor, newHead);
  4663. }
  4664. }
  4665. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4666. }
  4667. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4668. var line = getLine(doc, pos.line);
  4669. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4670. var sp = line.markedSpans[i], m = sp.marker;
  4671. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  4672. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  4673. // is with selectLeft/Right
  4674. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  4675. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  4676. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4677. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4678. if (mayClear) {
  4679. signal(m, "beforeCursorEnter");
  4680. if (m.explicitlyCleared) {
  4681. if (!line.markedSpans) { break }
  4682. else {--i; continue}
  4683. }
  4684. }
  4685. if (!m.atomic) { continue }
  4686. if (oldPos) {
  4687. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4688. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  4689. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4690. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4691. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4692. }
  4693. var far = m.find(dir < 0 ? -1 : 1);
  4694. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  4695. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4696. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4697. }
  4698. } }
  4699. return pos
  4700. }
  4701. // Ensure a given position is not inside an atomic range.
  4702. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4703. var dir = bias || 1;
  4704. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4705. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4706. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4707. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4708. if (!found) {
  4709. doc.cantEdit = true;
  4710. return Pos(doc.first, 0)
  4711. }
  4712. return found
  4713. }
  4714. function movePos(doc, pos, dir, line) {
  4715. if (dir < 0 && pos.ch == 0) {
  4716. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4717. else { return null }
  4718. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4719. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4720. else { return null }
  4721. } else {
  4722. return new Pos(pos.line, pos.ch + dir)
  4723. }
  4724. }
  4725. function selectAll(cm) {
  4726. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4727. }
  4728. // UPDATING
  4729. // Allow "beforeChange" event handlers to influence a change
  4730. function filterChange(doc, change, update) {
  4731. var obj = {
  4732. canceled: false,
  4733. from: change.from,
  4734. to: change.to,
  4735. text: change.text,
  4736. origin: change.origin,
  4737. cancel: function () { return obj.canceled = true; }
  4738. };
  4739. if (update) { obj.update = function (from, to, text, origin) {
  4740. if (from) { obj.from = clipPos(doc, from); }
  4741. if (to) { obj.to = clipPos(doc, to); }
  4742. if (text) { obj.text = text; }
  4743. if (origin !== undefined) { obj.origin = origin; }
  4744. }; }
  4745. signal(doc, "beforeChange", doc, obj);
  4746. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4747. if (obj.canceled) {
  4748. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4749. return null
  4750. }
  4751. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4752. }
  4753. // Apply a change to a document, and add it to the document's
  4754. // history, and propagating it to all linked documents.
  4755. function makeChange(doc, change, ignoreReadOnly) {
  4756. if (doc.cm) {
  4757. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4758. if (doc.cm.state.suppressEdits) { return }
  4759. }
  4760. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4761. change = filterChange(doc, change, true);
  4762. if (!change) { return }
  4763. }
  4764. // Possibly split or suppress the update based on the presence
  4765. // of read-only spans in its range.
  4766. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4767. if (split) {
  4768. for (var i = split.length - 1; i >= 0; --i)
  4769. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4770. } else {
  4771. makeChangeInner(doc, change);
  4772. }
  4773. }
  4774. function makeChangeInner(doc, change) {
  4775. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4776. var selAfter = computeSelAfterChange(doc, change);
  4777. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4778. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4779. var rebased = [];
  4780. linkedDocs(doc, function (doc, sharedHist) {
  4781. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4782. rebaseHist(doc.history, change);
  4783. rebased.push(doc.history);
  4784. }
  4785. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4786. });
  4787. }
  4788. // Revert a change stored in a document's history.
  4789. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4790. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4791. if (suppress && !allowSelectionOnly) { return }
  4792. var hist = doc.history, event, selAfter = doc.sel;
  4793. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4794. // Verify that there is a useable event (so that ctrl-z won't
  4795. // needlessly clear selection events)
  4796. var i = 0;
  4797. for (; i < source.length; i++) {
  4798. event = source[i];
  4799. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4800. { break }
  4801. }
  4802. if (i == source.length) { return }
  4803. hist.lastOrigin = hist.lastSelOrigin = null;
  4804. for (;;) {
  4805. event = source.pop();
  4806. if (event.ranges) {
  4807. pushSelectionToHistory(event, dest);
  4808. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4809. setSelection(doc, event, {clearRedo: false});
  4810. return
  4811. }
  4812. selAfter = event;
  4813. } else if (suppress) {
  4814. source.push(event);
  4815. return
  4816. } else { break }
  4817. }
  4818. // Build up a reverse change object to add to the opposite history
  4819. // stack (redo when undoing, and vice versa).
  4820. var antiChanges = [];
  4821. pushSelectionToHistory(selAfter, dest);
  4822. dest.push({changes: antiChanges, generation: hist.generation});
  4823. hist.generation = event.generation || ++hist.maxGeneration;
  4824. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4825. var loop = function ( i ) {
  4826. var change = event.changes[i];
  4827. change.origin = type;
  4828. if (filter && !filterChange(doc, change, false)) {
  4829. source.length = 0;
  4830. return {}
  4831. }
  4832. antiChanges.push(historyChangeFromChange(doc, change));
  4833. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4834. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4835. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4836. var rebased = [];
  4837. // Propagate to the linked documents
  4838. linkedDocs(doc, function (doc, sharedHist) {
  4839. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4840. rebaseHist(doc.history, change);
  4841. rebased.push(doc.history);
  4842. }
  4843. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4844. });
  4845. };
  4846. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4847. var returned = loop( i$1 );
  4848. if ( returned ) return returned.v;
  4849. }
  4850. }
  4851. // Sub-views need their line numbers shifted when text is added
  4852. // above or below them in the parent document.
  4853. function shiftDoc(doc, distance) {
  4854. if (distance == 0) { return }
  4855. doc.first += distance;
  4856. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4857. Pos(range.anchor.line + distance, range.anchor.ch),
  4858. Pos(range.head.line + distance, range.head.ch)
  4859. ); }), doc.sel.primIndex);
  4860. if (doc.cm) {
  4861. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4862. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4863. { regLineChange(doc.cm, l, "gutter"); }
  4864. }
  4865. }
  4866. // More lower-level change function, handling only a single document
  4867. // (not linked ones).
  4868. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4869. if (doc.cm && !doc.cm.curOp)
  4870. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4871. if (change.to.line < doc.first) {
  4872. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4873. return
  4874. }
  4875. if (change.from.line > doc.lastLine()) { return }
  4876. // Clip the change to the size of this doc
  4877. if (change.from.line < doc.first) {
  4878. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4879. shiftDoc(doc, shift);
  4880. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4881. text: [lst(change.text)], origin: change.origin};
  4882. }
  4883. var last = doc.lastLine();
  4884. if (change.to.line > last) {
  4885. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4886. text: [change.text[0]], origin: change.origin};
  4887. }
  4888. change.removed = getBetween(doc, change.from, change.to);
  4889. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4890. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4891. else { updateDoc(doc, change, spans); }
  4892. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4893. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  4894. { doc.cantEdit = false; }
  4895. }
  4896. // Handle the interaction of a change to a document with the editor
  4897. // that this document is part of.
  4898. function makeChangeSingleDocInEditor(cm, change, spans) {
  4899. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4900. var recomputeMaxLength = false, checkWidthStart = from.line;
  4901. if (!cm.options.lineWrapping) {
  4902. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4903. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4904. if (line == display.maxLine) {
  4905. recomputeMaxLength = true;
  4906. return true
  4907. }
  4908. });
  4909. }
  4910. if (doc.sel.contains(change.from, change.to) > -1)
  4911. { signalCursorActivity(cm); }
  4912. updateDoc(doc, change, spans, estimateHeight(cm));
  4913. if (!cm.options.lineWrapping) {
  4914. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4915. var len = lineLength(line);
  4916. if (len > display.maxLineLength) {
  4917. display.maxLine = line;
  4918. display.maxLineLength = len;
  4919. display.maxLineChanged = true;
  4920. recomputeMaxLength = false;
  4921. }
  4922. });
  4923. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4924. }
  4925. retreatFrontier(doc, from.line);
  4926. startWorker(cm, 400);
  4927. var lendiff = change.text.length - (to.line - from.line) - 1;
  4928. // Remember that these lines changed, for updating the display
  4929. if (change.full)
  4930. { regChange(cm); }
  4931. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4932. { regLineChange(cm, from.line, "text"); }
  4933. else
  4934. { regChange(cm, from.line, to.line + 1, lendiff); }
  4935. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4936. if (changeHandler || changesHandler) {
  4937. var obj = {
  4938. from: from, to: to,
  4939. text: change.text,
  4940. removed: change.removed,
  4941. origin: change.origin
  4942. };
  4943. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  4944. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  4945. }
  4946. cm.display.selForContextMenu = null;
  4947. }
  4948. function replaceRange(doc, code, from, to, origin) {
  4949. var assign;
  4950. if (!to) { to = from; }
  4951. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  4952. if (typeof code == "string") { code = doc.splitLines(code); }
  4953. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4954. }
  4955. // Rebasing/resetting history to deal with externally-sourced changes
  4956. function rebaseHistSelSingle(pos, from, to, diff) {
  4957. if (to < pos.line) {
  4958. pos.line += diff;
  4959. } else if (from < pos.line) {
  4960. pos.line = from;
  4961. pos.ch = 0;
  4962. }
  4963. }
  4964. // Tries to rebase an array of history events given a change in the
  4965. // document. If the change touches the same lines as the event, the
  4966. // event, and everything 'behind' it, is discarded. If the change is
  4967. // before the event, the event's positions are updated. Uses a
  4968. // copy-on-write scheme for the positions, to avoid having to
  4969. // reallocate them all on every rebase, but also avoid problems with
  4970. // shared position objects being unsafely updated.
  4971. function rebaseHistArray(array, from, to, diff) {
  4972. for (var i = 0; i < array.length; ++i) {
  4973. var sub = array[i], ok = true;
  4974. if (sub.ranges) {
  4975. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  4976. for (var j = 0; j < sub.ranges.length; j++) {
  4977. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  4978. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  4979. }
  4980. continue
  4981. }
  4982. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4983. var cur = sub.changes[j$1];
  4984. if (to < cur.from.line) {
  4985. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  4986. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  4987. } else if (from <= cur.to.line) {
  4988. ok = false;
  4989. break
  4990. }
  4991. }
  4992. if (!ok) {
  4993. array.splice(0, i + 1);
  4994. i = 0;
  4995. }
  4996. }
  4997. }
  4998. function rebaseHist(hist, change) {
  4999. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5000. rebaseHistArray(hist.done, from, to, diff);
  5001. rebaseHistArray(hist.undone, from, to, diff);
  5002. }
  5003. // Utility for applying a change to a line by handle or number,
  5004. // returning the number and optionally registering the line as
  5005. // changed.
  5006. function changeLine(doc, handle, changeType, op) {
  5007. var no = handle, line = handle;
  5008. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5009. else { no = lineNo(handle); }
  5010. if (no == null) { return null }
  5011. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5012. return line
  5013. }
  5014. // The document is represented as a BTree consisting of leaves, with
  5015. // chunk of lines in them, and branches, with up to ten leaves or
  5016. // other branch nodes below them. The top node is always a branch
  5017. // node, and is the document object itself (meaning it has
  5018. // additional methods and properties).
  5019. //
  5020. // All nodes have parent links. The tree is used both to go from
  5021. // line numbers to line objects, and to go from objects to numbers.
  5022. // It also indexes by height, and is used to convert between height
  5023. // and line object, and to find the total height of the document.
  5024. //
  5025. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5026. function LeafChunk(lines) {
  5027. this.lines = lines;
  5028. this.parent = null;
  5029. var height = 0;
  5030. for (var i = 0; i < lines.length; ++i) {
  5031. lines[i].parent = this;
  5032. height += lines[i].height;
  5033. }
  5034. this.height = height;
  5035. }
  5036. LeafChunk.prototype = {
  5037. chunkSize: function() { return this.lines.length },
  5038. // Remove the n lines at offset 'at'.
  5039. removeInner: function(at, n) {
  5040. for (var i = at, e = at + n; i < e; ++i) {
  5041. var line = this.lines[i];
  5042. this.height -= line.height;
  5043. cleanUpLine(line);
  5044. signalLater(line, "delete");
  5045. }
  5046. this.lines.splice(at, n);
  5047. },
  5048. // Helper used to collapse a small branch into a single leaf.
  5049. collapse: function(lines) {
  5050. lines.push.apply(lines, this.lines);
  5051. },
  5052. // Insert the given array of lines at offset 'at', count them as
  5053. // having the given height.
  5054. insertInner: function(at, lines, height) {
  5055. this.height += height;
  5056. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5057. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5058. },
  5059. // Used to iterate over a part of the tree.
  5060. iterN: function(at, n, op) {
  5061. for (var e = at + n; at < e; ++at)
  5062. { if (op(this.lines[at])) { return true } }
  5063. }
  5064. };
  5065. function BranchChunk(children) {
  5066. this.children = children;
  5067. var size = 0, height = 0;
  5068. for (var i = 0; i < children.length; ++i) {
  5069. var ch = children[i];
  5070. size += ch.chunkSize(); height += ch.height;
  5071. ch.parent = this;
  5072. }
  5073. this.size = size;
  5074. this.height = height;
  5075. this.parent = null;
  5076. }
  5077. BranchChunk.prototype = {
  5078. chunkSize: function() { return this.size },
  5079. removeInner: function(at, n) {
  5080. this.size -= n;
  5081. for (var i = 0; i < this.children.length; ++i) {
  5082. var child = this.children[i], sz = child.chunkSize();
  5083. if (at < sz) {
  5084. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5085. child.removeInner(at, rm);
  5086. this.height -= oldHeight - child.height;
  5087. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5088. if ((n -= rm) == 0) { break }
  5089. at = 0;
  5090. } else { at -= sz; }
  5091. }
  5092. // If the result is smaller than 25 lines, ensure that it is a
  5093. // single leaf node.
  5094. if (this.size - n < 25 &&
  5095. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5096. var lines = [];
  5097. this.collapse(lines);
  5098. this.children = [new LeafChunk(lines)];
  5099. this.children[0].parent = this;
  5100. }
  5101. },
  5102. collapse: function(lines) {
  5103. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5104. },
  5105. insertInner: function(at, lines, height) {
  5106. this.size += lines.length;
  5107. this.height += height;
  5108. for (var i = 0; i < this.children.length; ++i) {
  5109. var child = this.children[i], sz = child.chunkSize();
  5110. if (at <= sz) {
  5111. child.insertInner(at, lines, height);
  5112. if (child.lines && child.lines.length > 50) {
  5113. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5114. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5115. var remaining = child.lines.length % 25 + 25;
  5116. for (var pos = remaining; pos < child.lines.length;) {
  5117. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5118. child.height -= leaf.height;
  5119. this.children.splice(++i, 0, leaf);
  5120. leaf.parent = this;
  5121. }
  5122. child.lines = child.lines.slice(0, remaining);
  5123. this.maybeSpill();
  5124. }
  5125. break
  5126. }
  5127. at -= sz;
  5128. }
  5129. },
  5130. // When a node has grown, check whether it should be split.
  5131. maybeSpill: function() {
  5132. if (this.children.length <= 10) { return }
  5133. var me = this;
  5134. do {
  5135. var spilled = me.children.splice(me.children.length - 5, 5);
  5136. var sibling = new BranchChunk(spilled);
  5137. if (!me.parent) { // Become the parent node
  5138. var copy = new BranchChunk(me.children);
  5139. copy.parent = me;
  5140. me.children = [copy, sibling];
  5141. me = copy;
  5142. } else {
  5143. me.size -= sibling.size;
  5144. me.height -= sibling.height;
  5145. var myIndex = indexOf(me.parent.children, me);
  5146. me.parent.children.splice(myIndex + 1, 0, sibling);
  5147. }
  5148. sibling.parent = me.parent;
  5149. } while (me.children.length > 10)
  5150. me.parent.maybeSpill();
  5151. },
  5152. iterN: function(at, n, op) {
  5153. for (var i = 0; i < this.children.length; ++i) {
  5154. var child = this.children[i], sz = child.chunkSize();
  5155. if (at < sz) {
  5156. var used = Math.min(n, sz - at);
  5157. if (child.iterN(at, used, op)) { return true }
  5158. if ((n -= used) == 0) { break }
  5159. at = 0;
  5160. } else { at -= sz; }
  5161. }
  5162. }
  5163. };
  5164. // Line widgets are block elements displayed above or below a line.
  5165. var LineWidget = function(doc, node, options) {
  5166. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5167. { this[opt] = options[opt]; } } }
  5168. this.doc = doc;
  5169. this.node = node;
  5170. };
  5171. LineWidget.prototype.clear = function () {
  5172. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5173. if (no == null || !ws) { return }
  5174. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5175. if (!ws.length) { line.widgets = null; }
  5176. var height = widgetHeight(this);
  5177. updateLineHeight(line, Math.max(0, line.height - height));
  5178. if (cm) {
  5179. runInOp(cm, function () {
  5180. adjustScrollWhenAboveVisible(cm, line, -height);
  5181. regLineChange(cm, no, "widget");
  5182. });
  5183. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5184. }
  5185. };
  5186. LineWidget.prototype.changed = function () {
  5187. var this$1 = this;
  5188. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5189. this.height = null;
  5190. var diff = widgetHeight(this) - oldH;
  5191. if (!diff) { return }
  5192. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5193. if (cm) {
  5194. runInOp(cm, function () {
  5195. cm.curOp.forceUpdate = true;
  5196. adjustScrollWhenAboveVisible(cm, line, diff);
  5197. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5198. });
  5199. }
  5200. };
  5201. eventMixin(LineWidget);
  5202. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5203. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5204. { addToScrollTop(cm, diff); }
  5205. }
  5206. function addLineWidget(doc, handle, node, options) {
  5207. var widget = new LineWidget(doc, node, options);
  5208. var cm = doc.cm;
  5209. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5210. changeLine(doc, handle, "widget", function (line) {
  5211. var widgets = line.widgets || (line.widgets = []);
  5212. if (widget.insertAt == null) { widgets.push(widget); }
  5213. else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  5214. widget.line = line;
  5215. if (cm && !lineIsHidden(doc, line)) {
  5216. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5217. updateLineHeight(line, line.height + widgetHeight(widget));
  5218. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5219. cm.curOp.forceUpdate = true;
  5220. }
  5221. return true
  5222. });
  5223. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5224. return widget
  5225. }
  5226. // TEXTMARKERS
  5227. // Created with markText and setBookmark methods. A TextMarker is a
  5228. // handle that can be used to clear or find a marked position in the
  5229. // document. Line objects hold arrays (markedSpans) containing
  5230. // {from, to, marker} object pointing to such marker objects, and
  5231. // indicating that such a marker is present on that line. Multiple
  5232. // lines may point to the same marker when it spans across lines.
  5233. // The spans will have null for their from/to properties when the
  5234. // marker continues beyond the start/end of the line. Markers have
  5235. // links back to the lines they currently touch.
  5236. // Collapsed markers have unique ids, in order to be able to order
  5237. // them, which is needed for uniquely determining an outer marker
  5238. // when they overlap (they may nest, but not partially overlap).
  5239. var nextMarkerId = 0;
  5240. var TextMarker = function(doc, type) {
  5241. this.lines = [];
  5242. this.type = type;
  5243. this.doc = doc;
  5244. this.id = ++nextMarkerId;
  5245. };
  5246. // Clear the marker.
  5247. TextMarker.prototype.clear = function () {
  5248. if (this.explicitlyCleared) { return }
  5249. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5250. if (withOp) { startOperation(cm); }
  5251. if (hasHandler(this, "clear")) {
  5252. var found = this.find();
  5253. if (found) { signalLater(this, "clear", found.from, found.to); }
  5254. }
  5255. var min = null, max = null;
  5256. for (var i = 0; i < this.lines.length; ++i) {
  5257. var line = this.lines[i];
  5258. var span = getMarkedSpanFor(line.markedSpans, this);
  5259. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5260. else if (cm) {
  5261. if (span.to != null) { max = lineNo(line); }
  5262. if (span.from != null) { min = lineNo(line); }
  5263. }
  5264. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5265. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5266. { updateLineHeight(line, textHeight(cm.display)); }
  5267. }
  5268. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5269. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5270. if (len > cm.display.maxLineLength) {
  5271. cm.display.maxLine = visual;
  5272. cm.display.maxLineLength = len;
  5273. cm.display.maxLineChanged = true;
  5274. }
  5275. } }
  5276. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5277. this.lines.length = 0;
  5278. this.explicitlyCleared = true;
  5279. if (this.atomic && this.doc.cantEdit) {
  5280. this.doc.cantEdit = false;
  5281. if (cm) { reCheckSelection(cm.doc); }
  5282. }
  5283. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5284. if (withOp) { endOperation(cm); }
  5285. if (this.parent) { this.parent.clear(); }
  5286. };
  5287. // Find the position of the marker in the document. Returns a {from,
  5288. // to} object by default. Side can be passed to get a specific side
  5289. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5290. // Pos objects returned contain a line object, rather than a line
  5291. // number (used to prevent looking up the same line twice).
  5292. TextMarker.prototype.find = function (side, lineObj) {
  5293. if (side == null && this.type == "bookmark") { side = 1; }
  5294. var from, to;
  5295. for (var i = 0; i < this.lines.length; ++i) {
  5296. var line = this.lines[i];
  5297. var span = getMarkedSpanFor(line.markedSpans, this);
  5298. if (span.from != null) {
  5299. from = Pos(lineObj ? line : lineNo(line), span.from);
  5300. if (side == -1) { return from }
  5301. }
  5302. if (span.to != null) {
  5303. to = Pos(lineObj ? line : lineNo(line), span.to);
  5304. if (side == 1) { return to }
  5305. }
  5306. }
  5307. return from && {from: from, to: to}
  5308. };
  5309. // Signals that the marker's widget changed, and surrounding layout
  5310. // should be recomputed.
  5311. TextMarker.prototype.changed = function () {
  5312. var this$1 = this;
  5313. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5314. if (!pos || !cm) { return }
  5315. runInOp(cm, function () {
  5316. var line = pos.line, lineN = lineNo(pos.line);
  5317. var view = findViewForLine(cm, lineN);
  5318. if (view) {
  5319. clearLineMeasurementCacheFor(view);
  5320. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5321. }
  5322. cm.curOp.updateMaxLine = true;
  5323. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5324. var oldHeight = widget.height;
  5325. widget.height = null;
  5326. var dHeight = widgetHeight(widget) - oldHeight;
  5327. if (dHeight)
  5328. { updateLineHeight(line, line.height + dHeight); }
  5329. }
  5330. signalLater(cm, "markerChanged", cm, this$1);
  5331. });
  5332. };
  5333. TextMarker.prototype.attachLine = function (line) {
  5334. if (!this.lines.length && this.doc.cm) {
  5335. var op = this.doc.cm.curOp;
  5336. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5337. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5338. }
  5339. this.lines.push(line);
  5340. };
  5341. TextMarker.prototype.detachLine = function (line) {
  5342. this.lines.splice(indexOf(this.lines, line), 1);
  5343. if (!this.lines.length && this.doc.cm) {
  5344. var op = this.doc.cm.curOp
  5345. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5346. }
  5347. };
  5348. eventMixin(TextMarker);
  5349. // Create a marker, wire it up to the right lines, and
  5350. function markText(doc, from, to, options, type) {
  5351. // Shared markers (across linked documents) are handled separately
  5352. // (markTextShared will call out to this again, once per
  5353. // document).
  5354. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5355. // Ensure we are in an operation.
  5356. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5357. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5358. if (options) { copyObj(options, marker, false); }
  5359. // Don't connect empty markers unless clearWhenEmpty is false
  5360. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5361. { return marker }
  5362. if (marker.replacedWith) {
  5363. // Showing up as a widget implies collapsed (widget replaces text)
  5364. marker.collapsed = true;
  5365. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5366. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5367. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5368. }
  5369. if (marker.collapsed) {
  5370. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5371. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5372. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5373. seeCollapsedSpans();
  5374. }
  5375. if (marker.addToHistory)
  5376. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5377. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5378. doc.iter(curLine, to.line + 1, function (line) {
  5379. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5380. { updateMaxLine = true; }
  5381. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5382. addMarkedSpan(line, new MarkedSpan(marker,
  5383. curLine == from.line ? from.ch : null,
  5384. curLine == to.line ? to.ch : null));
  5385. ++curLine;
  5386. });
  5387. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5388. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5389. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5390. }); }
  5391. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5392. if (marker.readOnly) {
  5393. seeReadOnlySpans();
  5394. if (doc.history.done.length || doc.history.undone.length)
  5395. { doc.clearHistory(); }
  5396. }
  5397. if (marker.collapsed) {
  5398. marker.id = ++nextMarkerId;
  5399. marker.atomic = true;
  5400. }
  5401. if (cm) {
  5402. // Sync editor state
  5403. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5404. if (marker.collapsed)
  5405. { regChange(cm, from.line, to.line + 1); }
  5406. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5407. marker.attributes || marker.title)
  5408. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5409. if (marker.atomic) { reCheckSelection(cm.doc); }
  5410. signalLater(cm, "markerAdded", cm, marker);
  5411. }
  5412. return marker
  5413. }
  5414. // SHARED TEXTMARKERS
  5415. // A shared marker spans multiple linked documents. It is
  5416. // implemented as a meta-marker-object controlling multiple normal
  5417. // markers.
  5418. var SharedTextMarker = function(markers, primary) {
  5419. this.markers = markers;
  5420. this.primary = primary;
  5421. for (var i = 0; i < markers.length; ++i)
  5422. { markers[i].parent = this; }
  5423. };
  5424. SharedTextMarker.prototype.clear = function () {
  5425. if (this.explicitlyCleared) { return }
  5426. this.explicitlyCleared = true;
  5427. for (var i = 0; i < this.markers.length; ++i)
  5428. { this.markers[i].clear(); }
  5429. signalLater(this, "clear");
  5430. };
  5431. SharedTextMarker.prototype.find = function (side, lineObj) {
  5432. return this.primary.find(side, lineObj)
  5433. };
  5434. eventMixin(SharedTextMarker);
  5435. function markTextShared(doc, from, to, options, type) {
  5436. options = copyObj(options);
  5437. options.shared = false;
  5438. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5439. var widget = options.widgetNode;
  5440. linkedDocs(doc, function (doc) {
  5441. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5442. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5443. for (var i = 0; i < doc.linked.length; ++i)
  5444. { if (doc.linked[i].isParent) { return } }
  5445. primary = lst(markers);
  5446. });
  5447. return new SharedTextMarker(markers, primary)
  5448. }
  5449. function findSharedMarkers(doc) {
  5450. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5451. }
  5452. function copySharedMarkers(doc, markers) {
  5453. for (var i = 0; i < markers.length; i++) {
  5454. var marker = markers[i], pos = marker.find();
  5455. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5456. if (cmp(mFrom, mTo)) {
  5457. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5458. marker.markers.push(subMark);
  5459. subMark.parent = marker;
  5460. }
  5461. }
  5462. }
  5463. function detachSharedMarkers(markers) {
  5464. var loop = function ( i ) {
  5465. var marker = markers[i], linked = [marker.primary.doc];
  5466. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5467. for (var j = 0; j < marker.markers.length; j++) {
  5468. var subMarker = marker.markers[j];
  5469. if (indexOf(linked, subMarker.doc) == -1) {
  5470. subMarker.parent = null;
  5471. marker.markers.splice(j--, 1);
  5472. }
  5473. }
  5474. };
  5475. for (var i = 0; i < markers.length; i++) loop( i );
  5476. }
  5477. var nextDocId = 0;
  5478. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5479. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5480. if (firstLine == null) { firstLine = 0; }
  5481. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5482. this.first = firstLine;
  5483. this.scrollTop = this.scrollLeft = 0;
  5484. this.cantEdit = false;
  5485. this.cleanGeneration = 1;
  5486. this.modeFrontier = this.highlightFrontier = firstLine;
  5487. var start = Pos(firstLine, 0);
  5488. this.sel = simpleSelection(start);
  5489. this.history = new History(null);
  5490. this.id = ++nextDocId;
  5491. this.modeOption = mode;
  5492. this.lineSep = lineSep;
  5493. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5494. this.extend = false;
  5495. if (typeof text == "string") { text = this.splitLines(text); }
  5496. updateDoc(this, {from: start, to: start, text: text});
  5497. setSelection(this, simpleSelection(start), sel_dontScroll);
  5498. };
  5499. Doc.prototype = createObj(BranchChunk.prototype, {
  5500. constructor: Doc,
  5501. // Iterate over the document. Supports two forms -- with only one
  5502. // argument, it calls that for each line in the document. With
  5503. // three, it iterates over the range given by the first two (with
  5504. // the second being non-inclusive).
  5505. iter: function(from, to, op) {
  5506. if (op) { this.iterN(from - this.first, to - from, op); }
  5507. else { this.iterN(this.first, this.first + this.size, from); }
  5508. },
  5509. // Non-public interface for adding and removing lines.
  5510. insert: function(at, lines) {
  5511. var height = 0;
  5512. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5513. this.insertInner(at - this.first, lines, height);
  5514. },
  5515. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5516. // From here, the methods are part of the public interface. Most
  5517. // are also available from CodeMirror (editor) instances.
  5518. getValue: function(lineSep) {
  5519. var lines = getLines(this, this.first, this.first + this.size);
  5520. if (lineSep === false) { return lines }
  5521. return lines.join(lineSep || this.lineSeparator())
  5522. },
  5523. setValue: docMethodOp(function(code) {
  5524. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5525. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5526. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5527. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5528. setSelection(this, simpleSelection(top), sel_dontScroll);
  5529. }),
  5530. replaceRange: function(code, from, to, origin) {
  5531. from = clipPos(this, from);
  5532. to = to ? clipPos(this, to) : from;
  5533. replaceRange(this, code, from, to, origin);
  5534. },
  5535. getRange: function(from, to, lineSep) {
  5536. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5537. if (lineSep === false) { return lines }
  5538. return lines.join(lineSep || this.lineSeparator())
  5539. },
  5540. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5541. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5542. getLineNumber: function(line) {return lineNo(line)},
  5543. getLineHandleVisualStart: function(line) {
  5544. if (typeof line == "number") { line = getLine(this, line); }
  5545. return visualLine(line)
  5546. },
  5547. lineCount: function() {return this.size},
  5548. firstLine: function() {return this.first},
  5549. lastLine: function() {return this.first + this.size - 1},
  5550. clipPos: function(pos) {return clipPos(this, pos)},
  5551. getCursor: function(start) {
  5552. var range = this.sel.primary(), pos;
  5553. if (start == null || start == "head") { pos = range.head; }
  5554. else if (start == "anchor") { pos = range.anchor; }
  5555. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  5556. else { pos = range.from(); }
  5557. return pos
  5558. },
  5559. listSelections: function() { return this.sel.ranges },
  5560. somethingSelected: function() {return this.sel.somethingSelected()},
  5561. setCursor: docMethodOp(function(line, ch, options) {
  5562. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5563. }),
  5564. setSelection: docMethodOp(function(anchor, head, options) {
  5565. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5566. }),
  5567. extendSelection: docMethodOp(function(head, other, options) {
  5568. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5569. }),
  5570. extendSelections: docMethodOp(function(heads, options) {
  5571. extendSelections(this, clipPosArray(this, heads), options);
  5572. }),
  5573. extendSelectionsBy: docMethodOp(function(f, options) {
  5574. var heads = map(this.sel.ranges, f);
  5575. extendSelections(this, clipPosArray(this, heads), options);
  5576. }),
  5577. setSelections: docMethodOp(function(ranges, primary, options) {
  5578. if (!ranges.length) { return }
  5579. var out = [];
  5580. for (var i = 0; i < ranges.length; i++)
  5581. { out[i] = new Range(clipPos(this, ranges[i].anchor),
  5582. clipPos(this, ranges[i].head)); }
  5583. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5584. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5585. }),
  5586. addSelection: docMethodOp(function(anchor, head, options) {
  5587. var ranges = this.sel.ranges.slice(0);
  5588. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5589. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5590. }),
  5591. getSelection: function(lineSep) {
  5592. var ranges = this.sel.ranges, lines;
  5593. for (var i = 0; i < ranges.length; i++) {
  5594. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5595. lines = lines ? lines.concat(sel) : sel;
  5596. }
  5597. if (lineSep === false) { return lines }
  5598. else { return lines.join(lineSep || this.lineSeparator()) }
  5599. },
  5600. getSelections: function(lineSep) {
  5601. var parts = [], ranges = this.sel.ranges;
  5602. for (var i = 0; i < ranges.length; i++) {
  5603. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5604. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  5605. parts[i] = sel;
  5606. }
  5607. return parts
  5608. },
  5609. replaceSelection: function(code, collapse, origin) {
  5610. var dup = [];
  5611. for (var i = 0; i < this.sel.ranges.length; i++)
  5612. { dup[i] = code; }
  5613. this.replaceSelections(dup, collapse, origin || "+input");
  5614. },
  5615. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5616. var changes = [], sel = this.sel;
  5617. for (var i = 0; i < sel.ranges.length; i++) {
  5618. var range = sel.ranges[i];
  5619. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  5620. }
  5621. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5622. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5623. { makeChange(this, changes[i$1]); }
  5624. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5625. else if (this.cm) { ensureCursorVisible(this.cm); }
  5626. }),
  5627. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5628. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5629. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5630. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5631. setExtending: function(val) {this.extend = val;},
  5632. getExtending: function() {return this.extend},
  5633. historySize: function() {
  5634. var hist = this.history, done = 0, undone = 0;
  5635. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5636. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5637. return {undo: done, redo: undone}
  5638. },
  5639. clearHistory: function() {
  5640. var this$1 = this;
  5641. this.history = new History(this.history.maxGeneration);
  5642. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  5643. },
  5644. markClean: function() {
  5645. this.cleanGeneration = this.changeGeneration(true);
  5646. },
  5647. changeGeneration: function(forceSplit) {
  5648. if (forceSplit)
  5649. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5650. return this.history.generation
  5651. },
  5652. isClean: function (gen) {
  5653. return this.history.generation == (gen || this.cleanGeneration)
  5654. },
  5655. getHistory: function() {
  5656. return {done: copyHistoryArray(this.history.done),
  5657. undone: copyHistoryArray(this.history.undone)}
  5658. },
  5659. setHistory: function(histData) {
  5660. var hist = this.history = new History(this.history.maxGeneration);
  5661. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5662. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5663. },
  5664. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5665. return changeLine(this, line, "gutter", function (line) {
  5666. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5667. markers[gutterID] = value;
  5668. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5669. return true
  5670. })
  5671. }),
  5672. clearGutter: docMethodOp(function(gutterID) {
  5673. var this$1 = this;
  5674. this.iter(function (line) {
  5675. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5676. changeLine(this$1, line, "gutter", function () {
  5677. line.gutterMarkers[gutterID] = null;
  5678. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5679. return true
  5680. });
  5681. }
  5682. });
  5683. }),
  5684. lineInfo: function(line) {
  5685. var n;
  5686. if (typeof line == "number") {
  5687. if (!isLine(this, line)) { return null }
  5688. n = line;
  5689. line = getLine(this, line);
  5690. if (!line) { return null }
  5691. } else {
  5692. n = lineNo(line);
  5693. if (n == null) { return null }
  5694. }
  5695. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5696. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5697. widgets: line.widgets}
  5698. },
  5699. addLineClass: docMethodOp(function(handle, where, cls) {
  5700. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5701. var prop = where == "text" ? "textClass"
  5702. : where == "background" ? "bgClass"
  5703. : where == "gutter" ? "gutterClass" : "wrapClass";
  5704. if (!line[prop]) { line[prop] = cls; }
  5705. else if (classTest(cls).test(line[prop])) { return false }
  5706. else { line[prop] += " " + cls; }
  5707. return true
  5708. })
  5709. }),
  5710. removeLineClass: docMethodOp(function(handle, where, cls) {
  5711. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5712. var prop = where == "text" ? "textClass"
  5713. : where == "background" ? "bgClass"
  5714. : where == "gutter" ? "gutterClass" : "wrapClass";
  5715. var cur = line[prop];
  5716. if (!cur) { return false }
  5717. else if (cls == null) { line[prop] = null; }
  5718. else {
  5719. var found = cur.match(classTest(cls));
  5720. if (!found) { return false }
  5721. var end = found.index + found[0].length;
  5722. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5723. }
  5724. return true
  5725. })
  5726. }),
  5727. addLineWidget: docMethodOp(function(handle, node, options) {
  5728. return addLineWidget(this, handle, node, options)
  5729. }),
  5730. removeLineWidget: function(widget) { widget.clear(); },
  5731. markText: function(from, to, options) {
  5732. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5733. },
  5734. setBookmark: function(pos, options) {
  5735. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5736. insertLeft: options && options.insertLeft,
  5737. clearWhenEmpty: false, shared: options && options.shared,
  5738. handleMouseEvents: options && options.handleMouseEvents};
  5739. pos = clipPos(this, pos);
  5740. return markText(this, pos, pos, realOpts, "bookmark")
  5741. },
  5742. findMarksAt: function(pos) {
  5743. pos = clipPos(this, pos);
  5744. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5745. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5746. var span = spans[i];
  5747. if ((span.from == null || span.from <= pos.ch) &&
  5748. (span.to == null || span.to >= pos.ch))
  5749. { markers.push(span.marker.parent || span.marker); }
  5750. } }
  5751. return markers
  5752. },
  5753. findMarks: function(from, to, filter) {
  5754. from = clipPos(this, from); to = clipPos(this, to);
  5755. var found = [], lineNo = from.line;
  5756. this.iter(from.line, to.line + 1, function (line) {
  5757. var spans = line.markedSpans;
  5758. if (spans) { for (var i = 0; i < spans.length; i++) {
  5759. var span = spans[i];
  5760. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5761. span.from == null && lineNo != from.line ||
  5762. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5763. (!filter || filter(span.marker)))
  5764. { found.push(span.marker.parent || span.marker); }
  5765. } }
  5766. ++lineNo;
  5767. });
  5768. return found
  5769. },
  5770. getAllMarks: function() {
  5771. var markers = [];
  5772. this.iter(function (line) {
  5773. var sps = line.markedSpans;
  5774. if (sps) { for (var i = 0; i < sps.length; ++i)
  5775. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5776. });
  5777. return markers
  5778. },
  5779. posFromIndex: function(off) {
  5780. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  5781. this.iter(function (line) {
  5782. var sz = line.text.length + sepSize;
  5783. if (sz > off) { ch = off; return true }
  5784. off -= sz;
  5785. ++lineNo;
  5786. });
  5787. return clipPos(this, Pos(lineNo, ch))
  5788. },
  5789. indexFromPos: function (coords) {
  5790. coords = clipPos(this, coords);
  5791. var index = coords.ch;
  5792. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5793. var sepSize = this.lineSeparator().length;
  5794. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5795. index += line.text.length + sepSize;
  5796. });
  5797. return index
  5798. },
  5799. copy: function(copyHistory) {
  5800. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5801. this.modeOption, this.first, this.lineSep, this.direction);
  5802. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5803. doc.sel = this.sel;
  5804. doc.extend = false;
  5805. if (copyHistory) {
  5806. doc.history.undoDepth = this.history.undoDepth;
  5807. doc.setHistory(this.getHistory());
  5808. }
  5809. return doc
  5810. },
  5811. linkedDoc: function(options) {
  5812. if (!options) { options = {}; }
  5813. var from = this.first, to = this.first + this.size;
  5814. if (options.from != null && options.from > from) { from = options.from; }
  5815. if (options.to != null && options.to < to) { to = options.to; }
  5816. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5817. if (options.sharedHist) { copy.history = this.history
  5818. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5819. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5820. copySharedMarkers(copy, findSharedMarkers(this));
  5821. return copy
  5822. },
  5823. unlinkDoc: function(other) {
  5824. if (other instanceof CodeMirror) { other = other.doc; }
  5825. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5826. var link = this.linked[i];
  5827. if (link.doc != other) { continue }
  5828. this.linked.splice(i, 1);
  5829. other.unlinkDoc(this);
  5830. detachSharedMarkers(findSharedMarkers(this));
  5831. break
  5832. } }
  5833. // If the histories were shared, split them again
  5834. if (other.history == this.history) {
  5835. var splitIds = [other.id];
  5836. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5837. other.history = new History(null);
  5838. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5839. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5840. }
  5841. },
  5842. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5843. getMode: function() {return this.mode},
  5844. getEditor: function() {return this.cm},
  5845. splitLines: function(str) {
  5846. if (this.lineSep) { return str.split(this.lineSep) }
  5847. return splitLinesAuto(str)
  5848. },
  5849. lineSeparator: function() { return this.lineSep || "\n" },
  5850. setDirection: docMethodOp(function (dir) {
  5851. if (dir != "rtl") { dir = "ltr"; }
  5852. if (dir == this.direction) { return }
  5853. this.direction = dir;
  5854. this.iter(function (line) { return line.order = null; });
  5855. if (this.cm) { directionChanged(this.cm); }
  5856. })
  5857. });
  5858. // Public alias.
  5859. Doc.prototype.eachLine = Doc.prototype.iter;
  5860. // Kludge to work around strange IE behavior where it'll sometimes
  5861. // re-fire a series of drag-related events right after the drop (#1551)
  5862. var lastDrop = 0;
  5863. function onDrop(e) {
  5864. var cm = this;
  5865. clearDragCursor(cm);
  5866. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5867. { return }
  5868. e_preventDefault(e);
  5869. if (ie) { lastDrop = +new Date; }
  5870. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5871. if (!pos || cm.isReadOnly()) { return }
  5872. // Might be a file drop, in which case we simply extract the text
  5873. // and insert it.
  5874. if (files && files.length && window.FileReader && window.File) {
  5875. var n = files.length, text = Array(n), read = 0;
  5876. var markAsReadAndPasteIfAllFilesAreRead = function () {
  5877. if (++read == n) {
  5878. operation(cm, function () {
  5879. pos = clipPos(cm.doc, pos);
  5880. var change = {from: pos, to: pos,
  5881. text: cm.doc.splitLines(
  5882. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  5883. origin: "paste"};
  5884. makeChange(cm.doc, change);
  5885. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  5886. })();
  5887. }
  5888. };
  5889. var readTextFromFile = function (file, i) {
  5890. if (cm.options.allowDropFileTypes &&
  5891. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  5892. markAsReadAndPasteIfAllFilesAreRead();
  5893. return
  5894. }
  5895. var reader = new FileReader;
  5896. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  5897. reader.onload = function () {
  5898. var content = reader.result;
  5899. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  5900. markAsReadAndPasteIfAllFilesAreRead();
  5901. return
  5902. }
  5903. text[i] = content;
  5904. markAsReadAndPasteIfAllFilesAreRead();
  5905. };
  5906. reader.readAsText(file);
  5907. };
  5908. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  5909. } else { // Normal drop
  5910. // Don't do a replace if the drop happened inside of the selected text.
  5911. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5912. cm.state.draggingText(e);
  5913. // Ensure the editor is re-focused
  5914. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5915. return
  5916. }
  5917. try {
  5918. var text$1 = e.dataTransfer.getData("Text");
  5919. if (text$1) {
  5920. var selected;
  5921. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5922. { selected = cm.listSelections(); }
  5923. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5924. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5925. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5926. cm.replaceSelection(text$1, "around", "paste");
  5927. cm.display.input.focus();
  5928. }
  5929. }
  5930. catch(e$1){}
  5931. }
  5932. }
  5933. function onDragStart(cm, e) {
  5934. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5935. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5936. e.dataTransfer.setData("Text", cm.getSelection());
  5937. e.dataTransfer.effectAllowed = "copyMove";
  5938. // Use dummy image instead of default browsers image.
  5939. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5940. if (e.dataTransfer.setDragImage && !safari) {
  5941. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5942. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5943. if (presto) {
  5944. img.width = img.height = 1;
  5945. cm.display.wrapper.appendChild(img);
  5946. // Force a relayout, or Opera won't use our image for some obscure reason
  5947. img._top = img.offsetTop;
  5948. }
  5949. e.dataTransfer.setDragImage(img, 0, 0);
  5950. if (presto) { img.parentNode.removeChild(img); }
  5951. }
  5952. }
  5953. function onDragOver(cm, e) {
  5954. var pos = posFromMouse(cm, e);
  5955. if (!pos) { return }
  5956. var frag = document.createDocumentFragment();
  5957. drawSelectionCursor(cm, pos, frag);
  5958. if (!cm.display.dragCursor) {
  5959. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5960. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5961. }
  5962. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5963. }
  5964. function clearDragCursor(cm) {
  5965. if (cm.display.dragCursor) {
  5966. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5967. cm.display.dragCursor = null;
  5968. }
  5969. }
  5970. // These must be handled carefully, because naively registering a
  5971. // handler for each editor will cause the editors to never be
  5972. // garbage collected.
  5973. function forEachCodeMirror(f) {
  5974. if (!document.getElementsByClassName) { return }
  5975. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  5976. for (var i = 0; i < byClass.length; i++) {
  5977. var cm = byClass[i].CodeMirror;
  5978. if (cm) { editors.push(cm); }
  5979. }
  5980. if (editors.length) { editors[0].operation(function () {
  5981. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  5982. }); }
  5983. }
  5984. var globalsRegistered = false;
  5985. function ensureGlobalHandlers() {
  5986. if (globalsRegistered) { return }
  5987. registerGlobalHandlers();
  5988. globalsRegistered = true;
  5989. }
  5990. function registerGlobalHandlers() {
  5991. // When the window resizes, we need to refresh active editors.
  5992. var resizeTimer;
  5993. on(window, "resize", function () {
  5994. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5995. resizeTimer = null;
  5996. forEachCodeMirror(onResize);
  5997. }, 100); }
  5998. });
  5999. // When the window loses focus, we want to show the editor as blurred
  6000. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6001. }
  6002. // Called when the window resizes
  6003. function onResize(cm) {
  6004. var d = cm.display;
  6005. // Might be a text scaling operation, clear size caches.
  6006. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6007. d.scrollbarsClipped = false;
  6008. cm.setSize();
  6009. }
  6010. var keyNames = {
  6011. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6012. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6013. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6014. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6015. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6016. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6017. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6018. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6019. };
  6020. // Number keys
  6021. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6022. // Alphabetic keys
  6023. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6024. // Function keys
  6025. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6026. var keyMap = {};
  6027. keyMap.basic = {
  6028. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6029. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6030. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6031. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6032. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6033. "Esc": "singleSelection"
  6034. };
  6035. // Note that the save and find-related commands aren't defined by
  6036. // default. User code or addons can define them. Unknown commands
  6037. // are simply ignored.
  6038. keyMap.pcDefault = {
  6039. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6040. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6041. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6042. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6043. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6044. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6045. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6046. "fallthrough": "basic"
  6047. };
  6048. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6049. keyMap.emacsy = {
  6050. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6051. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  6052. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  6053. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  6054. "Ctrl-O": "openLine"
  6055. };
  6056. keyMap.macDefault = {
  6057. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6058. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6059. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6060. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6061. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6062. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6063. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6064. "fallthrough": ["basic", "emacsy"]
  6065. };
  6066. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6067. // KEYMAP DISPATCH
  6068. function normalizeKeyName(name) {
  6069. var parts = name.split(/-(?!$)/);
  6070. name = parts[parts.length - 1];
  6071. var alt, ctrl, shift, cmd;
  6072. for (var i = 0; i < parts.length - 1; i++) {
  6073. var mod = parts[i];
  6074. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6075. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6076. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6077. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6078. else { throw new Error("Unrecognized modifier name: " + mod) }
  6079. }
  6080. if (alt) { name = "Alt-" + name; }
  6081. if (ctrl) { name = "Ctrl-" + name; }
  6082. if (cmd) { name = "Cmd-" + name; }
  6083. if (shift) { name = "Shift-" + name; }
  6084. return name
  6085. }
  6086. // This is a kludge to keep keymaps mostly working as raw objects
  6087. // (backwards compatibility) while at the same time support features
  6088. // like normalization and multi-stroke key bindings. It compiles a
  6089. // new normalized keymap, and then updates the old object to reflect
  6090. // this.
  6091. function normalizeKeyMap(keymap) {
  6092. var copy = {};
  6093. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6094. var value = keymap[keyname];
  6095. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6096. if (value == "...") { delete keymap[keyname]; continue }
  6097. var keys = map(keyname.split(" "), normalizeKeyName);
  6098. for (var i = 0; i < keys.length; i++) {
  6099. var val = (void 0), name = (void 0);
  6100. if (i == keys.length - 1) {
  6101. name = keys.join(" ");
  6102. val = value;
  6103. } else {
  6104. name = keys.slice(0, i + 1).join(" ");
  6105. val = "...";
  6106. }
  6107. var prev = copy[name];
  6108. if (!prev) { copy[name] = val; }
  6109. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6110. }
  6111. delete keymap[keyname];
  6112. } }
  6113. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6114. return keymap
  6115. }
  6116. function lookupKey(key, map, handle, context) {
  6117. map = getKeyMap(map);
  6118. var found = map.call ? map.call(key, context) : map[key];
  6119. if (found === false) { return "nothing" }
  6120. if (found === "...") { return "multi" }
  6121. if (found != null && handle(found)) { return "handled" }
  6122. if (map.fallthrough) {
  6123. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6124. { return lookupKey(key, map.fallthrough, handle, context) }
  6125. for (var i = 0; i < map.fallthrough.length; i++) {
  6126. var result = lookupKey(key, map.fallthrough[i], handle, context);
  6127. if (result) { return result }
  6128. }
  6129. }
  6130. }
  6131. // Modifier key presses don't count as 'real' key presses for the
  6132. // purpose of keymap fallthrough.
  6133. function isModifierKey(value) {
  6134. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6135. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6136. }
  6137. function addModifierNames(name, event, noShift) {
  6138. var base = name;
  6139. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6140. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6141. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  6142. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6143. return name
  6144. }
  6145. // Look up the name of a key as indicated by an event object.
  6146. function keyName(event, noShift) {
  6147. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6148. var name = keyNames[event.keyCode];
  6149. if (name == null || event.altGraphKey) { return false }
  6150. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6151. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6152. if (event.keyCode == 3 && event.code) { name = event.code; }
  6153. return addModifierNames(name, event, noShift)
  6154. }
  6155. function getKeyMap(val) {
  6156. return typeof val == "string" ? keyMap[val] : val
  6157. }
  6158. // Helper for deleting text near the selection(s), used to implement
  6159. // backspace, delete, and similar functionality.
  6160. function deleteNearSelection(cm, compute) {
  6161. var ranges = cm.doc.sel.ranges, kill = [];
  6162. // Build up a set of ranges to kill first, merging overlapping
  6163. // ranges.
  6164. for (var i = 0; i < ranges.length; i++) {
  6165. var toKill = compute(ranges[i]);
  6166. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6167. var replaced = kill.pop();
  6168. if (cmp(replaced.from, toKill.from) < 0) {
  6169. toKill.from = replaced.from;
  6170. break
  6171. }
  6172. }
  6173. kill.push(toKill);
  6174. }
  6175. // Next, remove those actual ranges.
  6176. runInOp(cm, function () {
  6177. for (var i = kill.length - 1; i >= 0; i--)
  6178. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6179. ensureCursorVisible(cm);
  6180. });
  6181. }
  6182. function moveCharLogically(line, ch, dir) {
  6183. var target = skipExtendingChars(line.text, ch + dir, dir);
  6184. return target < 0 || target > line.text.length ? null : target
  6185. }
  6186. function moveLogically(line, start, dir) {
  6187. var ch = moveCharLogically(line, start.ch, dir);
  6188. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6189. }
  6190. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6191. if (visually) {
  6192. if (cm.doc.direction == "rtl") { dir = -dir; }
  6193. var order = getOrder(lineObj, cm.doc.direction);
  6194. if (order) {
  6195. var part = dir < 0 ? lst(order) : order[0];
  6196. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6197. var sticky = moveInStorageOrder ? "after" : "before";
  6198. var ch;
  6199. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6200. // it could be that the last bidi part is not on the last visual line,
  6201. // since visual lines contain content order-consecutive chunks.
  6202. // Thus, in rtl, we are looking for the first (content-order) character
  6203. // in the rtl chunk that is on the last line (that is, the same line
  6204. // as the last (content-order) character).
  6205. if (part.level > 0 || cm.doc.direction == "rtl") {
  6206. var prep = prepareMeasureForLine(cm, lineObj);
  6207. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6208. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6209. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6210. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6211. } else { ch = dir < 0 ? part.to : part.from; }
  6212. return new Pos(lineNo, ch, sticky)
  6213. }
  6214. }
  6215. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6216. }
  6217. function moveVisually(cm, line, start, dir) {
  6218. var bidi = getOrder(line, cm.doc.direction);
  6219. if (!bidi) { return moveLogically(line, start, dir) }
  6220. if (start.ch >= line.text.length) {
  6221. start.ch = line.text.length;
  6222. start.sticky = "before";
  6223. } else if (start.ch <= 0) {
  6224. start.ch = 0;
  6225. start.sticky = "after";
  6226. }
  6227. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6228. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6229. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6230. // nothing interesting happens.
  6231. return moveLogically(line, start, dir)
  6232. }
  6233. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6234. var prep;
  6235. var getWrappedLineExtent = function (ch) {
  6236. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6237. prep = prep || prepareMeasureForLine(cm, line);
  6238. return wrappedLineExtentChar(cm, line, prep, ch)
  6239. };
  6240. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6241. if (cm.doc.direction == "rtl" || part.level == 1) {
  6242. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6243. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6244. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6245. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6246. var sticky = moveInStorageOrder ? "before" : "after";
  6247. return new Pos(start.line, ch, sticky)
  6248. }
  6249. }
  6250. // Case 3: Could not move within this bidi part in this visual line, so leave
  6251. // the current bidi part
  6252. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6253. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6254. ? new Pos(start.line, mv(ch, 1), "before")
  6255. : new Pos(start.line, ch, "after"); };
  6256. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6257. var part = bidi[partPos];
  6258. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6259. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6260. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6261. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6262. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6263. }
  6264. };
  6265. // Case 3a: Look for other bidi parts on the same visual line
  6266. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6267. if (res) { return res }
  6268. // Case 3b: Look for other bidi parts on the next visual line
  6269. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6270. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6271. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6272. if (res) { return res }
  6273. }
  6274. // Case 4: Nowhere to move
  6275. return null
  6276. }
  6277. // Commands are parameter-less actions that can be performed on an
  6278. // editor, mostly used for keybindings.
  6279. var commands = {
  6280. selectAll: selectAll,
  6281. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6282. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6283. if (range.empty()) {
  6284. var len = getLine(cm.doc, range.head.line).text.length;
  6285. if (range.head.ch == len && range.head.line < cm.lastLine())
  6286. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6287. else
  6288. { return {from: range.head, to: Pos(range.head.line, len)} }
  6289. } else {
  6290. return {from: range.from(), to: range.to()}
  6291. }
  6292. }); },
  6293. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6294. from: Pos(range.from().line, 0),
  6295. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6296. }); }); },
  6297. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6298. from: Pos(range.from().line, 0), to: range.from()
  6299. }); }); },
  6300. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6301. var top = cm.charCoords(range.head, "div").top + 5;
  6302. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6303. return {from: leftPos, to: range.from()}
  6304. }); },
  6305. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6306. var top = cm.charCoords(range.head, "div").top + 5;
  6307. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6308. return {from: range.from(), to: rightPos }
  6309. }); },
  6310. undo: function (cm) { return cm.undo(); },
  6311. redo: function (cm) { return cm.redo(); },
  6312. undoSelection: function (cm) { return cm.undoSelection(); },
  6313. redoSelection: function (cm) { return cm.redoSelection(); },
  6314. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6315. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6316. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6317. {origin: "+move", bias: 1}
  6318. ); },
  6319. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6320. {origin: "+move", bias: 1}
  6321. ); },
  6322. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6323. {origin: "+move", bias: -1}
  6324. ); },
  6325. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6326. var top = cm.cursorCoords(range.head, "div").top + 5;
  6327. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6328. }, sel_move); },
  6329. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6330. var top = cm.cursorCoords(range.head, "div").top + 5;
  6331. return cm.coordsChar({left: 0, top: top}, "div")
  6332. }, sel_move); },
  6333. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6334. var top = cm.cursorCoords(range.head, "div").top + 5;
  6335. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6336. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6337. return pos
  6338. }, sel_move); },
  6339. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6340. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6341. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6342. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6343. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6344. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6345. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6346. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6347. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6348. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6349. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6350. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6351. delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  6352. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6353. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6354. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6355. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6356. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6357. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6358. indentMore: function (cm) { return cm.indentSelection("add"); },
  6359. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6360. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6361. insertSoftTab: function (cm) {
  6362. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6363. for (var i = 0; i < ranges.length; i++) {
  6364. var pos = ranges[i].from();
  6365. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6366. spaces.push(spaceStr(tabSize - col % tabSize));
  6367. }
  6368. cm.replaceSelections(spaces);
  6369. },
  6370. defaultTab: function (cm) {
  6371. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6372. else { cm.execCommand("insertTab"); }
  6373. },
  6374. // Swap the two chars left and right of each selection's head.
  6375. // Move cursor behind the two swapped characters afterwards.
  6376. //
  6377. // Doesn't consider line feeds a character.
  6378. // Doesn't scan more than one line above to find a character.
  6379. // Doesn't do anything on an empty line.
  6380. // Doesn't do anything with non-empty selections.
  6381. transposeChars: function (cm) { return runInOp(cm, function () {
  6382. var ranges = cm.listSelections(), newSel = [];
  6383. for (var i = 0; i < ranges.length; i++) {
  6384. if (!ranges[i].empty()) { continue }
  6385. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6386. if (line) {
  6387. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6388. if (cur.ch > 0) {
  6389. cur = new Pos(cur.line, cur.ch + 1);
  6390. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6391. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6392. } else if (cur.line > cm.doc.first) {
  6393. var prev = getLine(cm.doc, cur.line - 1).text;
  6394. if (prev) {
  6395. cur = new Pos(cur.line, 1);
  6396. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6397. prev.charAt(prev.length - 1),
  6398. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6399. }
  6400. }
  6401. }
  6402. newSel.push(new Range(cur, cur));
  6403. }
  6404. cm.setSelections(newSel);
  6405. }); },
  6406. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6407. var sels = cm.listSelections();
  6408. for (var i = sels.length - 1; i >= 0; i--)
  6409. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6410. sels = cm.listSelections();
  6411. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6412. { cm.indentLine(sels[i$1].from().line, null, true); }
  6413. ensureCursorVisible(cm);
  6414. }); },
  6415. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6416. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6417. };
  6418. function lineStart(cm, lineN) {
  6419. var line = getLine(cm.doc, lineN);
  6420. var visual = visualLine(line);
  6421. if (visual != line) { lineN = lineNo(visual); }
  6422. return endOfLine(true, cm, visual, lineN, 1)
  6423. }
  6424. function lineEnd(cm, lineN) {
  6425. var line = getLine(cm.doc, lineN);
  6426. var visual = visualLineEnd(line);
  6427. if (visual != line) { lineN = lineNo(visual); }
  6428. return endOfLine(true, cm, line, lineN, -1)
  6429. }
  6430. function lineStartSmart(cm, pos) {
  6431. var start = lineStart(cm, pos.line);
  6432. var line = getLine(cm.doc, start.line);
  6433. var order = getOrder(line, cm.doc.direction);
  6434. if (!order || order[0].level == 0) {
  6435. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  6436. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6437. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6438. }
  6439. return start
  6440. }
  6441. // Run a handler that was bound to a key.
  6442. function doHandleBinding(cm, bound, dropShift) {
  6443. if (typeof bound == "string") {
  6444. bound = commands[bound];
  6445. if (!bound) { return false }
  6446. }
  6447. // Ensure previous input has been read, so that the handler sees a
  6448. // consistent view of the document
  6449. cm.display.input.ensurePolled();
  6450. var prevShift = cm.display.shift, done = false;
  6451. try {
  6452. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6453. if (dropShift) { cm.display.shift = false; }
  6454. done = bound(cm) != Pass;
  6455. } finally {
  6456. cm.display.shift = prevShift;
  6457. cm.state.suppressEdits = false;
  6458. }
  6459. return done
  6460. }
  6461. function lookupKeyForEditor(cm, name, handle) {
  6462. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6463. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6464. if (result) { return result }
  6465. }
  6466. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6467. || lookupKey(name, cm.options.keyMap, handle, cm)
  6468. }
  6469. // Note that, despite the name, this function is also used to check
  6470. // for bound mouse clicks.
  6471. var stopSeq = new Delayed;
  6472. function dispatchKey(cm, name, e, handle) {
  6473. var seq = cm.state.keySeq;
  6474. if (seq) {
  6475. if (isModifierKey(name)) { return "handled" }
  6476. if (/\'$/.test(name))
  6477. { cm.state.keySeq = null; }
  6478. else
  6479. { stopSeq.set(50, function () {
  6480. if (cm.state.keySeq == seq) {
  6481. cm.state.keySeq = null;
  6482. cm.display.input.reset();
  6483. }
  6484. }); }
  6485. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6486. }
  6487. return dispatchKeyInner(cm, name, e, handle)
  6488. }
  6489. function dispatchKeyInner(cm, name, e, handle) {
  6490. var result = lookupKeyForEditor(cm, name, handle);
  6491. if (result == "multi")
  6492. { cm.state.keySeq = name; }
  6493. if (result == "handled")
  6494. { signalLater(cm, "keyHandled", cm, name, e); }
  6495. if (result == "handled" || result == "multi") {
  6496. e_preventDefault(e);
  6497. restartBlink(cm);
  6498. }
  6499. return !!result
  6500. }
  6501. // Handle a key from the keydown event.
  6502. function handleKeyBinding(cm, e) {
  6503. var name = keyName(e, true);
  6504. if (!name) { return false }
  6505. if (e.shiftKey && !cm.state.keySeq) {
  6506. // First try to resolve full name (including 'Shift-'). Failing
  6507. // that, see if there is a cursor-motion command (starting with
  6508. // 'go') bound to the keyname without 'Shift-'.
  6509. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6510. || dispatchKey(cm, name, e, function (b) {
  6511. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6512. { return doHandleBinding(cm, b) }
  6513. })
  6514. } else {
  6515. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6516. }
  6517. }
  6518. // Handle a key from the keypress event
  6519. function handleCharBinding(cm, e, ch) {
  6520. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6521. }
  6522. var lastStoppedKey = null;
  6523. function onKeyDown(e) {
  6524. var cm = this;
  6525. if (e.target && e.target != cm.display.input.getField()) { return }
  6526. cm.curOp.focus = activeElt();
  6527. if (signalDOMEvent(cm, e)) { return }
  6528. // IE does strange things with escape.
  6529. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6530. var code = e.keyCode;
  6531. cm.display.shift = code == 16 || e.shiftKey;
  6532. var handled = handleKeyBinding(cm, e);
  6533. if (presto) {
  6534. lastStoppedKey = handled ? code : null;
  6535. // Opera has no cut event... we try to at least catch the key combo
  6536. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6537. { cm.replaceSelection("", null, "cut"); }
  6538. }
  6539. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  6540. { document.execCommand("cut"); }
  6541. // Turn mouse into crosshair when Alt is held on Mac.
  6542. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6543. { showCrossHair(cm); }
  6544. }
  6545. function showCrossHair(cm) {
  6546. var lineDiv = cm.display.lineDiv;
  6547. addClass(lineDiv, "CodeMirror-crosshair");
  6548. function up(e) {
  6549. if (e.keyCode == 18 || !e.altKey) {
  6550. rmClass(lineDiv, "CodeMirror-crosshair");
  6551. off(document, "keyup", up);
  6552. off(document, "mouseover", up);
  6553. }
  6554. }
  6555. on(document, "keyup", up);
  6556. on(document, "mouseover", up);
  6557. }
  6558. function onKeyUp(e) {
  6559. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6560. signalDOMEvent(this, e);
  6561. }
  6562. function onKeyPress(e) {
  6563. var cm = this;
  6564. if (e.target && e.target != cm.display.input.getField()) { return }
  6565. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6566. var keyCode = e.keyCode, charCode = e.charCode;
  6567. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6568. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6569. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6570. // Some browsers fire keypress events for backspace
  6571. if (ch == "\x08") { return }
  6572. if (handleCharBinding(cm, e, ch)) { return }
  6573. cm.display.input.onKeyPress(e);
  6574. }
  6575. var DOUBLECLICK_DELAY = 400;
  6576. var PastClick = function(time, pos, button) {
  6577. this.time = time;
  6578. this.pos = pos;
  6579. this.button = button;
  6580. };
  6581. PastClick.prototype.compare = function (time, pos, button) {
  6582. return this.time + DOUBLECLICK_DELAY > time &&
  6583. cmp(pos, this.pos) == 0 && button == this.button
  6584. };
  6585. var lastClick, lastDoubleClick;
  6586. function clickRepeat(pos, button) {
  6587. var now = +new Date;
  6588. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6589. lastClick = lastDoubleClick = null;
  6590. return "triple"
  6591. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6592. lastDoubleClick = new PastClick(now, pos, button);
  6593. lastClick = null;
  6594. return "double"
  6595. } else {
  6596. lastClick = new PastClick(now, pos, button);
  6597. lastDoubleClick = null;
  6598. return "single"
  6599. }
  6600. }
  6601. // A mouse down can be a single click, double click, triple click,
  6602. // start of selection drag, start of text drag, new cursor
  6603. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6604. // middle-click-paste. Or it might be a click on something we should
  6605. // not interfere with, such as a scrollbar or widget.
  6606. function onMouseDown(e) {
  6607. var cm = this, display = cm.display;
  6608. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6609. display.input.ensurePolled();
  6610. display.shift = e.shiftKey;
  6611. if (eventInWidget(display, e)) {
  6612. if (!webkit) {
  6613. // Briefly turn off draggability, to allow widgets to do
  6614. // normal dragging things.
  6615. display.scroller.draggable = false;
  6616. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6617. }
  6618. return
  6619. }
  6620. if (clickInGutter(cm, e)) { return }
  6621. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6622. window.focus();
  6623. // #3261: make sure, that we're not starting a second selection
  6624. if (button == 1 && cm.state.selectingText)
  6625. { cm.state.selectingText(e); }
  6626. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6627. if (button == 1) {
  6628. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6629. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6630. } else if (button == 2) {
  6631. if (pos) { extendSelection(cm.doc, pos); }
  6632. setTimeout(function () { return display.input.focus(); }, 20);
  6633. } else if (button == 3) {
  6634. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6635. else { delayBlurEvent(cm); }
  6636. }
  6637. }
  6638. function handleMappedButton(cm, button, pos, repeat, event) {
  6639. var name = "Click";
  6640. if (repeat == "double") { name = "Double" + name; }
  6641. else if (repeat == "triple") { name = "Triple" + name; }
  6642. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6643. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6644. if (typeof bound == "string") { bound = commands[bound]; }
  6645. if (!bound) { return false }
  6646. var done = false;
  6647. try {
  6648. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6649. done = bound(cm, pos) != Pass;
  6650. } finally {
  6651. cm.state.suppressEdits = false;
  6652. }
  6653. return done
  6654. })
  6655. }
  6656. function configureMouse(cm, repeat, event) {
  6657. var option = cm.getOption("configureMouse");
  6658. var value = option ? option(cm, repeat, event) : {};
  6659. if (value.unit == null) {
  6660. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6661. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6662. }
  6663. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6664. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6665. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6666. return value
  6667. }
  6668. function leftButtonDown(cm, pos, repeat, event) {
  6669. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6670. else { cm.curOp.focus = activeElt(); }
  6671. var behavior = configureMouse(cm, repeat, event);
  6672. var sel = cm.doc.sel, contained;
  6673. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6674. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6675. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6676. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6677. { leftButtonStartDrag(cm, event, pos, behavior); }
  6678. else
  6679. { leftButtonSelect(cm, event, pos, behavior); }
  6680. }
  6681. // Start a text drag. When it ends, see if any dragging actually
  6682. // happen, and treat as a click if it didn't.
  6683. function leftButtonStartDrag(cm, event, pos, behavior) {
  6684. var display = cm.display, moved = false;
  6685. var dragEnd = operation(cm, function (e) {
  6686. if (webkit) { display.scroller.draggable = false; }
  6687. cm.state.draggingText = false;
  6688. if (cm.state.delayingBlurEvent) {
  6689. if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  6690. else { delayBlurEvent(cm); }
  6691. }
  6692. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6693. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6694. off(display.scroller, "dragstart", dragStart);
  6695. off(display.scroller, "drop", dragEnd);
  6696. if (!moved) {
  6697. e_preventDefault(e);
  6698. if (!behavior.addNew)
  6699. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6700. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6701. if ((webkit && !safari) || ie && ie_version == 9)
  6702. { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  6703. else
  6704. { display.input.focus(); }
  6705. }
  6706. });
  6707. var mouseMove = function(e2) {
  6708. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6709. };
  6710. var dragStart = function () { return moved = true; };
  6711. // Let the drag handler handle this.
  6712. if (webkit) { display.scroller.draggable = true; }
  6713. cm.state.draggingText = dragEnd;
  6714. dragEnd.copy = !behavior.moveOnDrag;
  6715. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6716. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6717. on(display.scroller, "dragstart", dragStart);
  6718. on(display.scroller, "drop", dragEnd);
  6719. cm.state.delayingBlurEvent = true;
  6720. setTimeout(function () { return display.input.focus(); }, 20);
  6721. // IE's approach to draggable
  6722. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6723. }
  6724. function rangeForUnit(cm, pos, unit) {
  6725. if (unit == "char") { return new Range(pos, pos) }
  6726. if (unit == "word") { return cm.findWordAt(pos) }
  6727. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6728. var result = unit(cm, pos);
  6729. return new Range(result.from, result.to)
  6730. }
  6731. // Normal selection, as opposed to text dragging.
  6732. function leftButtonSelect(cm, event, start, behavior) {
  6733. if (ie) { delayBlurEvent(cm); }
  6734. var display = cm.display, doc = cm.doc;
  6735. e_preventDefault(event);
  6736. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6737. if (behavior.addNew && !behavior.extend) {
  6738. ourIndex = doc.sel.contains(start);
  6739. if (ourIndex > -1)
  6740. { ourRange = ranges[ourIndex]; }
  6741. else
  6742. { ourRange = new Range(start, start); }
  6743. } else {
  6744. ourRange = doc.sel.primary();
  6745. ourIndex = doc.sel.primIndex;
  6746. }
  6747. if (behavior.unit == "rectangle") {
  6748. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6749. start = posFromMouse(cm, event, true, true);
  6750. ourIndex = -1;
  6751. } else {
  6752. var range = rangeForUnit(cm, start, behavior.unit);
  6753. if (behavior.extend)
  6754. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  6755. else
  6756. { ourRange = range; }
  6757. }
  6758. if (!behavior.addNew) {
  6759. ourIndex = 0;
  6760. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6761. startSel = doc.sel;
  6762. } else if (ourIndex == -1) {
  6763. ourIndex = ranges.length;
  6764. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  6765. {scroll: false, origin: "*mouse"});
  6766. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6767. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6768. {scroll: false, origin: "*mouse"});
  6769. startSel = doc.sel;
  6770. } else {
  6771. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6772. }
  6773. var lastPos = start;
  6774. function extendTo(pos) {
  6775. if (cmp(lastPos, pos) == 0) { return }
  6776. lastPos = pos;
  6777. if (behavior.unit == "rectangle") {
  6778. var ranges = [], tabSize = cm.options.tabSize;
  6779. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6780. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6781. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6782. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6783. line <= end; line++) {
  6784. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6785. if (left == right)
  6786. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6787. else if (text.length > leftPos)
  6788. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6789. }
  6790. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6791. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6792. {origin: "*mouse", scroll: false});
  6793. cm.scrollIntoView(pos);
  6794. } else {
  6795. var oldRange = ourRange;
  6796. var range = rangeForUnit(cm, pos, behavior.unit);
  6797. var anchor = oldRange.anchor, head;
  6798. if (cmp(range.anchor, anchor) > 0) {
  6799. head = range.head;
  6800. anchor = minPos(oldRange.from(), range.anchor);
  6801. } else {
  6802. head = range.anchor;
  6803. anchor = maxPos(oldRange.to(), range.head);
  6804. }
  6805. var ranges$1 = startSel.ranges.slice(0);
  6806. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  6807. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  6808. }
  6809. }
  6810. var editorSize = display.wrapper.getBoundingClientRect();
  6811. // Used to ensure timeout re-tries don't fire when another extend
  6812. // happened in the meantime (clearTimeout isn't reliable -- at
  6813. // least on Chrome, the timeouts still happen even when cleared,
  6814. // if the clear happens after their scheduled firing time).
  6815. var counter = 0;
  6816. function extend(e) {
  6817. var curCount = ++counter;
  6818. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6819. if (!cur) { return }
  6820. if (cmp(cur, lastPos) != 0) {
  6821. cm.curOp.focus = activeElt();
  6822. extendTo(cur);
  6823. var visible = visibleLines(display, doc);
  6824. if (cur.line >= visible.to || cur.line < visible.from)
  6825. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6826. } else {
  6827. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6828. if (outside) { setTimeout(operation(cm, function () {
  6829. if (counter != curCount) { return }
  6830. display.scroller.scrollTop += outside;
  6831. extend(e);
  6832. }), 50); }
  6833. }
  6834. }
  6835. function done(e) {
  6836. cm.state.selectingText = false;
  6837. counter = Infinity;
  6838. // If e is null or undefined we interpret this as someone trying
  6839. // to explicitly cancel the selection rather than the user
  6840. // letting go of the mouse button.
  6841. if (e) {
  6842. e_preventDefault(e);
  6843. display.input.focus();
  6844. }
  6845. off(display.wrapper.ownerDocument, "mousemove", move);
  6846. off(display.wrapper.ownerDocument, "mouseup", up);
  6847. doc.history.lastSelOrigin = null;
  6848. }
  6849. var move = operation(cm, function (e) {
  6850. if (e.buttons === 0 || !e_button(e)) { done(e); }
  6851. else { extend(e); }
  6852. });
  6853. var up = operation(cm, done);
  6854. cm.state.selectingText = up;
  6855. on(display.wrapper.ownerDocument, "mousemove", move);
  6856. on(display.wrapper.ownerDocument, "mouseup", up);
  6857. }
  6858. // Used when mouse-selecting to adjust the anchor to the proper side
  6859. // of a bidi jump depending on the visual position of the head.
  6860. function bidiSimplify(cm, range) {
  6861. var anchor = range.anchor;
  6862. var head = range.head;
  6863. var anchorLine = getLine(cm.doc, anchor.line);
  6864. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6865. var order = getOrder(anchorLine);
  6866. if (!order) { return range }
  6867. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6868. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6869. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6870. if (boundary == 0 || boundary == order.length) { return range }
  6871. // Compute the relative visual position of the head compared to the
  6872. // anchor (<0 is to the left, >0 to the right)
  6873. var leftSide;
  6874. if (head.line != anchor.line) {
  6875. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6876. } else {
  6877. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6878. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6879. if (headIndex == boundary - 1 || headIndex == boundary)
  6880. { leftSide = dir < 0; }
  6881. else
  6882. { leftSide = dir > 0; }
  6883. }
  6884. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6885. var from = leftSide == (usePart.level == 1);
  6886. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6887. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6888. }
  6889. // Determines whether an event happened in the gutter, and fires the
  6890. // handlers for the corresponding event.
  6891. function gutterEvent(cm, e, type, prevent) {
  6892. var mX, mY;
  6893. if (e.touches) {
  6894. mX = e.touches[0].clientX;
  6895. mY = e.touches[0].clientY;
  6896. } else {
  6897. try { mX = e.clientX; mY = e.clientY; }
  6898. catch(e$1) { return false }
  6899. }
  6900. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6901. if (prevent) { e_preventDefault(e); }
  6902. var display = cm.display;
  6903. var lineBox = display.lineDiv.getBoundingClientRect();
  6904. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6905. mY -= lineBox.top - display.viewOffset;
  6906. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  6907. var g = display.gutters.childNodes[i];
  6908. if (g && g.getBoundingClientRect().right >= mX) {
  6909. var line = lineAtHeight(cm.doc, mY);
  6910. var gutter = cm.display.gutterSpecs[i];
  6911. signal(cm, type, cm, line, gutter.className, e);
  6912. return e_defaultPrevented(e)
  6913. }
  6914. }
  6915. }
  6916. function clickInGutter(cm, e) {
  6917. return gutterEvent(cm, e, "gutterClick", true)
  6918. }
  6919. // CONTEXT MENU HANDLING
  6920. // To make the context menu work, we need to briefly unhide the
  6921. // textarea (making it as unobtrusive as possible) to let the
  6922. // right-click take effect on it.
  6923. function onContextMenu(cm, e) {
  6924. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6925. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6926. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  6927. }
  6928. function contextMenuInGutter(cm, e) {
  6929. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6930. return gutterEvent(cm, e, "gutterContextMenu", false)
  6931. }
  6932. function themeChanged(cm) {
  6933. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6934. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6935. clearCaches(cm);
  6936. }
  6937. var Init = {toString: function(){return "CodeMirror.Init"}};
  6938. var defaults = {};
  6939. var optionHandlers = {};
  6940. function defineOptions(CodeMirror) {
  6941. var optionHandlers = CodeMirror.optionHandlers;
  6942. function option(name, deflt, handle, notOnInit) {
  6943. CodeMirror.defaults[name] = deflt;
  6944. if (handle) { optionHandlers[name] =
  6945. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  6946. }
  6947. CodeMirror.defineOption = option;
  6948. // Passed to option handlers when there is no old value.
  6949. CodeMirror.Init = Init;
  6950. // These two are, on init, called from the constructor because they
  6951. // have to be initialized before the editor can start at all.
  6952. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  6953. option("mode", null, function (cm, val) {
  6954. cm.doc.modeOption = val;
  6955. loadMode(cm);
  6956. }, true);
  6957. option("indentUnit", 2, loadMode, true);
  6958. option("indentWithTabs", false);
  6959. option("smartIndent", true);
  6960. option("tabSize", 4, function (cm) {
  6961. resetModeState(cm);
  6962. clearCaches(cm);
  6963. regChange(cm);
  6964. }, true);
  6965. option("lineSeparator", null, function (cm, val) {
  6966. cm.doc.lineSep = val;
  6967. if (!val) { return }
  6968. var newBreaks = [], lineNo = cm.doc.first;
  6969. cm.doc.iter(function (line) {
  6970. for (var pos = 0;;) {
  6971. var found = line.text.indexOf(val, pos);
  6972. if (found == -1) { break }
  6973. pos = found + val.length;
  6974. newBreaks.push(Pos(lineNo, found));
  6975. }
  6976. lineNo++;
  6977. });
  6978. for (var i = newBreaks.length - 1; i >= 0; i--)
  6979. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  6980. });
  6981. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  6982. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6983. if (old != Init) { cm.refresh(); }
  6984. });
  6985. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  6986. option("electricChars", true);
  6987. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6988. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6989. }, true);
  6990. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  6991. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  6992. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  6993. option("rtlMoveVisually", !windows);
  6994. option("wholeLineUpdateBefore", true);
  6995. option("theme", "default", function (cm) {
  6996. themeChanged(cm);
  6997. updateGutters(cm);
  6998. }, true);
  6999. option("keyMap", "default", function (cm, val, old) {
  7000. var next = getKeyMap(val);
  7001. var prev = old != Init && getKeyMap(old);
  7002. if (prev && prev.detach) { prev.detach(cm, next); }
  7003. if (next.attach) { next.attach(cm, prev || null); }
  7004. });
  7005. option("extraKeys", null);
  7006. option("configureMouse", null);
  7007. option("lineWrapping", false, wrappingChanged, true);
  7008. option("gutters", [], function (cm, val) {
  7009. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7010. updateGutters(cm);
  7011. }, true);
  7012. option("fixedGutter", true, function (cm, val) {
  7013. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7014. cm.refresh();
  7015. }, true);
  7016. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7017. option("scrollbarStyle", "native", function (cm) {
  7018. initScrollbars(cm);
  7019. updateScrollbars(cm);
  7020. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7021. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7022. }, true);
  7023. option("lineNumbers", false, function (cm, val) {
  7024. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7025. updateGutters(cm);
  7026. }, true);
  7027. option("firstLineNumber", 1, updateGutters, true);
  7028. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7029. option("showCursorWhenSelecting", false, updateSelection, true);
  7030. option("resetSelectionOnContextMenu", true);
  7031. option("lineWiseCopyCut", true);
  7032. option("pasteLinesPerSelection", true);
  7033. option("selectionsMayTouch", false);
  7034. option("readOnly", false, function (cm, val) {
  7035. if (val == "nocursor") {
  7036. onBlur(cm);
  7037. cm.display.input.blur();
  7038. }
  7039. cm.display.input.readOnlyChanged(val);
  7040. });
  7041. option("screenReaderLabel", null, function (cm, val) {
  7042. val = (val === '') ? null : val;
  7043. cm.display.input.screenReaderLabelChanged(val);
  7044. });
  7045. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7046. option("dragDrop", true, dragDropChanged);
  7047. option("allowDropFileTypes", null);
  7048. option("cursorBlinkRate", 530);
  7049. option("cursorScrollMargin", 0);
  7050. option("cursorHeight", 1, updateSelection, true);
  7051. option("singleCursorHeightPerLine", true, updateSelection, true);
  7052. option("workTime", 100);
  7053. option("workDelay", 100);
  7054. option("flattenSpans", true, resetModeState, true);
  7055. option("addModeClass", false, resetModeState, true);
  7056. option("pollInterval", 100);
  7057. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7058. option("historyEventDelay", 1250);
  7059. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7060. option("maxHighlightLength", 10000, resetModeState, true);
  7061. option("moveInputWithCursor", true, function (cm, val) {
  7062. if (!val) { cm.display.input.resetPosition(); }
  7063. });
  7064. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7065. option("autofocus", null);
  7066. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7067. option("phrases", null);
  7068. }
  7069. function dragDropChanged(cm, value, old) {
  7070. var wasOn = old && old != Init;
  7071. if (!value != !wasOn) {
  7072. var funcs = cm.display.dragFunctions;
  7073. var toggle = value ? on : off;
  7074. toggle(cm.display.scroller, "dragstart", funcs.start);
  7075. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7076. toggle(cm.display.scroller, "dragover", funcs.over);
  7077. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7078. toggle(cm.display.scroller, "drop", funcs.drop);
  7079. }
  7080. }
  7081. function wrappingChanged(cm) {
  7082. if (cm.options.lineWrapping) {
  7083. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7084. cm.display.sizer.style.minWidth = "";
  7085. cm.display.sizerWidth = null;
  7086. } else {
  7087. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7088. findMaxLine(cm);
  7089. }
  7090. estimateLineHeights(cm);
  7091. regChange(cm);
  7092. clearCaches(cm);
  7093. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7094. }
  7095. // A CodeMirror instance represents an editor. This is the object
  7096. // that user code is usually dealing with.
  7097. function CodeMirror(place, options) {
  7098. var this$1 = this;
  7099. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7100. this.options = options = options ? copyObj(options) : {};
  7101. // Determine effective options based on given values and defaults.
  7102. copyObj(defaults, options, false);
  7103. var doc = options.value;
  7104. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7105. else if (options.mode) { doc.modeOption = options.mode; }
  7106. this.doc = doc;
  7107. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7108. var display = this.display = new Display(place, doc, input, options);
  7109. display.wrapper.CodeMirror = this;
  7110. themeChanged(this);
  7111. if (options.lineWrapping)
  7112. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7113. initScrollbars(this);
  7114. this.state = {
  7115. keyMaps: [], // stores maps added by addKeyMap
  7116. overlays: [], // highlighting overlays, as added by addOverlay
  7117. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7118. overwrite: false,
  7119. delayingBlurEvent: false,
  7120. focused: false,
  7121. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7122. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7123. selectingText: false,
  7124. draggingText: false,
  7125. highlight: new Delayed(), // stores highlight worker timeout
  7126. keySeq: null, // Unfinished key sequence
  7127. specialChars: null
  7128. };
  7129. if (options.autofocus && !mobile) { display.input.focus(); }
  7130. // Override magic textarea content restore that IE sometimes does
  7131. // on our hidden textarea on reload
  7132. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7133. registerEventHandlers(this);
  7134. ensureGlobalHandlers();
  7135. startOperation(this);
  7136. this.curOp.forceUpdate = true;
  7137. attachDoc(this, doc);
  7138. if ((options.autofocus && !mobile) || this.hasFocus())
  7139. { setTimeout(function () {
  7140. if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  7141. }, 20); }
  7142. else
  7143. { onBlur(this); }
  7144. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7145. { optionHandlers[opt](this, options[opt], Init); } }
  7146. maybeUpdateLineNumberWidth(this);
  7147. if (options.finishInit) { options.finishInit(this); }
  7148. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7149. endOperation(this);
  7150. // Suppress optimizelegibility in Webkit, since it breaks text
  7151. // measuring on line wrapping boundaries.
  7152. if (webkit && options.lineWrapping &&
  7153. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7154. { display.lineDiv.style.textRendering = "auto"; }
  7155. }
  7156. // The default configuration options.
  7157. CodeMirror.defaults = defaults;
  7158. // Functions to run when options are changed.
  7159. CodeMirror.optionHandlers = optionHandlers;
  7160. // Attach the necessary event handlers when initializing the editor
  7161. function registerEventHandlers(cm) {
  7162. var d = cm.display;
  7163. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7164. // Older IE's will not fire a second mousedown for a double click
  7165. if (ie && ie_version < 11)
  7166. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7167. if (signalDOMEvent(cm, e)) { return }
  7168. var pos = posFromMouse(cm, e);
  7169. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7170. e_preventDefault(e);
  7171. var word = cm.findWordAt(pos);
  7172. extendSelection(cm.doc, word.anchor, word.head);
  7173. })); }
  7174. else
  7175. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7176. // Some browsers fire contextmenu *after* opening the menu, at
  7177. // which point we can't mess with it anymore. Context menu is
  7178. // handled in onMouseDown for these browsers.
  7179. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7180. on(d.input.getField(), "contextmenu", function (e) {
  7181. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7182. });
  7183. // Used to suppress mouse event handling when a touch happens
  7184. var touchFinished, prevTouch = {end: 0};
  7185. function finishTouch() {
  7186. if (d.activeTouch) {
  7187. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7188. prevTouch = d.activeTouch;
  7189. prevTouch.end = +new Date;
  7190. }
  7191. }
  7192. function isMouseLikeTouchEvent(e) {
  7193. if (e.touches.length != 1) { return false }
  7194. var touch = e.touches[0];
  7195. return touch.radiusX <= 1 && touch.radiusY <= 1
  7196. }
  7197. function farAway(touch, other) {
  7198. if (other.left == null) { return true }
  7199. var dx = other.left - touch.left, dy = other.top - touch.top;
  7200. return dx * dx + dy * dy > 20 * 20
  7201. }
  7202. on(d.scroller, "touchstart", function (e) {
  7203. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7204. d.input.ensurePolled();
  7205. clearTimeout(touchFinished);
  7206. var now = +new Date;
  7207. d.activeTouch = {start: now, moved: false,
  7208. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7209. if (e.touches.length == 1) {
  7210. d.activeTouch.left = e.touches[0].pageX;
  7211. d.activeTouch.top = e.touches[0].pageY;
  7212. }
  7213. }
  7214. });
  7215. on(d.scroller, "touchmove", function () {
  7216. if (d.activeTouch) { d.activeTouch.moved = true; }
  7217. });
  7218. on(d.scroller, "touchend", function (e) {
  7219. var touch = d.activeTouch;
  7220. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7221. !touch.moved && new Date - touch.start < 300) {
  7222. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7223. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7224. { range = new Range(pos, pos); }
  7225. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7226. { range = cm.findWordAt(pos); }
  7227. else // Triple tap
  7228. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7229. cm.setSelection(range.anchor, range.head);
  7230. cm.focus();
  7231. e_preventDefault(e);
  7232. }
  7233. finishTouch();
  7234. });
  7235. on(d.scroller, "touchcancel", finishTouch);
  7236. // Sync scrolling between fake scrollbars and real scrollable
  7237. // area, ensure viewport is updated when scrolling.
  7238. on(d.scroller, "scroll", function () {
  7239. if (d.scroller.clientHeight) {
  7240. updateScrollTop(cm, d.scroller.scrollTop);
  7241. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7242. signal(cm, "scroll", cm);
  7243. }
  7244. });
  7245. // Listen to wheel events in order to try and update the viewport on time.
  7246. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7247. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7248. // Prevent wrapper from ever scrolling
  7249. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7250. d.dragFunctions = {
  7251. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7252. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7253. start: function (e) { return onDragStart(cm, e); },
  7254. drop: operation(cm, onDrop),
  7255. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7256. };
  7257. var inp = d.input.getField();
  7258. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7259. on(inp, "keydown", operation(cm, onKeyDown));
  7260. on(inp, "keypress", operation(cm, onKeyPress));
  7261. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7262. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7263. }
  7264. var initHooks = [];
  7265. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7266. // Indent the given line. The how parameter can be "smart",
  7267. // "add"/null, "subtract", or "prev". When aggressive is false
  7268. // (typically set to true for forced single-line indents), empty
  7269. // lines are not indented, and places where the mode returns Pass
  7270. // are left alone.
  7271. function indentLine(cm, n, how, aggressive) {
  7272. var doc = cm.doc, state;
  7273. if (how == null) { how = "add"; }
  7274. if (how == "smart") {
  7275. // Fall back to "prev" when the mode doesn't have an indentation
  7276. // method.
  7277. if (!doc.mode.indent) { how = "prev"; }
  7278. else { state = getContextBefore(cm, n).state; }
  7279. }
  7280. var tabSize = cm.options.tabSize;
  7281. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7282. if (line.stateAfter) { line.stateAfter = null; }
  7283. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7284. if (!aggressive && !/\S/.test(line.text)) {
  7285. indentation = 0;
  7286. how = "not";
  7287. } else if (how == "smart") {
  7288. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7289. if (indentation == Pass || indentation > 150) {
  7290. if (!aggressive) { return }
  7291. how = "prev";
  7292. }
  7293. }
  7294. if (how == "prev") {
  7295. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7296. else { indentation = 0; }
  7297. } else if (how == "add") {
  7298. indentation = curSpace + cm.options.indentUnit;
  7299. } else if (how == "subtract") {
  7300. indentation = curSpace - cm.options.indentUnit;
  7301. } else if (typeof how == "number") {
  7302. indentation = curSpace + how;
  7303. }
  7304. indentation = Math.max(0, indentation);
  7305. var indentString = "", pos = 0;
  7306. if (cm.options.indentWithTabs)
  7307. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7308. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7309. if (indentString != curSpaceString) {
  7310. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7311. line.stateAfter = null;
  7312. return true
  7313. } else {
  7314. // Ensure that, if the cursor was in the whitespace at the start
  7315. // of the line, it is moved to the end of that space.
  7316. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7317. var range = doc.sel.ranges[i$1];
  7318. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7319. var pos$1 = Pos(n, curSpaceString.length);
  7320. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7321. break
  7322. }
  7323. }
  7324. }
  7325. }
  7326. // This will be set to a {lineWise: bool, text: [string]} object, so
  7327. // that, when pasting, we know what kind of selections the copied
  7328. // text was made out of.
  7329. var lastCopied = null;
  7330. function setLastCopied(newLastCopied) {
  7331. lastCopied = newLastCopied;
  7332. }
  7333. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7334. var doc = cm.doc;
  7335. cm.display.shift = false;
  7336. if (!sel) { sel = doc.sel; }
  7337. var recent = +new Date - 200;
  7338. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7339. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7340. // When pasting N lines into N selections, insert one line per selection
  7341. if (paste && sel.ranges.length > 1) {
  7342. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7343. if (sel.ranges.length % lastCopied.text.length == 0) {
  7344. multiPaste = [];
  7345. for (var i = 0; i < lastCopied.text.length; i++)
  7346. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7347. }
  7348. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7349. multiPaste = map(textLines, function (l) { return [l]; });
  7350. }
  7351. }
  7352. var updateInput = cm.curOp.updateInput;
  7353. // Normal behavior is to insert the new text into every selection
  7354. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7355. var range = sel.ranges[i$1];
  7356. var from = range.from(), to = range.to();
  7357. if (range.empty()) {
  7358. if (deleted && deleted > 0) // Handle deletion
  7359. { from = Pos(from.line, from.ch - deleted); }
  7360. else if (cm.state.overwrite && !paste) // Handle overwrite
  7361. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7362. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  7363. { from = to = Pos(from.line, 0); }
  7364. }
  7365. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7366. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  7367. makeChange(cm.doc, changeEvent);
  7368. signalLater(cm, "inputRead", cm, changeEvent);
  7369. }
  7370. if (inserted && !paste)
  7371. { triggerElectric(cm, inserted); }
  7372. ensureCursorVisible(cm);
  7373. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7374. cm.curOp.typing = true;
  7375. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7376. }
  7377. function handlePaste(e, cm) {
  7378. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7379. if (pasted) {
  7380. e.preventDefault();
  7381. if (!cm.isReadOnly() && !cm.options.disableInput)
  7382. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7383. return true
  7384. }
  7385. }
  7386. function triggerElectric(cm, inserted) {
  7387. // When an 'electric' character is inserted, immediately trigger a reindent
  7388. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7389. var sel = cm.doc.sel;
  7390. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7391. var range = sel.ranges[i];
  7392. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7393. var mode = cm.getModeAt(range.head);
  7394. var indented = false;
  7395. if (mode.electricChars) {
  7396. for (var j = 0; j < mode.electricChars.length; j++)
  7397. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7398. indented = indentLine(cm, range.head.line, "smart");
  7399. break
  7400. } }
  7401. } else if (mode.electricInput) {
  7402. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7403. { indented = indentLine(cm, range.head.line, "smart"); }
  7404. }
  7405. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  7406. }
  7407. }
  7408. function copyableRanges(cm) {
  7409. var text = [], ranges = [];
  7410. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7411. var line = cm.doc.sel.ranges[i].head.line;
  7412. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7413. ranges.push(lineRange);
  7414. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7415. }
  7416. return {text: text, ranges: ranges}
  7417. }
  7418. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7419. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  7420. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  7421. field.setAttribute("spellcheck", !!spellcheck);
  7422. }
  7423. function hiddenTextarea() {
  7424. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  7425. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7426. // The textarea is kept positioned near the cursor to prevent the
  7427. // fact that it'll be scrolled into view on input from scrolling
  7428. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7429. // very slow. So make the area wide instead.
  7430. if (webkit) { te.style.width = "1000px"; }
  7431. else { te.setAttribute("wrap", "off"); }
  7432. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7433. if (ios) { te.style.border = "1px solid black"; }
  7434. disableBrowserMagic(te);
  7435. return div
  7436. }
  7437. // The publicly visible API. Note that methodOp(f) means
  7438. // 'wrap f in an operation, performed on its `this` parameter'.
  7439. // This is not the complete set of editor methods. Most of the
  7440. // methods defined on the Doc type are also injected into
  7441. // CodeMirror.prototype, for backwards compatibility and
  7442. // convenience.
  7443. function addEditorMethods(CodeMirror) {
  7444. var optionHandlers = CodeMirror.optionHandlers;
  7445. var helpers = CodeMirror.helpers = {};
  7446. CodeMirror.prototype = {
  7447. constructor: CodeMirror,
  7448. focus: function(){window.focus(); this.display.input.focus();},
  7449. setOption: function(option, value) {
  7450. var options = this.options, old = options[option];
  7451. if (options[option] == value && option != "mode") { return }
  7452. options[option] = value;
  7453. if (optionHandlers.hasOwnProperty(option))
  7454. { operation(this, optionHandlers[option])(this, value, old); }
  7455. signal(this, "optionChange", this, option);
  7456. },
  7457. getOption: function(option) {return this.options[option]},
  7458. getDoc: function() {return this.doc},
  7459. addKeyMap: function(map, bottom) {
  7460. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  7461. },
  7462. removeKeyMap: function(map) {
  7463. var maps = this.state.keyMaps;
  7464. for (var i = 0; i < maps.length; ++i)
  7465. { if (maps[i] == map || maps[i].name == map) {
  7466. maps.splice(i, 1);
  7467. return true
  7468. } }
  7469. },
  7470. addOverlay: methodOp(function(spec, options) {
  7471. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7472. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7473. insertSorted(this.state.overlays,
  7474. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7475. priority: (options && options.priority) || 0},
  7476. function (overlay) { return overlay.priority; });
  7477. this.state.modeGen++;
  7478. regChange(this);
  7479. }),
  7480. removeOverlay: methodOp(function(spec) {
  7481. var overlays = this.state.overlays;
  7482. for (var i = 0; i < overlays.length; ++i) {
  7483. var cur = overlays[i].modeSpec;
  7484. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7485. overlays.splice(i, 1);
  7486. this.state.modeGen++;
  7487. regChange(this);
  7488. return
  7489. }
  7490. }
  7491. }),
  7492. indentLine: methodOp(function(n, dir, aggressive) {
  7493. if (typeof dir != "string" && typeof dir != "number") {
  7494. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7495. else { dir = dir ? "add" : "subtract"; }
  7496. }
  7497. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7498. }),
  7499. indentSelection: methodOp(function(how) {
  7500. var ranges = this.doc.sel.ranges, end = -1;
  7501. for (var i = 0; i < ranges.length; i++) {
  7502. var range = ranges[i];
  7503. if (!range.empty()) {
  7504. var from = range.from(), to = range.to();
  7505. var start = Math.max(end, from.line);
  7506. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7507. for (var j = start; j < end; ++j)
  7508. { indentLine(this, j, how); }
  7509. var newRanges = this.doc.sel.ranges;
  7510. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7511. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7512. } else if (range.head.line > end) {
  7513. indentLine(this, range.head.line, how, true);
  7514. end = range.head.line;
  7515. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  7516. }
  7517. }
  7518. }),
  7519. // Fetch the parser token for a given character. Useful for hacks
  7520. // that want to inspect the mode state (say, for completion).
  7521. getTokenAt: function(pos, precise) {
  7522. return takeToken(this, pos, precise)
  7523. },
  7524. getLineTokens: function(line, precise) {
  7525. return takeToken(this, Pos(line), precise, true)
  7526. },
  7527. getTokenTypeAt: function(pos) {
  7528. pos = clipPos(this.doc, pos);
  7529. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7530. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7531. var type;
  7532. if (ch == 0) { type = styles[2]; }
  7533. else { for (;;) {
  7534. var mid = (before + after) >> 1;
  7535. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7536. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7537. else { type = styles[mid * 2 + 2]; break }
  7538. } }
  7539. var cut = type ? type.indexOf("overlay ") : -1;
  7540. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7541. },
  7542. getModeAt: function(pos) {
  7543. var mode = this.doc.mode;
  7544. if (!mode.innerMode) { return mode }
  7545. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7546. },
  7547. getHelper: function(pos, type) {
  7548. return this.getHelpers(pos, type)[0]
  7549. },
  7550. getHelpers: function(pos, type) {
  7551. var found = [];
  7552. if (!helpers.hasOwnProperty(type)) { return found }
  7553. var help = helpers[type], mode = this.getModeAt(pos);
  7554. if (typeof mode[type] == "string") {
  7555. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7556. } else if (mode[type]) {
  7557. for (var i = 0; i < mode[type].length; i++) {
  7558. var val = help[mode[type][i]];
  7559. if (val) { found.push(val); }
  7560. }
  7561. } else if (mode.helperType && help[mode.helperType]) {
  7562. found.push(help[mode.helperType]);
  7563. } else if (help[mode.name]) {
  7564. found.push(help[mode.name]);
  7565. }
  7566. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7567. var cur = help._global[i$1];
  7568. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  7569. { found.push(cur.val); }
  7570. }
  7571. return found
  7572. },
  7573. getStateAfter: function(line, precise) {
  7574. var doc = this.doc;
  7575. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7576. return getContextBefore(this, line + 1, precise).state
  7577. },
  7578. cursorCoords: function(start, mode) {
  7579. var pos, range = this.doc.sel.primary();
  7580. if (start == null) { pos = range.head; }
  7581. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7582. else { pos = start ? range.from() : range.to(); }
  7583. return cursorCoords(this, pos, mode || "page")
  7584. },
  7585. charCoords: function(pos, mode) {
  7586. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7587. },
  7588. coordsChar: function(coords, mode) {
  7589. coords = fromCoordSystem(this, coords, mode || "page");
  7590. return coordsChar(this, coords.left, coords.top)
  7591. },
  7592. lineAtHeight: function(height, mode) {
  7593. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7594. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7595. },
  7596. heightAtLine: function(line, mode, includeWidgets) {
  7597. var end = false, lineObj;
  7598. if (typeof line == "number") {
  7599. var last = this.doc.first + this.doc.size - 1;
  7600. if (line < this.doc.first) { line = this.doc.first; }
  7601. else if (line > last) { line = last; end = true; }
  7602. lineObj = getLine(this.doc, line);
  7603. } else {
  7604. lineObj = line;
  7605. }
  7606. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7607. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7608. },
  7609. defaultTextHeight: function() { return textHeight(this.display) },
  7610. defaultCharWidth: function() { return charWidth(this.display) },
  7611. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7612. addWidget: function(pos, node, scroll, vert, horiz) {
  7613. var display = this.display;
  7614. pos = cursorCoords(this, clipPos(this.doc, pos));
  7615. var top = pos.bottom, left = pos.left;
  7616. node.style.position = "absolute";
  7617. node.setAttribute("cm-ignore-events", "true");
  7618. this.display.input.setUneditable(node);
  7619. display.sizer.appendChild(node);
  7620. if (vert == "over") {
  7621. top = pos.top;
  7622. } else if (vert == "above" || vert == "near") {
  7623. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7624. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7625. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7626. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7627. { top = pos.top - node.offsetHeight; }
  7628. else if (pos.bottom + node.offsetHeight <= vspace)
  7629. { top = pos.bottom; }
  7630. if (left + node.offsetWidth > hspace)
  7631. { left = hspace - node.offsetWidth; }
  7632. }
  7633. node.style.top = top + "px";
  7634. node.style.left = node.style.right = "";
  7635. if (horiz == "right") {
  7636. left = display.sizer.clientWidth - node.offsetWidth;
  7637. node.style.right = "0px";
  7638. } else {
  7639. if (horiz == "left") { left = 0; }
  7640. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7641. node.style.left = left + "px";
  7642. }
  7643. if (scroll)
  7644. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7645. },
  7646. triggerOnKeyDown: methodOp(onKeyDown),
  7647. triggerOnKeyPress: methodOp(onKeyPress),
  7648. triggerOnKeyUp: onKeyUp,
  7649. triggerOnMouseDown: methodOp(onMouseDown),
  7650. execCommand: function(cmd) {
  7651. if (commands.hasOwnProperty(cmd))
  7652. { return commands[cmd].call(null, this) }
  7653. },
  7654. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7655. findPosH: function(from, amount, unit, visually) {
  7656. var dir = 1;
  7657. if (amount < 0) { dir = -1; amount = -amount; }
  7658. var cur = clipPos(this.doc, from);
  7659. for (var i = 0; i < amount; ++i) {
  7660. cur = findPosH(this.doc, cur, dir, unit, visually);
  7661. if (cur.hitSide) { break }
  7662. }
  7663. return cur
  7664. },
  7665. moveH: methodOp(function(dir, unit) {
  7666. var this$1 = this;
  7667. this.extendSelectionsBy(function (range) {
  7668. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7669. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7670. else
  7671. { return dir < 0 ? range.from() : range.to() }
  7672. }, sel_move);
  7673. }),
  7674. deleteH: methodOp(function(dir, unit) {
  7675. var sel = this.doc.sel, doc = this.doc;
  7676. if (sel.somethingSelected())
  7677. { doc.replaceSelection("", null, "+delete"); }
  7678. else
  7679. { deleteNearSelection(this, function (range) {
  7680. var other = findPosH(doc, range.head, dir, unit, false);
  7681. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7682. }); }
  7683. }),
  7684. findPosV: function(from, amount, unit, goalColumn) {
  7685. var dir = 1, x = goalColumn;
  7686. if (amount < 0) { dir = -1; amount = -amount; }
  7687. var cur = clipPos(this.doc, from);
  7688. for (var i = 0; i < amount; ++i) {
  7689. var coords = cursorCoords(this, cur, "div");
  7690. if (x == null) { x = coords.left; }
  7691. else { coords.left = x; }
  7692. cur = findPosV(this, coords, dir, unit);
  7693. if (cur.hitSide) { break }
  7694. }
  7695. return cur
  7696. },
  7697. moveV: methodOp(function(dir, unit) {
  7698. var this$1 = this;
  7699. var doc = this.doc, goals = [];
  7700. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7701. doc.extendSelectionsBy(function (range) {
  7702. if (collapse)
  7703. { return dir < 0 ? range.from() : range.to() }
  7704. var headPos = cursorCoords(this$1, range.head, "div");
  7705. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  7706. goals.push(headPos.left);
  7707. var pos = findPosV(this$1, headPos, dir, unit);
  7708. if (unit == "page" && range == doc.sel.primary())
  7709. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7710. return pos
  7711. }, sel_move);
  7712. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7713. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7714. }),
  7715. // Find the word at the given position (as returned by coordsChar).
  7716. findWordAt: function(pos) {
  7717. var doc = this.doc, line = getLine(doc, pos.line).text;
  7718. var start = pos.ch, end = pos.ch;
  7719. if (line) {
  7720. var helper = this.getHelper(pos, "wordChars");
  7721. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7722. var startChar = line.charAt(start);
  7723. var check = isWordChar(startChar, helper)
  7724. ? function (ch) { return isWordChar(ch, helper); }
  7725. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7726. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7727. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7728. while (end < line.length && check(line.charAt(end))) { ++end; }
  7729. }
  7730. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7731. },
  7732. toggleOverwrite: function(value) {
  7733. if (value != null && value == this.state.overwrite) { return }
  7734. if (this.state.overwrite = !this.state.overwrite)
  7735. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7736. else
  7737. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7738. signal(this, "overwriteToggle", this, this.state.overwrite);
  7739. },
  7740. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7741. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7742. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7743. getScrollInfo: function() {
  7744. var scroller = this.display.scroller;
  7745. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7746. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7747. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7748. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7749. },
  7750. scrollIntoView: methodOp(function(range, margin) {
  7751. if (range == null) {
  7752. range = {from: this.doc.sel.primary().head, to: null};
  7753. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7754. } else if (typeof range == "number") {
  7755. range = {from: Pos(range, 0), to: null};
  7756. } else if (range.from == null) {
  7757. range = {from: range, to: null};
  7758. }
  7759. if (!range.to) { range.to = range.from; }
  7760. range.margin = margin || 0;
  7761. if (range.from.line != null) {
  7762. scrollToRange(this, range);
  7763. } else {
  7764. scrollToCoordsRange(this, range.from, range.to, range.margin);
  7765. }
  7766. }),
  7767. setSize: methodOp(function(width, height) {
  7768. var this$1 = this;
  7769. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7770. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7771. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7772. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7773. var lineNo = this.display.viewFrom;
  7774. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7775. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7776. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7777. ++lineNo;
  7778. });
  7779. this.curOp.forceUpdate = true;
  7780. signal(this, "refresh", this);
  7781. }),
  7782. operation: function(f){return runInOp(this, f)},
  7783. startOperation: function(){return startOperation(this)},
  7784. endOperation: function(){return endOperation(this)},
  7785. refresh: methodOp(function() {
  7786. var oldHeight = this.display.cachedTextHeight;
  7787. regChange(this);
  7788. this.curOp.forceUpdate = true;
  7789. clearCaches(this);
  7790. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7791. updateGutterSpace(this.display);
  7792. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  7793. { estimateLineHeights(this); }
  7794. signal(this, "refresh", this);
  7795. }),
  7796. swapDoc: methodOp(function(doc) {
  7797. var old = this.doc;
  7798. old.cm = null;
  7799. // Cancel the current text selection if any (#5821)
  7800. if (this.state.selectingText) { this.state.selectingText(); }
  7801. attachDoc(this, doc);
  7802. clearCaches(this);
  7803. this.display.input.reset();
  7804. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7805. this.curOp.forceScroll = true;
  7806. signalLater(this, "swapDoc", this, old);
  7807. return old
  7808. }),
  7809. phrase: function(phraseText) {
  7810. var phrases = this.options.phrases;
  7811. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7812. },
  7813. getInputField: function(){return this.display.input.getField()},
  7814. getWrapperElement: function(){return this.display.wrapper},
  7815. getScrollerElement: function(){return this.display.scroller},
  7816. getGutterElement: function(){return this.display.gutters}
  7817. };
  7818. eventMixin(CodeMirror);
  7819. CodeMirror.registerHelper = function(type, name, value) {
  7820. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7821. helpers[type][name] = value;
  7822. };
  7823. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7824. CodeMirror.registerHelper(type, name, value);
  7825. helpers[type]._global.push({pred: predicate, val: value});
  7826. };
  7827. }
  7828. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7829. // right), unit can be "codepoint", "char", "column" (like char, but
  7830. // doesn't cross line boundaries), "word" (across next word), or
  7831. // "group" (to the start of next group of word or
  7832. // non-word-non-whitespace chars). The visually param controls
  7833. // whether, in right-to-left text, direction 1 means to move towards
  7834. // the next index in the string, or towards the character to the right
  7835. // of the current position. The resulting position will have a
  7836. // hitSide=true property if it reached the end of the document.
  7837. function findPosH(doc, pos, dir, unit, visually) {
  7838. var oldPos = pos;
  7839. var origDir = dir;
  7840. var lineObj = getLine(doc, pos.line);
  7841. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  7842. function findNextLine() {
  7843. var l = pos.line + lineDir;
  7844. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7845. pos = new Pos(l, pos.ch, pos.sticky);
  7846. return lineObj = getLine(doc, l)
  7847. }
  7848. function moveOnce(boundToLine) {
  7849. var next;
  7850. if (unit == "codepoint") {
  7851. var ch = lineObj.text.charCodeAt(pos.ch + (unit > 0 ? 0 : -1));
  7852. if (isNaN(ch)) {
  7853. next = null;
  7854. } else {
  7855. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  7856. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  7857. }
  7858. } else if (visually) {
  7859. next = moveVisually(doc.cm, lineObj, pos, dir);
  7860. } else {
  7861. next = moveLogically(lineObj, pos, dir);
  7862. }
  7863. if (next == null) {
  7864. if (!boundToLine && findNextLine())
  7865. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  7866. else
  7867. { return false }
  7868. } else {
  7869. pos = next;
  7870. }
  7871. return true
  7872. }
  7873. if (unit == "char" || unit == "codepoint") {
  7874. moveOnce();
  7875. } else if (unit == "column") {
  7876. moveOnce(true);
  7877. } else if (unit == "word" || unit == "group") {
  7878. var sawType = null, group = unit == "group";
  7879. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7880. for (var first = true;; first = false) {
  7881. if (dir < 0 && !moveOnce(!first)) { break }
  7882. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7883. var type = isWordChar(cur, helper) ? "w"
  7884. : group && cur == "\n" ? "n"
  7885. : !group || /\s/.test(cur) ? null
  7886. : "p";
  7887. if (group && !first && !type) { type = "s"; }
  7888. if (sawType && sawType != type) {
  7889. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7890. break
  7891. }
  7892. if (type) { sawType = type; }
  7893. if (dir > 0 && !moveOnce(!first)) { break }
  7894. }
  7895. }
  7896. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7897. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7898. return result
  7899. }
  7900. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7901. // "page" or "line". The resulting position will have a hitSide=true
  7902. // property if it reached the end of the document.
  7903. function findPosV(cm, pos, dir, unit) {
  7904. var doc = cm.doc, x = pos.left, y;
  7905. if (unit == "page") {
  7906. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  7907. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7908. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7909. } else if (unit == "line") {
  7910. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7911. }
  7912. var target;
  7913. for (;;) {
  7914. target = coordsChar(cm, x, y);
  7915. if (!target.outside) { break }
  7916. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7917. y += dir * 5;
  7918. }
  7919. return target
  7920. }
  7921. // CONTENTEDITABLE INPUT STYLE
  7922. var ContentEditableInput = function(cm) {
  7923. this.cm = cm;
  7924. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7925. this.polling = new Delayed();
  7926. this.composing = null;
  7927. this.gracePeriod = false;
  7928. this.readDOMTimeout = null;
  7929. };
  7930. ContentEditableInput.prototype.init = function (display) {
  7931. var this$1 = this;
  7932. var input = this, cm = input.cm;
  7933. var div = input.div = display.lineDiv;
  7934. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  7935. function belongsToInput(e) {
  7936. for (var t = e.target; t; t = t.parentNode) {
  7937. if (t == div) { return true }
  7938. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  7939. }
  7940. return false
  7941. }
  7942. on(div, "paste", function (e) {
  7943. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7944. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7945. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  7946. });
  7947. on(div, "compositionstart", function (e) {
  7948. this$1.composing = {data: e.data, done: false};
  7949. });
  7950. on(div, "compositionupdate", function (e) {
  7951. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  7952. });
  7953. on(div, "compositionend", function (e) {
  7954. if (this$1.composing) {
  7955. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  7956. this$1.composing.done = true;
  7957. }
  7958. });
  7959. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  7960. on(div, "input", function () {
  7961. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  7962. });
  7963. function onCopyCut(e) {
  7964. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  7965. if (cm.somethingSelected()) {
  7966. setLastCopied({lineWise: false, text: cm.getSelections()});
  7967. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  7968. } else if (!cm.options.lineWiseCopyCut) {
  7969. return
  7970. } else {
  7971. var ranges = copyableRanges(cm);
  7972. setLastCopied({lineWise: true, text: ranges.text});
  7973. if (e.type == "cut") {
  7974. cm.operation(function () {
  7975. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  7976. cm.replaceSelection("", null, "cut");
  7977. });
  7978. }
  7979. }
  7980. if (e.clipboardData) {
  7981. e.clipboardData.clearData();
  7982. var content = lastCopied.text.join("\n");
  7983. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7984. e.clipboardData.setData("Text", content);
  7985. if (e.clipboardData.getData("Text") == content) {
  7986. e.preventDefault();
  7987. return
  7988. }
  7989. }
  7990. // Old-fashioned briefly-focus-a-textarea hack
  7991. var kludge = hiddenTextarea(), te = kludge.firstChild;
  7992. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  7993. te.value = lastCopied.text.join("\n");
  7994. var hadFocus = document.activeElement;
  7995. selectInput(te);
  7996. setTimeout(function () {
  7997. cm.display.lineSpace.removeChild(kludge);
  7998. hadFocus.focus();
  7999. if (hadFocus == div) { input.showPrimarySelection(); }
  8000. }, 50);
  8001. }
  8002. on(div, "copy", onCopyCut);
  8003. on(div, "cut", onCopyCut);
  8004. };
  8005. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8006. // Label for screenreaders, accessibility
  8007. if(label) {
  8008. this.div.setAttribute('aria-label', label);
  8009. } else {
  8010. this.div.removeAttribute('aria-label');
  8011. }
  8012. };
  8013. ContentEditableInput.prototype.prepareSelection = function () {
  8014. var result = prepareSelection(this.cm, false);
  8015. result.focus = document.activeElement == this.div;
  8016. return result
  8017. };
  8018. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8019. if (!info || !this.cm.display.view.length) { return }
  8020. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8021. this.showMultipleSelections(info);
  8022. };
  8023. ContentEditableInput.prototype.getSelection = function () {
  8024. return this.cm.display.wrapper.ownerDocument.getSelection()
  8025. };
  8026. ContentEditableInput.prototype.showPrimarySelection = function () {
  8027. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8028. var from = prim.from(), to = prim.to();
  8029. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8030. sel.removeAllRanges();
  8031. return
  8032. }
  8033. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8034. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8035. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8036. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8037. cmp(maxPos(curAnchor, curFocus), to) == 0)
  8038. { return }
  8039. var view = cm.display.view;
  8040. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8041. {node: view[0].measure.map[2], offset: 0};
  8042. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8043. if (!end) {
  8044. var measure = view[view.length - 1].measure;
  8045. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8046. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  8047. }
  8048. if (!start || !end) {
  8049. sel.removeAllRanges();
  8050. return
  8051. }
  8052. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8053. try { rng = range(start.node, start.offset, end.offset, end.node); }
  8054. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8055. if (rng) {
  8056. if (!gecko && cm.state.focused) {
  8057. sel.collapse(start.node, start.offset);
  8058. if (!rng.collapsed) {
  8059. sel.removeAllRanges();
  8060. sel.addRange(rng);
  8061. }
  8062. } else {
  8063. sel.removeAllRanges();
  8064. sel.addRange(rng);
  8065. }
  8066. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8067. else if (gecko) { this.startGracePeriod(); }
  8068. }
  8069. this.rememberSelection();
  8070. };
  8071. ContentEditableInput.prototype.startGracePeriod = function () {
  8072. var this$1 = this;
  8073. clearTimeout(this.gracePeriod);
  8074. this.gracePeriod = setTimeout(function () {
  8075. this$1.gracePeriod = false;
  8076. if (this$1.selectionChanged())
  8077. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8078. }, 20);
  8079. };
  8080. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8081. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8082. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8083. };
  8084. ContentEditableInput.prototype.rememberSelection = function () {
  8085. var sel = this.getSelection();
  8086. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8087. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8088. };
  8089. ContentEditableInput.prototype.selectionInEditor = function () {
  8090. var sel = this.getSelection();
  8091. if (!sel.rangeCount) { return false }
  8092. var node = sel.getRangeAt(0).commonAncestorContainer;
  8093. return contains(this.div, node)
  8094. };
  8095. ContentEditableInput.prototype.focus = function () {
  8096. if (this.cm.options.readOnly != "nocursor") {
  8097. if (!this.selectionInEditor() || document.activeElement != this.div)
  8098. { this.showSelection(this.prepareSelection(), true); }
  8099. this.div.focus();
  8100. }
  8101. };
  8102. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8103. ContentEditableInput.prototype.getField = function () { return this.div };
  8104. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8105. ContentEditableInput.prototype.receivedFocus = function () {
  8106. var input = this;
  8107. if (this.selectionInEditor())
  8108. { this.pollSelection(); }
  8109. else
  8110. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8111. function poll() {
  8112. if (input.cm.state.focused) {
  8113. input.pollSelection();
  8114. input.polling.set(input.cm.options.pollInterval, poll);
  8115. }
  8116. }
  8117. this.polling.set(this.cm.options.pollInterval, poll);
  8118. };
  8119. ContentEditableInput.prototype.selectionChanged = function () {
  8120. var sel = this.getSelection();
  8121. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8122. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8123. };
  8124. ContentEditableInput.prototype.pollSelection = function () {
  8125. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8126. var sel = this.getSelection(), cm = this.cm;
  8127. // On Android Chrome (version 56, at least), backspacing into an
  8128. // uneditable block element will put the cursor in that element,
  8129. // and then, because it's not editable, hide the virtual keyboard.
  8130. // Because Android doesn't allow us to actually detect backspace
  8131. // presses in a sane way, this code checks for when that happens
  8132. // and simulates a backspace press in this case.
  8133. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8134. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8135. this.blur();
  8136. this.focus();
  8137. return
  8138. }
  8139. if (this.composing) { return }
  8140. this.rememberSelection();
  8141. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8142. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8143. if (anchor && head) { runInOp(cm, function () {
  8144. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8145. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8146. }); }
  8147. };
  8148. ContentEditableInput.prototype.pollContent = function () {
  8149. if (this.readDOMTimeout != null) {
  8150. clearTimeout(this.readDOMTimeout);
  8151. this.readDOMTimeout = null;
  8152. }
  8153. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8154. var from = sel.from(), to = sel.to();
  8155. if (from.ch == 0 && from.line > cm.firstLine())
  8156. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8157. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8158. { to = Pos(to.line + 1, 0); }
  8159. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8160. var fromIndex, fromLine, fromNode;
  8161. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8162. fromLine = lineNo(display.view[0].line);
  8163. fromNode = display.view[0].node;
  8164. } else {
  8165. fromLine = lineNo(display.view[fromIndex].line);
  8166. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8167. }
  8168. var toIndex = findViewIndex(cm, to.line);
  8169. var toLine, toNode;
  8170. if (toIndex == display.view.length - 1) {
  8171. toLine = display.viewTo - 1;
  8172. toNode = display.lineDiv.lastChild;
  8173. } else {
  8174. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8175. toNode = display.view[toIndex + 1].node.previousSibling;
  8176. }
  8177. if (!fromNode) { return false }
  8178. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8179. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8180. while (newText.length > 1 && oldText.length > 1) {
  8181. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8182. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8183. else { break }
  8184. }
  8185. var cutFront = 0, cutEnd = 0;
  8186. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8187. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8188. { ++cutFront; }
  8189. var newBot = lst(newText), oldBot = lst(oldText);
  8190. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8191. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8192. while (cutEnd < maxCutEnd &&
  8193. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8194. { ++cutEnd; }
  8195. // Try to move start of change to start of selection if ambiguous
  8196. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8197. while (cutFront && cutFront > from.ch &&
  8198. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8199. cutFront--;
  8200. cutEnd++;
  8201. }
  8202. }
  8203. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8204. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8205. var chFrom = Pos(fromLine, cutFront);
  8206. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8207. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8208. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8209. return true
  8210. }
  8211. };
  8212. ContentEditableInput.prototype.ensurePolled = function () {
  8213. this.forceCompositionEnd();
  8214. };
  8215. ContentEditableInput.prototype.reset = function () {
  8216. this.forceCompositionEnd();
  8217. };
  8218. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8219. if (!this.composing) { return }
  8220. clearTimeout(this.readDOMTimeout);
  8221. this.composing = null;
  8222. this.updateFromDOM();
  8223. this.div.blur();
  8224. this.div.focus();
  8225. };
  8226. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8227. var this$1 = this;
  8228. if (this.readDOMTimeout != null) { return }
  8229. this.readDOMTimeout = setTimeout(function () {
  8230. this$1.readDOMTimeout = null;
  8231. if (this$1.composing) {
  8232. if (this$1.composing.done) { this$1.composing = null; }
  8233. else { return }
  8234. }
  8235. this$1.updateFromDOM();
  8236. }, 80);
  8237. };
  8238. ContentEditableInput.prototype.updateFromDOM = function () {
  8239. var this$1 = this;
  8240. if (this.cm.isReadOnly() || !this.pollContent())
  8241. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8242. };
  8243. ContentEditableInput.prototype.setUneditable = function (node) {
  8244. node.contentEditable = "false";
  8245. };
  8246. ContentEditableInput.prototype.onKeyPress = function (e) {
  8247. if (e.charCode == 0 || this.composing) { return }
  8248. e.preventDefault();
  8249. if (!this.cm.isReadOnly())
  8250. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8251. };
  8252. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8253. this.div.contentEditable = String(val != "nocursor");
  8254. };
  8255. ContentEditableInput.prototype.onContextMenu = function () {};
  8256. ContentEditableInput.prototype.resetPosition = function () {};
  8257. ContentEditableInput.prototype.needsContentAttribute = true;
  8258. function posToDOM(cm, pos) {
  8259. var view = findViewForLine(cm, pos.line);
  8260. if (!view || view.hidden) { return null }
  8261. var line = getLine(cm.doc, pos.line);
  8262. var info = mapFromLineView(view, line, pos.line);
  8263. var order = getOrder(line, cm.doc.direction), side = "left";
  8264. if (order) {
  8265. var partPos = getBidiPartAt(order, pos.ch);
  8266. side = partPos % 2 ? "right" : "left";
  8267. }
  8268. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8269. result.offset = result.collapse == "right" ? result.end : result.start;
  8270. return result
  8271. }
  8272. function isInGutter(node) {
  8273. for (var scan = node; scan; scan = scan.parentNode)
  8274. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8275. return false
  8276. }
  8277. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8278. function domTextBetween(cm, from, to, fromLine, toLine) {
  8279. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8280. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8281. function close() {
  8282. if (closing) {
  8283. text += lineSep;
  8284. if (extraLinebreak) { text += lineSep; }
  8285. closing = extraLinebreak = false;
  8286. }
  8287. }
  8288. function addText(str) {
  8289. if (str) {
  8290. close();
  8291. text += str;
  8292. }
  8293. }
  8294. function walk(node) {
  8295. if (node.nodeType == 1) {
  8296. var cmText = node.getAttribute("cm-text");
  8297. if (cmText) {
  8298. addText(cmText);
  8299. return
  8300. }
  8301. var markerID = node.getAttribute("cm-marker"), range;
  8302. if (markerID) {
  8303. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8304. if (found.length && (range = found[0].find(0)))
  8305. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  8306. return
  8307. }
  8308. if (node.getAttribute("contenteditable") == "false") { return }
  8309. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8310. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8311. if (isBlock) { close(); }
  8312. for (var i = 0; i < node.childNodes.length; i++)
  8313. { walk(node.childNodes[i]); }
  8314. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8315. if (isBlock) { closing = true; }
  8316. } else if (node.nodeType == 3) {
  8317. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8318. }
  8319. }
  8320. for (;;) {
  8321. walk(from);
  8322. if (from == to) { break }
  8323. from = from.nextSibling;
  8324. extraLinebreak = false;
  8325. }
  8326. return text
  8327. }
  8328. function domToPos(cm, node, offset) {
  8329. var lineNode;
  8330. if (node == cm.display.lineDiv) {
  8331. lineNode = cm.display.lineDiv.childNodes[offset];
  8332. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8333. node = null; offset = 0;
  8334. } else {
  8335. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8336. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8337. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8338. }
  8339. }
  8340. for (var i = 0; i < cm.display.view.length; i++) {
  8341. var lineView = cm.display.view[i];
  8342. if (lineView.node == lineNode)
  8343. { return locateNodeInLineView(lineView, node, offset) }
  8344. }
  8345. }
  8346. function locateNodeInLineView(lineView, node, offset) {
  8347. var wrapper = lineView.text.firstChild, bad = false;
  8348. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8349. if (node == wrapper) {
  8350. bad = true;
  8351. node = wrapper.childNodes[offset];
  8352. offset = 0;
  8353. if (!node) {
  8354. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8355. return badPos(Pos(lineNo(line), line.text.length), bad)
  8356. }
  8357. }
  8358. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8359. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8360. textNode = node.firstChild;
  8361. if (offset) { offset = textNode.nodeValue.length; }
  8362. }
  8363. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8364. var measure = lineView.measure, maps = measure.maps;
  8365. function find(textNode, topNode, offset) {
  8366. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8367. var map = i < 0 ? measure.map : maps[i];
  8368. for (var j = 0; j < map.length; j += 3) {
  8369. var curNode = map[j + 2];
  8370. if (curNode == textNode || curNode == topNode) {
  8371. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8372. var ch = map[j] + offset;
  8373. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  8374. return Pos(line, ch)
  8375. }
  8376. }
  8377. }
  8378. }
  8379. var found = find(textNode, topNode, offset);
  8380. if (found) { return badPos(found, bad) }
  8381. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8382. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8383. found = find(after, after.firstChild, 0);
  8384. if (found)
  8385. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8386. else
  8387. { dist += after.textContent.length; }
  8388. }
  8389. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8390. found = find(before, before.firstChild, -1);
  8391. if (found)
  8392. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8393. else
  8394. { dist$1 += before.textContent.length; }
  8395. }
  8396. }
  8397. // TEXTAREA INPUT STYLE
  8398. var TextareaInput = function(cm) {
  8399. this.cm = cm;
  8400. // See input.poll and input.reset
  8401. this.prevInput = "";
  8402. // Flag that indicates whether we expect input to appear real soon
  8403. // now (after some event like 'keypress' or 'input') and are
  8404. // polling intensively.
  8405. this.pollingFast = false;
  8406. // Self-resetting timeout for the poller
  8407. this.polling = new Delayed();
  8408. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8409. this.hasSelection = false;
  8410. this.composing = null;
  8411. };
  8412. TextareaInput.prototype.init = function (display) {
  8413. var this$1 = this;
  8414. var input = this, cm = this.cm;
  8415. this.createField(display);
  8416. var te = this.textarea;
  8417. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8418. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8419. if (ios) { te.style.width = "0px"; }
  8420. on(te, "input", function () {
  8421. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8422. input.poll();
  8423. });
  8424. on(te, "paste", function (e) {
  8425. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8426. cm.state.pasteIncoming = +new Date;
  8427. input.fastPoll();
  8428. });
  8429. function prepareCopyCut(e) {
  8430. if (signalDOMEvent(cm, e)) { return }
  8431. if (cm.somethingSelected()) {
  8432. setLastCopied({lineWise: false, text: cm.getSelections()});
  8433. } else if (!cm.options.lineWiseCopyCut) {
  8434. return
  8435. } else {
  8436. var ranges = copyableRanges(cm);
  8437. setLastCopied({lineWise: true, text: ranges.text});
  8438. if (e.type == "cut") {
  8439. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8440. } else {
  8441. input.prevInput = "";
  8442. te.value = ranges.text.join("\n");
  8443. selectInput(te);
  8444. }
  8445. }
  8446. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8447. }
  8448. on(te, "cut", prepareCopyCut);
  8449. on(te, "copy", prepareCopyCut);
  8450. on(display.scroller, "paste", function (e) {
  8451. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8452. if (!te.dispatchEvent) {
  8453. cm.state.pasteIncoming = +new Date;
  8454. input.focus();
  8455. return
  8456. }
  8457. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8458. var event = new Event("paste");
  8459. event.clipboardData = e.clipboardData;
  8460. te.dispatchEvent(event);
  8461. });
  8462. // Prevent normal selection in the editor (we handle our own)
  8463. on(display.lineSpace, "selectstart", function (e) {
  8464. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8465. });
  8466. on(te, "compositionstart", function () {
  8467. var start = cm.getCursor("from");
  8468. if (input.composing) { input.composing.range.clear(); }
  8469. input.composing = {
  8470. start: start,
  8471. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8472. };
  8473. });
  8474. on(te, "compositionend", function () {
  8475. if (input.composing) {
  8476. input.poll();
  8477. input.composing.range.clear();
  8478. input.composing = null;
  8479. }
  8480. });
  8481. };
  8482. TextareaInput.prototype.createField = function (_display) {
  8483. // Wraps and hides input textarea
  8484. this.wrapper = hiddenTextarea();
  8485. // The semihidden textarea that is focused when the editor is
  8486. // focused, and receives input.
  8487. this.textarea = this.wrapper.firstChild;
  8488. };
  8489. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  8490. // Label for screenreaders, accessibility
  8491. if(label) {
  8492. this.textarea.setAttribute('aria-label', label);
  8493. } else {
  8494. this.textarea.removeAttribute('aria-label');
  8495. }
  8496. };
  8497. TextareaInput.prototype.prepareSelection = function () {
  8498. // Redraw the selection and/or cursor
  8499. var cm = this.cm, display = cm.display, doc = cm.doc;
  8500. var result = prepareSelection(cm);
  8501. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8502. if (cm.options.moveInputWithCursor) {
  8503. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8504. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8505. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8506. headPos.top + lineOff.top - wrapOff.top));
  8507. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8508. headPos.left + lineOff.left - wrapOff.left));
  8509. }
  8510. return result
  8511. };
  8512. TextareaInput.prototype.showSelection = function (drawn) {
  8513. var cm = this.cm, display = cm.display;
  8514. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8515. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8516. if (drawn.teTop != null) {
  8517. this.wrapper.style.top = drawn.teTop + "px";
  8518. this.wrapper.style.left = drawn.teLeft + "px";
  8519. }
  8520. };
  8521. // Reset the input to correspond to the selection (or to be empty,
  8522. // when not typing and nothing is selected)
  8523. TextareaInput.prototype.reset = function (typing) {
  8524. if (this.contextMenuPending || this.composing) { return }
  8525. var cm = this.cm;
  8526. if (cm.somethingSelected()) {
  8527. this.prevInput = "";
  8528. var content = cm.getSelection();
  8529. this.textarea.value = content;
  8530. if (cm.state.focused) { selectInput(this.textarea); }
  8531. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8532. } else if (!typing) {
  8533. this.prevInput = this.textarea.value = "";
  8534. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8535. }
  8536. };
  8537. TextareaInput.prototype.getField = function () { return this.textarea };
  8538. TextareaInput.prototype.supportsTouch = function () { return false };
  8539. TextareaInput.prototype.focus = function () {
  8540. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8541. try { this.textarea.focus(); }
  8542. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8543. }
  8544. };
  8545. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8546. TextareaInput.prototype.resetPosition = function () {
  8547. this.wrapper.style.top = this.wrapper.style.left = 0;
  8548. };
  8549. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8550. // Poll for input changes, using the normal rate of polling. This
  8551. // runs as long as the editor is focused.
  8552. TextareaInput.prototype.slowPoll = function () {
  8553. var this$1 = this;
  8554. if (this.pollingFast) { return }
  8555. this.polling.set(this.cm.options.pollInterval, function () {
  8556. this$1.poll();
  8557. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8558. });
  8559. };
  8560. // When an event has just come in that is likely to add or change
  8561. // something in the input textarea, we poll faster, to ensure that
  8562. // the change appears on the screen quickly.
  8563. TextareaInput.prototype.fastPoll = function () {
  8564. var missed = false, input = this;
  8565. input.pollingFast = true;
  8566. function p() {
  8567. var changed = input.poll();
  8568. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8569. else {input.pollingFast = false; input.slowPoll();}
  8570. }
  8571. input.polling.set(20, p);
  8572. };
  8573. // Read input from the textarea, and update the document to match.
  8574. // When something is selected, it is present in the textarea, and
  8575. // selected (unless it is huge, in which case a placeholder is
  8576. // used). When nothing is selected, the cursor sits after previously
  8577. // seen text (can be empty), which is stored in prevInput (we must
  8578. // not reset the textarea when typing, because that breaks IME).
  8579. TextareaInput.prototype.poll = function () {
  8580. var this$1 = this;
  8581. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8582. // Since this is called a *lot*, try to bail out as cheaply as
  8583. // possible when it is clear that nothing happened. hasSelection
  8584. // will be the case when there is a lot of text in the textarea,
  8585. // in which case reading its value would be expensive.
  8586. if (this.contextMenuPending || !cm.state.focused ||
  8587. (hasSelection(input) && !prevInput && !this.composing) ||
  8588. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8589. { return false }
  8590. var text = input.value;
  8591. // If nothing changed, bail.
  8592. if (text == prevInput && !cm.somethingSelected()) { return false }
  8593. // Work around nonsensical selection resetting in IE9/10, and
  8594. // inexplicable appearance of private area unicode characters on
  8595. // some key combos in Mac (#2689).
  8596. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8597. mac && /[\uf700-\uf7ff]/.test(text)) {
  8598. cm.display.input.reset();
  8599. return false
  8600. }
  8601. if (cm.doc.sel == cm.display.selForContextMenu) {
  8602. var first = text.charCodeAt(0);
  8603. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8604. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8605. }
  8606. // Find the part of the input that is actually new
  8607. var same = 0, l = Math.min(prevInput.length, text.length);
  8608. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8609. runInOp(cm, function () {
  8610. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8611. null, this$1.composing ? "*compose" : null);
  8612. // Don't leave long text in the textarea, since it makes further polling slow
  8613. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8614. else { this$1.prevInput = text; }
  8615. if (this$1.composing) {
  8616. this$1.composing.range.clear();
  8617. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8618. {className: "CodeMirror-composing"});
  8619. }
  8620. });
  8621. return true
  8622. };
  8623. TextareaInput.prototype.ensurePolled = function () {
  8624. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8625. };
  8626. TextareaInput.prototype.onKeyPress = function () {
  8627. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8628. this.fastPoll();
  8629. };
  8630. TextareaInput.prototype.onContextMenu = function (e) {
  8631. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8632. if (input.contextMenuPending) { input.contextMenuPending(); }
  8633. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8634. if (!pos || presto) { return } // Opera is difficult.
  8635. // Reset the current text selection only if the click is done outside of the selection
  8636. // and 'resetSelectionOnContextMenu' option is true.
  8637. var reset = cm.options.resetSelectionOnContextMenu;
  8638. if (reset && cm.doc.sel.contains(pos) == -1)
  8639. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8640. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8641. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8642. input.wrapper.style.cssText = "position: static";
  8643. 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);";
  8644. var oldScrollY;
  8645. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  8646. display.input.focus();
  8647. if (webkit) { window.scrollTo(null, oldScrollY); }
  8648. display.input.reset();
  8649. // Adds "Select all" to context menu in FF
  8650. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8651. input.contextMenuPending = rehide;
  8652. display.selForContextMenu = cm.doc.sel;
  8653. clearTimeout(display.detectingSelectAll);
  8654. // Select-all will be greyed out if there's nothing to select, so
  8655. // this adds a zero-width space so that we can later check whether
  8656. // it got selected.
  8657. function prepareSelectAllHack() {
  8658. if (te.selectionStart != null) {
  8659. var selected = cm.somethingSelected();
  8660. var extval = "\u200b" + (selected ? te.value : "");
  8661. te.value = "\u21da"; // Used to catch context-menu undo
  8662. te.value = extval;
  8663. input.prevInput = selected ? "" : "\u200b";
  8664. te.selectionStart = 1; te.selectionEnd = extval.length;
  8665. // Re-set this, in case some other handler touched the
  8666. // selection in the meantime.
  8667. display.selForContextMenu = cm.doc.sel;
  8668. }
  8669. }
  8670. function rehide() {
  8671. if (input.contextMenuPending != rehide) { return }
  8672. input.contextMenuPending = false;
  8673. input.wrapper.style.cssText = oldWrapperCSS;
  8674. te.style.cssText = oldCSS;
  8675. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8676. // Try to detect the user choosing select-all
  8677. if (te.selectionStart != null) {
  8678. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8679. var i = 0, poll = function () {
  8680. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8681. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8682. operation(cm, selectAll)(cm);
  8683. } else if (i++ < 10) {
  8684. display.detectingSelectAll = setTimeout(poll, 500);
  8685. } else {
  8686. display.selForContextMenu = null;
  8687. display.input.reset();
  8688. }
  8689. };
  8690. display.detectingSelectAll = setTimeout(poll, 200);
  8691. }
  8692. }
  8693. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8694. if (captureRightClick) {
  8695. e_stop(e);
  8696. var mouseup = function () {
  8697. off(window, "mouseup", mouseup);
  8698. setTimeout(rehide, 20);
  8699. };
  8700. on(window, "mouseup", mouseup);
  8701. } else {
  8702. setTimeout(rehide, 50);
  8703. }
  8704. };
  8705. TextareaInput.prototype.readOnlyChanged = function (val) {
  8706. if (!val) { this.reset(); }
  8707. this.textarea.disabled = val == "nocursor";
  8708. this.textarea.readOnly = !!val;
  8709. };
  8710. TextareaInput.prototype.setUneditable = function () {};
  8711. TextareaInput.prototype.needsContentAttribute = false;
  8712. function fromTextArea(textarea, options) {
  8713. options = options ? copyObj(options) : {};
  8714. options.value = textarea.value;
  8715. if (!options.tabindex && textarea.tabIndex)
  8716. { options.tabindex = textarea.tabIndex; }
  8717. if (!options.placeholder && textarea.placeholder)
  8718. { options.placeholder = textarea.placeholder; }
  8719. // Set autofocus to true if this textarea is focused, or if it has
  8720. // autofocus and no other element is focused.
  8721. if (options.autofocus == null) {
  8722. var hasFocus = activeElt();
  8723. options.autofocus = hasFocus == textarea ||
  8724. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8725. }
  8726. function save() {textarea.value = cm.getValue();}
  8727. var realSubmit;
  8728. if (textarea.form) {
  8729. on(textarea.form, "submit", save);
  8730. // Deplorable hack to make the submit method do the right thing.
  8731. if (!options.leaveSubmitMethodAlone) {
  8732. var form = textarea.form;
  8733. realSubmit = form.submit;
  8734. try {
  8735. var wrappedSubmit = form.submit = function () {
  8736. save();
  8737. form.submit = realSubmit;
  8738. form.submit();
  8739. form.submit = wrappedSubmit;
  8740. };
  8741. } catch(e) {}
  8742. }
  8743. }
  8744. options.finishInit = function (cm) {
  8745. cm.save = save;
  8746. cm.getTextArea = function () { return textarea; };
  8747. cm.toTextArea = function () {
  8748. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8749. save();
  8750. textarea.parentNode.removeChild(cm.getWrapperElement());
  8751. textarea.style.display = "";
  8752. if (textarea.form) {
  8753. off(textarea.form, "submit", save);
  8754. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  8755. { textarea.form.submit = realSubmit; }
  8756. }
  8757. };
  8758. };
  8759. textarea.style.display = "none";
  8760. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8761. options);
  8762. return cm
  8763. }
  8764. function addLegacyProps(CodeMirror) {
  8765. CodeMirror.off = off;
  8766. CodeMirror.on = on;
  8767. CodeMirror.wheelEventPixels = wheelEventPixels;
  8768. CodeMirror.Doc = Doc;
  8769. CodeMirror.splitLines = splitLinesAuto;
  8770. CodeMirror.countColumn = countColumn;
  8771. CodeMirror.findColumn = findColumn;
  8772. CodeMirror.isWordChar = isWordCharBasic;
  8773. CodeMirror.Pass = Pass;
  8774. CodeMirror.signal = signal;
  8775. CodeMirror.Line = Line;
  8776. CodeMirror.changeEnd = changeEnd;
  8777. CodeMirror.scrollbarModel = scrollbarModel;
  8778. CodeMirror.Pos = Pos;
  8779. CodeMirror.cmpPos = cmp;
  8780. CodeMirror.modes = modes;
  8781. CodeMirror.mimeModes = mimeModes;
  8782. CodeMirror.resolveMode = resolveMode;
  8783. CodeMirror.getMode = getMode;
  8784. CodeMirror.modeExtensions = modeExtensions;
  8785. CodeMirror.extendMode = extendMode;
  8786. CodeMirror.copyState = copyState;
  8787. CodeMirror.startState = startState;
  8788. CodeMirror.innerMode = innerMode;
  8789. CodeMirror.commands = commands;
  8790. CodeMirror.keyMap = keyMap;
  8791. CodeMirror.keyName = keyName;
  8792. CodeMirror.isModifierKey = isModifierKey;
  8793. CodeMirror.lookupKey = lookupKey;
  8794. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8795. CodeMirror.StringStream = StringStream;
  8796. CodeMirror.SharedTextMarker = SharedTextMarker;
  8797. CodeMirror.TextMarker = TextMarker;
  8798. CodeMirror.LineWidget = LineWidget;
  8799. CodeMirror.e_preventDefault = e_preventDefault;
  8800. CodeMirror.e_stopPropagation = e_stopPropagation;
  8801. CodeMirror.e_stop = e_stop;
  8802. CodeMirror.addClass = addClass;
  8803. CodeMirror.contains = contains;
  8804. CodeMirror.rmClass = rmClass;
  8805. CodeMirror.keyNames = keyNames;
  8806. }
  8807. // EDITOR CONSTRUCTOR
  8808. defineOptions(CodeMirror);
  8809. addEditorMethods(CodeMirror);
  8810. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8811. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8812. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8813. { CodeMirror.prototype[prop] = (function(method) {
  8814. return function() {return method.apply(this.doc, arguments)}
  8815. })(Doc.prototype[prop]); } }
  8816. eventMixin(Doc);
  8817. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8818. // Extra arguments are stored as the mode's dependencies, which is
  8819. // used by (legacy) mechanisms like loadmode.js to automatically
  8820. // load a mode. (Preferred mechanism is the require/define calls.)
  8821. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8822. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  8823. defineMode.apply(this, arguments);
  8824. };
  8825. CodeMirror.defineMIME = defineMIME;
  8826. // Minimal default mode.
  8827. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8828. CodeMirror.defineMIME("text/plain", "null");
  8829. // EXTENSIONS
  8830. CodeMirror.defineExtension = function (name, func) {
  8831. CodeMirror.prototype[name] = func;
  8832. };
  8833. CodeMirror.defineDocExtension = function (name, func) {
  8834. Doc.prototype[name] = func;
  8835. };
  8836. CodeMirror.fromTextArea = fromTextArea;
  8837. addLegacyProps(CodeMirror);
  8838. CodeMirror.version = "5.59.1";
  8839. return CodeMirror;
  8840. })));